Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 83 additions & 2 deletions tests/support/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
Expand All @@ -20,7 +20,7 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

Check warning on line 23 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

line too long (81 > 80 characters)
#
# -- END_HEADER ---
#
Expand All @@ -46,6 +46,21 @@

from tests.support._env import MIG_ENV, PY2

# Alow the use of SimpleNamespace on PY2.

if PY2:
class SimpleNamespace(dict):
"""Bare minimum SimpleNamespace for Python 2."""

def __getattribute__(self, name):
if name == '__dict__':
return dict(**self)

return self[name]
else:
from types import SimpleNamespace


# Provide access to a configuration file for the active environment.

if MIG_ENV in ('local', 'docker'):
Expand All @@ -60,7 +75,7 @@

# adjust the link through which confs are accessed to suit the environment
_conf_link = os.path.join(_output_dir, 'testconfs')
assert os.path.lexists(_conf_link) # it must already exist

Check warning on line 78 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

at least two spaces before inline comment
os.remove(_conf_link) # blow it away
os.symlink(_conf_dir, _conf_link) # recreate it using the active MIG_BASE
else:
Expand All @@ -86,10 +101,10 @@

# Exports to expose at the top level from the support library.

from tests.support.assertover import AssertOver

Check warning on line 104 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

module level import not at top of file
from tests.support.configsupp import FakeConfiguration

Check warning on line 105 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

module level import not at top of file
from tests.support.loggersupp import FakeLogger

Check warning on line 106 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

module level import not at top of file
from tests.support.serversupp import make_wrapped_server

Check warning on line 107 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

module level import not at top of file


# Basic global logging configuration for testing
Expand All @@ -98,7 +113,7 @@
class BlackHole:
"""Arrange a stream that ignores all logging messages"""

def write(self, message):

Check failure on line 116 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

unused method 'write' (60% confidence)
"""NoOp to fake write"""
pass

Expand Down Expand Up @@ -192,10 +207,10 @@
return FakeConfiguration()
elif configuration_to_make == 'testconfig':
from mig.shared.conf import get_configuration_object
return get_configuration_object(skip_log=True, disable_auth_log=True)

Check warning on line 210 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

line too long (81 > 80 characters)
else:
raise AssertionError(
"MigTestCase: unknown configuration %r" % (configuration_to_make,))

Check warning on line 213 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

line too long (83 > 80 characters)

def _provide_configuration(self):
return 'fakeconfig'
Expand Down Expand Up @@ -224,7 +239,7 @@
return configuration_instance


@property

Check warning on line 242 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

too many blank lines (2)
def logger(self):
"""Init a fake logger if not already done"""
if self._logger is None:
Expand All @@ -237,11 +252,14 @@
self._register_check(check_callable)
return assert_over

def temppath(self, relative_path, **kwargs):
return temppath(relative_path, self, **kwargs)

# custom assertions available for common use

def assertFileContentIdentical(self, file_actual, file_expected):

Check failure on line 260 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

unused method 'assertFileContentIdentical' (60% confidence)
"""Make sure file_actual and file_expected are identical"""
with io.open(file_actual) as f_actual, io.open(file_expected) as f_expected:

Check warning on line 262 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

line too long (84 > 80 characters)
lhs = f_actual.readlines()
rhs = f_expected.readlines()
different_lines = list(difflib.unified_diff(rhs, lhs))
Expand All @@ -258,7 +276,7 @@
os.path.relpath(file_actual, MIG_BASE),
''.join(different_lines)))

def assertFileExists(self, relative_path):

Check failure on line 279 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

unused method 'assertFileExists' (60% confidence)
"""Make sure relative_path exists and is a file"""
path_kind = self.assertPathExists(relative_path)
assert path_kind == "file", "expected a file but found %s" % (
Expand All @@ -282,19 +300,82 @@
else:
return "file"

def assertPathWithin(self, path, start=None):

Check failure on line 303 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

unused method 'assertPathWithin' (60% confidence)
"""Make sure path is within start directory"""
if not is_path_within(path, start=start):
raise AssertionError(
"path %s is not within directory %s" % (path, start))

@staticmethod

Check failure on line 309 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

unused method 'pretty_display_path' (60% confidence)
def pretty_display_path(absolute_path):
assert os.path.isabs(absolute_path)
relative_path = os.path.relpath(absolute_path, start=MIG_BASE)
assert not relative_path.startswith('..')
return relative_path

def prepareFixtureAssert(self, fixture_relpath, fixture_format=None):
"""Prepare to assert a value against a fixture."""

fixture_data, fixture_path = fixturefile(
fixture_relpath, fixture_format)
return SimpleNamespace(
assertAgainstFixture=lambda val: MigTestCase._assertAgainstFixture(
self,
fixture_format,
fixture_data,
fixture_path,
value=val
),
copy_as_temp=lambda prefix: self._fixture_copy_as_temp(
self,
fixture_format,
fixture_data,
fixture_path,
prefix=prefix
)
)

@staticmethod
def _assertAgainstFixture(testcase, fixture_format, fixture_data, fixture_path, value=None):
"""Compare a value against fixture data ensuring that in the case of
failure the location of the fixture is prepended to the diff."""

assert value is not None
originalMaxDiff = testcase.maxDiff
testcase.maxDiff = None

raised_exception = None
try:
testcase.assertEqual(value, fixture_data)
except AssertionError as diffexc:
raised_exception = diffexc
finally:
testcase.maxDiff = originalMaxDiff
if raised_exception:
message = "value differed from fixture stored at %s\n\n%s" % (
_to_display_path(fixture_path), raised_exception)
raise AssertionError(message)

@staticmethod
def _fixture_copy_as_temp(testcase, fixture_format, fixture_data, fixture_path, prefix=None):
"""Copy a fixture to temporary file at the given path prefix."""

assert prefix is not None
fixture_basename = os.path.basename(fixture_path)
fixture_name = fixture_basename[0:-len(fixture_format) - 1]
normalised_path = fixturefile_normname(fixture_name, prefix=prefix)
copied_fixture_file = testcase.temppath(normalised_path)
shutil.copyfile(fixture_path, copied_fixture_file)
return copied_fixture_file


def _to_display_path(value):
"""Convert a relative path to one to be shown as part of test output."""
display_path = os.path.relpath(value, MIG_BASE)
if not display_path.startswith('.'):
return "./" + display_path
return display_path


def is_path_within(path, start=None, _msg=None):
"""Check if path is within start directory"""
Expand All @@ -316,7 +397,7 @@
return absolute_dir


def fixturefile(relative_path, fixture_format=None, include_path=False):
def fixturefile(relative_path, fixture_format=None):
"""Support function for loading fixtures from their serialised format.

Doing so is a little more involved than it may seem because serialisation
Expand Down Expand Up @@ -347,7 +428,7 @@
raise AssertionError(
"unsupported fixture format: %s" % (fixture_format,))

return (data, tmp_path) if include_path else data
return data, tmp_path


def fixturefile_normname(relative_path, prefix=''):
Expand Down Expand Up @@ -385,7 +466,7 @@
return json_object


def fixturepath(relative_path):

Check failure on line 469 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

unused function 'fixturepath' (60% confidence)
"""Get absolute fixture path for relative_path"""
tmp_path = os.path.join(TEST_FIXTURE_DIR, relative_path)
return tmp_path
Expand Down Expand Up @@ -429,5 +510,5 @@


# compatibility alias
def cleanpath(relative_path, test_case, **kwargs):

Check failure on line 513 in tests/support/__init__.py

View workflow job for this annotation

GitHub Actions / Style Check Python with Lint

unused function 'cleanpath' (60% confidence)
return temppath(relative_path, test_case, **kwargs)
7 changes: 3 additions & 4 deletions tests/test_mig_shared_configuration.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-
#
# --- BEGIN_HEADER ---
Expand Down Expand Up @@ -31,7 +31,7 @@
import os
import unittest

from tests.support import MigTestCase, TEST_DATA_DIR, PY2, testmain, fixturefile
from tests.support import MigTestCase, TEST_DATA_DIR, PY2, testmain
from mig.shared.configuration import Configuration


Expand Down Expand Up @@ -71,7 +71,7 @@

@unittest.skipIf(PY2, "Python 3 only")
def test_default_object(self):
expected_values = fixturefile(
prepared_fixture = self.prepareFixtureAssert(
'mig_shared_configuration--new', fixture_format='json')

configuration = Configuration(None)
Expand All @@ -84,8 +84,7 @@

actual_values = _to_dict(configuration)

self.maxDiff = None
self.assertEqual(actual_values, expected_values)
prepared_fixture.assertAgainstFixture(actual_values)

def test_object_isolation(self):
configuration_1 = Configuration(None)
Expand Down
15 changes: 7 additions & 8 deletions tests/test_mig_shared_functionality_cat.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-
#
# --- BEGIN_HEADER ---
Expand Down Expand Up @@ -35,7 +35,7 @@
import unittest

from tests.support import MIG_BASE, PY2, TEST_DATA_DIR, MigTestCase, testmain, \
fixturefile, fixturefile_normname, ensure_dirs_exist, temppath
temppath, ensure_dirs_exist

from mig.shared.base import client_id_dir
from mig.shared.functionality.cat import _main as submain, main as realmain
Expand Down Expand Up @@ -78,13 +78,12 @@

conf_user_db_home = ensure_dirs_exist(self.configuration.user_db_home)
temppath(conf_user_db_home, self)
db_fixture, db_fixture_file = fixturefile('MiG-users.db--example',
fixture_format='binary',
include_path=True)
test_db_file = temppath(fixturefile_normname('MiG-users.db--example',
prefix=conf_user_db_home),
self)
shutil.copyfile(db_fixture_file, test_db_file)
prepared_fixture = self.prepareFixtureAssert(
'MiG-users.db--example',
fixture_format='binary',
)

test_db_file = prepared_fixture.copy_as_temp(prefix=conf_user_db_home)

# create the test user home directory
self.test_user_dir = ensure_dirs_exist(test_user_dir)
Expand Down
Loading