diff options
author | Arthur Zamarin <arthurzam@gentoo.org> | 2022-08-27 10:59:39 +0300 |
---|---|---|
committer | Arthur Zamarin <arthurzam@gentoo.org> | 2022-08-27 11:32:24 +0300 |
commit | bab590f912d12c35fd7809cabf692bc12d5bce9b (patch) | |
tree | 2223debaee7d41f8dcbc561bcede0b4ccd0a4abc /tests | |
parent | resolver/test_*.py: modernize tests to pytest (diff) | |
download | pkgcore-bab590f912d12c35fd7809cabf692bc12d5bce9b.tar.gz pkgcore-bab590f912d12c35fd7809cabf692bc12d5bce9b.tar.bz2 pkgcore-bab590f912d12c35fd7809cabf692bc12d5bce9b.zip |
test/**.py: modernize tests to pytest
Signed-off-by: Arthur Zamarin <arthurzam@gentoo.org>
Diffstat (limited to 'tests')
-rw-r--r-- | tests/cache/test_base.py | 4 | ||||
-rw-r--r-- | tests/ebuild/test_digest.py | 7 | ||||
-rw-r--r-- | tests/ebuild/test_filter_env.py | 387 | ||||
-rw-r--r-- | tests/ebuild/test_formatter.py | 74 | ||||
-rw-r--r-- | tests/fetch/test_init.py | 125 | ||||
-rw-r--r-- | tests/fs/test_contents.py | 412 | ||||
-rw-r--r-- | tests/package/test_base.py | 15 |
7 files changed, 482 insertions, 542 deletions
diff --git a/tests/cache/test_base.py b/tests/cache/test_base.py index 4ed852b1..6b3fdc22 100644 --- a/tests/cache/test_base.py +++ b/tests/cache/test_base.py @@ -79,7 +79,7 @@ class DictCacheBulk(bulk): return iter(self._data.keys()) -class BaseTest: +class TestBase: cache_keys = ("foo", "_eclasses_") @@ -178,7 +178,7 @@ class BaseTest: assert len(tracker) == 3 -class TestBulk(BaseTest): +class TestBulk(TestBase): def get_db(self, readonly=False): return DictCacheBulk(auxdbkeys=self.cache_keys, diff --git a/tests/ebuild/test_digest.py b/tests/ebuild/test_digest.py index 8163bc3c..86d32e47 100644 --- a/tests/ebuild/test_digest.py +++ b/tests/ebuild/test_digest.py @@ -4,7 +4,6 @@ import tempfile from pkgcore import gpg from pkgcore.ebuild import digest from snakeoil.data_source import local_source -from snakeoil.test import TestCase # "Line too long" (and our custom more aggressive version of that) # pylint: disable-msg=C0301,CPC01 @@ -49,7 +48,7 @@ for x in pure_manifest2.split("\n"): del chksum, l, i -class TestManifest(TestCase): +class TestManifest: convert_source = staticmethod(lambda x:x) @@ -78,11 +77,11 @@ class TestManifest(TestCase): for dtype, d in (("DIST", dist), ("AUX", aux), ("EBUILD", ebuild), ("MISC", misc)): req_d = pure_manifest2_chksums[dtype] - self.assertEqual(sorted(req_d), sorted(d)) + assert set(req_d) == set(d) for k, v in req_d.items(): i1 = sorted(v) i2 = sorted(d[k].items()) - self.assertEqual(i1, i2, msg="{i1!r} != {i2!r}\nfor {dtype} {k}") + assert i1 == i2 class TestManifestDataSource(TestManifest): diff --git a/tests/ebuild/test_filter_env.py b/tests/ebuild/test_filter_env.py index 0fbb49ec..89d91f5c 100644 --- a/tests/ebuild/test_filter_env.py +++ b/tests/ebuild/test_filter_env.py @@ -1,13 +1,11 @@ import io -from functools import partial +import textwrap -from pkgcore.ebuild import filter_env -from snakeoil.test import TestCase +import pytest +from pkgcore.ebuild.filter_env import main_run -class TestFilterEnv(TestCase): - - filter_env = staticmethod(partial(filter_env.main_run)) +class TestFilterEnv: def get_output(self, raw_data, funcs=None, vars=None, preserve_funcs=False, preserve_vars=False, debug=False, global_envvar_callback=None): @@ -16,230 +14,211 @@ class TestFilterEnv(TestCase): funcs = funcs.split(',') if vars: vars = vars.split(',') - self.filter_env(out, raw_data, vars, funcs, preserve_vars, preserve_funcs, + main_run(out, raw_data, vars, funcs, preserve_vars, preserve_funcs, global_envvar_callback=global_envvar_callback) return out.getvalue().decode('utf-8') def test_function_foo(self): ret = ''.join(self.get_output("function foo() {:;}", funcs="foo")) - self.assertEqual(ret, '') + assert ret == '' ret = ''.join(self.get_output("functionfoo() {:;}", funcs="foo")) - self.assertEqual(ret, 'functionfoo() {:;}') + assert ret == 'functionfoo() {:;}' def test_simple(self): - data = \ -""" -foo() { - : -} - -bar() { - : -} -""" + data = textwrap.dedent("""\ + foo() { + : + } + + bar() { + : + } + """) ret = ''.join(self.get_output(data)) - self.assertIn('foo', ret) - self.assertIn('bar', ret) + assert 'foo' in ret + assert 'bar' in ret ret = ''.join(self.get_output(data, funcs='foo')) - self.assertNotIn('foo', ret) - self.assertIn('bar', ret) + assert 'foo' not in ret + assert 'bar' in ret ret = ''.join(self.get_output(data, funcs='bar')) - self.assertIn('foo', ret) - self.assertNotIn('bar', ret) + assert 'foo' in ret + assert 'bar' not in ret ret = ''.join(self.get_output(data, funcs='bar,foo')) - self.assertNotIn('foo', ret) - self.assertNotIn('bar', ret) + assert 'foo' not in ret + assert 'bar' not in ret def test1(self): - data = \ -""" -MODULE_NAMES=${MODULE_NAMES//${i}(*}; -tc-arch () -{ - tc-ninja_magic_to_arch portage $@ -} -""" + data = textwrap.dedent("""\ + MODULE_NAMES=${MODULE_NAMES//${i}(*}; + tc-arch () + { + tc-ninja_magic_to_arch portage $@ + } + """) ret = ''.join(self.get_output(data, vars='MODULE_NAMES')) - self.assertNotIn('MODULE_NAMES', ret) - self.assertIn('tc-arch', ret) + assert 'MODULE_NAMES' not in ret + assert 'tc-arch' in ret def test_comments(self): data = "dar=${yar##.%}\nfoo() {\n:\n}\n" ret = ''.join(self.get_output(data, vars='dar')) - self.assertNotIn('dar', ret) - self.assertIn('foo', ret) - - data = \ -""" -src_unpack() { - use idn && { - # BIND 9.4.0 doesn't have this patch - : - } -} - -src_compile() { - : -} -""" - self.assertIn('src_unpack', ''.join( - self.get_output(data, funcs='src_compile'))) + assert 'dar' not in ret + assert 'foo' in ret + + data = textwrap.dedent("""\ + src_unpack() { + use idn && { + # BIND 9.4.0 doesn't have this patch + : + } + } + + src_compile() { + : + } + """) + assert 'src_unpack' in ''.join(self.get_output(data, funcs='src_compile')) ret = ''.join(self.get_output(data, funcs='src_unpack')) - self.assertIn('src_compile', ret) - self.assertNotIn('src_unpack', ret) - data = \ -"""src_install() { - local -f ${f##*=} -} - -pkg_postinst() { - : -} -""" - self.assertNotIn('pkg_postinst', - ''.join(self.get_output(data, funcs='pkg_postinst'))) - data = \ -"""src_unpack() { - fnames=$(scanelf -pyqs__uClibc_start_main -F%F#s) -} -src_compile() { - : -} -""" - self.assertIn('src_compile', - ''.join(self.get_output(data, funcs='src_unpack'))) - - data = \ -"""findtclver() { - [ "$(#i)" = "3" ] -} - -pkg_setup() { - : -} -""" - self.assertIn('pkg_setup', - ''.join(self.get_output(data, funcs='findtclver'))) + assert 'src_compile' in ret + assert 'src_unpack' not in ret + data = textwrap.dedent("""\ + src_install() { + local -f ${f##*=} + } + + pkg_postinst() { + : + } + """) + assert 'pkg_postinst' not in ''.join(self.get_output(data, funcs='pkg_postinst')) + data = textwrap.dedent("""\ + src_unpack() { + fnames=$(scanelf -pyqs__uClibc_start_main -F%F#s) + } + src_compile() { + : + } + """) + assert 'src_compile' in ''.join(self.get_output(data, funcs='src_unpack')) + + data = textwrap.dedent("""\ + findtclver() { + [ "$(#i)" = "3" ] + } + + pkg_setup() { + : + } + """) + assert 'pkg_setup' in ''.join(self.get_output(data, funcs='findtclver')) def test_here(self): - data = \ -""" -src_install() { - cat >${D}/etc/modules.d/davfs2 <<EOF -alias char-major-67 coda -alias /dev/davfs* coda -EOF -} - -pkg_setup() { - : -} -""" - self.assertNotIn('pkg_setup', ''.join(self.get_output(data, - funcs='pkg_setup'))) - - data = \ -""" -pkg_setup() { - while read line; do elog "${line}"; done <<EOF -The default behaviour of tcsh has significantly changed starting from -version 6.14-r1. In contrast to previous ebuilds, the amount of -customisation to the default shell's behaviour has been reduced to a -bare minimum (a customised prompt). -If you rely on the customisations provided by previous ebuilds, you will -have to copy over the relevant (now commented out) parts to your own -~/.tcshrc. Please check all tcsh-* files in -/usr/share/doc/${P}/examples/ and include their behaviour in your own -configuration files. -The tcsh-complete file is not any longer sourced by the default system -scripts. -EOF -} - -pkg_foo() { - : -} -""" - self.assertNotIn('pkg_foo', ''.join(self.get_output(data, - funcs='pkg_foo'))) + data = textwrap.dedent("""\ + src_install() { + cat >${D}/etc/modules.d/davfs2 <<EOF + alias char-major-67 coda + alias /dev/davfs* coda + EOF + } + + pkg_setup() { + : + } + """) + assert 'pkg_setup' not in ''.join(self.get_output(data, funcs='pkg_setup')) + + data = textwrap.dedent("""\ + pkg_setup() { + while read line; do elog "${line}"; done <<EOF + The default behaviour of tcsh has significantly changed starting from + version 6.14-r1. In contrast to previous ebuilds, the amount of + customisation to the default shell's behaviour has been reduced to a + bare minimum (a customised prompt). + If you rely on the customisations provided by previous ebuilds, you will + have to copy over the relevant (now commented out) parts to your own + ~/.tcshrc. Please check all tcsh-* files in + /usr/share/doc/${P}/examples/ and include their behaviour in your own + configuration files. + The tcsh-complete file is not any longer sourced by the default system + scripts. + EOF + } + + pkg_foo() { + : + } + """) + assert 'pkg_foo' not in ''.join(self.get_output(data, funcs='pkg_foo')) def test_vars(self): - data = \ -""" -f() { - x=$y -} - -z() { - : -} -""" - self.assertIn('z', ''.join(self.get_output(data, - funcs='f'))) - - data = \ -""" -f() { - x="${y}" -} - -z() { - : -} -""" - self.assertIn('z', ''.join(self.get_output(data, - funcs='f'))) - - data = \ -"""src_compile() { - $(ABI=foo get_libdir) -} - -pkg_setup() { - : -} -""" - self.assertIn('pkg_setup', ''.join(self.get_output(data, - funcs='src_compile'))) + data = textwrap.dedent("""\ + f() { + x=$y + } + + z() { + : + } + """) + assert 'z' in ''.join(self.get_output(data, funcs='f')) + + data = textwrap.dedent("""\ + f() { + x="${y}" + } + + z() { + : + } + """) + assert 'z' in ''.join(self.get_output(data, funcs='f')) + + data = textwrap.dedent("""\ + src_compile() { + $(ABI=foo get_libdir) + } + + pkg_setup() { + : + } + """) + assert 'pkg_setup' in ''.join(self.get_output(data, funcs='src_compile')) def test_quoting(self): - data = \ -""" -pkg_postinst() { - einfo " /bin/ls ${ROOT}etc/init.d/net.* | grep -v '/net.lo$' | xargs -n1 ln -sfvn net.lo" -} - -pkg_setup() { - : -} -""" - self.assertIn('pkg_setup', ''.join(self.get_output(data, - funcs='pkg_postinst'))) - - data = \ -"""src_unpack() { - testExp=$'\177\105\114\106\001\001\001' -} - -src_install() { - : -} -""" - self.assertIn('src_install', ''.join(self.get_output(data, - funcs='src_unpack'))) + data = textwrap.dedent("""\ + pkg_postinst() { + einfo " /bin/ls ${ROOT}etc/init.d/net.* | grep -v '/net.lo$' | xargs -n1 ln -sfvn net.lo" + } + + pkg_setup() { + : + } + """) + assert 'pkg_setup' in ''.join(self.get_output(data, funcs='pkg_postinst')) + + data = textwrap.dedent("""\ + src_unpack() { + testExp=$'\177\105\114\106\001\001\001' + } + + src_install() { + : + } + """) + assert 'src_install' in ''.join(self.get_output(data, funcs='src_unpack')) def test_arg_awareness(self): data = "f() {\n x \\{}\n}\n" - self.assertNotIn('}', ''.join(self.get_output(data, 'f'))) - - def test_print_vars(self): - def assertVars(data, var_list, assert_func=self.assertEqual): - l = [] - self.get_output(data, global_envvar_callback=l.append) - assert_func(sorted(var_list), sorted(l)) - assertVars("f(){\nX=dar\n}", []) - assertVars("f(){\nX=dar\n}\nY=a", ['Y']) - assertVars("f(){\nX=dar\n}\nmy command\nY=a\nf=$(dar)", ['Y', 'f']) - assertVars("f(){\nX=dar\n}\nmy command\nY=a\nf=$(dar) foon\n", ['Y'], - self.assertNotEqual) - assertVars("f(){\nX=dar foon\n}\nY=dar\nf2(){Z=dar;}\n", ['Y']) + assert '}' not in ''.join(self.get_output(data, 'f')) + + @pytest.mark.parametrize(("data", "var_list"), ( + ("f(){\nX=dar\n}", set()), + ("f(){\nX=dar\n}\nY=a", {'Y'}), + ("f(){\nX=dar\n}\nmy command\nY=a\nf=$(dar)", {'Y', 'f'}), + ("f(){\nX=dar\n}\nmy command\nY=a\nf=$(dar) foon\n", {'Y', 'f'}), + ("f(){\nX=dar foon\n}\nY=dar\nf2(){Z=dar;}\n", {'Y'}) + )) + def test_print_vars(self, data, var_list): + l = set() + self.get_output(data, global_envvar_callback=l.add) + assert var_list == l diff --git a/tests/ebuild/test_formatter.py b/tests/ebuild/test_formatter.py index 3b406173..ec897b2c 100644 --- a/tests/ebuild/test_formatter.py +++ b/tests/ebuild/test_formatter.py @@ -1,9 +1,6 @@ -import difflib - from pkgcore.ebuild.atom import atom from pkgcore.ebuild.formatter import BasicFormatter, PkgcoreFormatter, PortageFormatter from pkgcore.test.misc import FakePkg, FakeRepo -from snakeoil.test import TestCase from snakeoil.test.argparse_helpers import Bold, Color, FakeStreamFormatter, Reset @@ -35,7 +32,8 @@ class FakeOp: class BaseFormatterTest: prefix = () suffix = ('\n',) - def setUp(self): + + def setup_method(self): self.fakeout = FakeStreamFormatter() self.fakeerr = FakeStreamFormatter() self.formatter = self.newFormatter() @@ -47,14 +45,12 @@ class BaseFormatterTest: autoline = self.fakeout.autoline try: ret = self.formatterClass.format(internal_self, *args, **kwds) - except Exception as e: - self.assertEqual( - autoline, self.fakeout.autoline, - msg="exception thrown {e}, autoline was {autoline}, now is {self.fakeout.autoline}") + except Exception as exc: + assert autoline == self.fakeout.autoline, \ + f"exception thrown {exc}, autoline was {autoline}, now is {self.fakeout.autoline}" raise - self.assertEqual( - autoline, self.fakeout.autoline, - msg="autoline was {autoline}, now is {self.fakeout.autoline}") + assert autoline == self.fakeout.autoline, \ + f"autoline was {autoline}, now is {self.fakeout.autoline}" return ret return state_verifying_class @@ -70,12 +66,12 @@ class BaseFormatterTest: def assertOut(self, *args, **kwargs): - stringlist = [] - objectlist = [] + strings = [] + objects = [] args = list(args) - prefix = kwargs.setdefault("prefix", self.prefix) + prefix = kwargs.get("prefix", self.prefix) if isinstance(prefix, tuple): args = list(prefix) + args elif isinstance(prefix, list): @@ -83,7 +79,7 @@ class BaseFormatterTest: else: args.insert(0, prefix) - suffix = kwargs.setdefault("suffix", self.suffix) + suffix = kwargs.get("suffix", self.suffix) if isinstance(suffix, tuple): args = args + list(suffix) elif isinstance(suffix, list): @@ -93,24 +89,20 @@ class BaseFormatterTest: for arg in args: if isinstance(arg, str): - stringlist.append(arg.encode('ascii')) + strings.append(arg.encode('utf-8')) elif isinstance(arg, bytes): - stringlist.append(arg) + strings.append(arg) else: - objectlist.append(b''.join(stringlist)) - stringlist = [] - objectlist.append(arg) - objectlist.append(b''.join(stringlist)) + objects.append(b''.join(strings)) + strings = [] + objects.append(arg) + objects.append(b''.join(strings)) # Hack because a list with an empty string in is True - if objectlist == [b'']: - objectlist = [] - - self.assertEqual(self.fakeout.stream, objectlist, '\n' + '\n'.join( - difflib.unified_diff( - list(repr(s) for s in objectlist), - list(repr(s) for s in self.fakeout.stream), - 'expected', 'actual', lineterm=''))) + if objects == [b'']: + objects = [] + + assert self.fakeout.stream == objects self.fakeout.resetstream() def test_end(self): @@ -121,7 +113,7 @@ class BaseFormatterTest: self.assertOut(suffix=()) -class TestBasicFormatter(BaseFormatterTest, TestCase): +class TestBasicFormatter(BaseFormatterTest): formatterClass = BasicFormatter @@ -137,7 +129,7 @@ class TestBasicFormatter(BaseFormatterTest, TestCase): self.assertOut('app-arch/bzip2') -class TestPkgcoreFormatter(BaseFormatterTest, TestCase): +class TestPkgcoreFormatter(BaseFormatterTest): formatterClass = PkgcoreFormatter @@ -175,12 +167,12 @@ class CountingFormatterTest(BaseFormatterTest): def newFormatter(self, **kwargs): kwargs.setdefault('verbosity', 1) - return BaseFormatterTest.newFormatter(self, **kwargs) + return super().newFormatter(**kwargs) def assertEnd(self, *args, **kwargs): kwargs.setdefault('prefix', self.endprefix) kwargs.setdefault('suffix', self.endsuffix) - BaseFormatterTest.assertOut(self, *args, **kwargs) + super().assertOut(*args, **kwargs) def test_end(self): self.formatter.end() @@ -295,11 +287,11 @@ class CountingFormatterTest(BaseFormatterTest): '\nTotal: 5 packages (1 new, 1 upgrade, 1 downgrade, 1 in new slot, 1 reinstall)') -class TestPortageFormatter(BaseFormatterTest, TestCase): +class TestPortageFormatter(BaseFormatterTest): formatterClass = PortageFormatter - def setUp(self): + def setup_method(self): pkg = FakeMutatedPkg('app-arch/bzip2-1.0.1-r1', slot='0') masked_atom = atom('>=app-arch/bzip2-2.0') self.domain_settings = {"ACCEPT_KEYWORDS": ("amd64",)} @@ -310,12 +302,12 @@ class TestPortageFormatter(BaseFormatterTest, TestCase): repo_id='repo2', location='/var/gentoo/repos/repo2', domain_settings=self.domain_settings) self.vdb = FakeRepo(repo_id='vdb', pkgs=[pkg]) - BaseFormatterTest.setUp(self) + super().setup_method() def newFormatter(self, **kwargs): kwargs.setdefault('quiet_repo_display', False) kwargs.setdefault('installed_repos', self.vdb) - return BaseFormatterTest.newFormatter(self, **kwargs) + return super().newFormatter(**kwargs) def repo_id(self, repo): if getattr(self.formatter, 'verbosity', 0): @@ -583,7 +575,7 @@ class TestPortageVerboseFormatter(TestPortageFormatter): def newFormatter(self, **kwargs): kwargs.setdefault("verbosity", 1) kwargs.setdefault("unstable_arch", "~amd64") - return TestPortageFormatter.newFormatter(self, **kwargs) + return super().newFormatter(**kwargs) def test_install_symbol_unkeyworded(self): self.formatter.format( @@ -751,14 +743,14 @@ class TestPortageVerboseFormatter(TestPortageFormatter): class TestPortageVerboseRepoIdFormatter(TestPortageVerboseFormatter): suffix = [Color("fg", "cyan"), ' [1]\n'] - def setUp(self): - TestPortageVerboseFormatter.setUp(self) + def setup_method(self): + super().setup_method() self.repo3 = FakeRepo( location='/var/gentoo/repos/repo3', domain_settings=self.domain_settings) def newFormatter(self, **kwargs): kwargs.setdefault("quiet_repo_display", True) - return TestPortageVerboseFormatter.newFormatter(self, **kwargs) + return super().newFormatter(**kwargs) def repo_id(self, repo): return '' diff --git a/tests/fetch/test_init.py b/tests/fetch/test_init.py index 554dc6f7..7f69fe15 100644 --- a/tests/fetch/test_init.py +++ b/tests/fetch/test_init.py @@ -1,67 +1,60 @@ +import pytest + from pkgcore import fetch from snakeoil.sequences import iflatten_instance -from snakeoil.test import TestCase - -class base(TestCase): - def assertUri(self, obj, uri): - uri = list(uri) - self.assertEqual(list(iflatten_instance(obj)), uri) - if uri: - self.assertTrue(obj) - else: - self.assertFalse(obj) +def assert_uri(obj, uri): + uri = list(uri) + assert list(iflatten_instance(obj)) == uri + assert bool(uri) == bool(obj) -class TestFetchable(base): +class TestFetchable: def test_init(self): o = fetch.fetchable("dar", uri=["asdf"], chksums={"asdf":1}) - self.assertEqual(o.filename, "dar") - self.assertUri(o.uri, ["asdf"]) - self.assertEqual(o.chksums, {"asdf":1}) + assert o.filename == "dar" + assert_uri(o.uri, ["asdf"]) + assert o.chksums == {"asdf":1} def test_eq_ne(self): o1 = fetch.fetchable("dar", uri=["asdf"], chksums={"asdf":1}) - self.assertEqual(o1, o1) + assert o1 == o1 o2 = fetch.fetchable("dar", uri=["asdf"], chksums={"asdf":1}) - self.assertEqual(o1, o2) - self.assertNotEqual(o1, - fetch.fetchable("dar1", uri=["asdf"], chksums={"asdf":1})) - self.assertNotEqual(o1, - fetch.fetchable("dar", uri=["asdf1"], chksums={"asdf":1})) - self.assertNotEqual(o1, - fetch.fetchable("dar", uri=["asdf1"], chksums={"asdf":1, "foon":1})) + assert o1 == o2 + assert o1 != fetch.fetchable("dar1", uri=["asdf"], chksums={"asdf":1}) + assert o1 != fetch.fetchable("dar", uri=["asdf1"], chksums={"asdf":1}) + assert o1 != fetch.fetchable("dar", uri=["asdf1"], chksums={"asdf":1, "foon":1}) -class TestMirror(base): +class TestMirror: kls = fetch.mirror - default_mirrors = ["http://foon", "ftp://spoon"] - def setUp(self): - self.mirror = self.kls(self.default_mirrors, "fork") - def test_init(self): - self.assertEqual(self.mirror.mirror_name, "fork") + @pytest.fixture + def mirror(self): + return self.kls(self.default_mirrors, "fork") + + def test_init(self, mirror): + assert mirror.mirror_name == "fork" # explicit test should any tuple like sequence show up - self.assertInstance(self.mirror.mirrors, tuple) - self.assertEqual(self.mirror.mirrors, tuple(self.default_mirrors)) + assert isinstance(mirror.mirrors, tuple) + assert mirror.mirrors == tuple(self.default_mirrors) - def test_iter(self): - self.assertEqual(list(self.mirror), self.default_mirrors) + def test_iter(self, mirror): + assert list(mirror) == self.default_mirrors - def test_len(self): - self.assertEqual(len(self.mirror), len(self.default_mirrors)) + def test_len(self, mirror): + assert len(mirror) == len(self.default_mirrors) - def test_getitem(self): - self.assertEqual(self.mirror[1], self.default_mirrors[1]) + def test_getitem(self, mirror): + assert mirror[1] == self.default_mirrors[1] - def test_eq_ne(self): - self.assertEqual(self.mirror, self.kls(self.default_mirrors, 'fork')) - self.assertNotEqual(self.mirror, - self.kls(self.default_mirrors + ['http://fark'], 'fork')) + def test_eq_ne(self, mirror): + assert mirror == self.kls(self.default_mirrors, 'fork') + assert mirror != self.kls(self.default_mirrors + ['http://fark'], 'fork') class TestDefaultMirror(TestMirror): @@ -69,10 +62,11 @@ class TestDefaultMirror(TestMirror): kls = fetch.default_mirror -class Test_uri_list(base): +class Test_uri_list: - def setUp(self): - self.uril = fetch.uri_list("cows") + @pytest.fixture + def uril(self): + return fetch.uri_list("cows") @staticmethod def mk_uri_list(*iterable, **kwds): @@ -85,36 +79,37 @@ class Test_uri_list(base): obj.add_uri(x) return obj - def test_mirrors(self): - self.assertRaises(TypeError, self.uril.add_mirror, "cows") + def test_mirrors(self, uril): + with pytest.raises(TypeError): + uril.add_mirror("cows") mirror = fetch.mirror(["me", "WI"], "asdf") - self.uril.add_mirror(mirror) - self.assertEqual(list(self.uril), ["me/cows", "WI/cows"]) - self.uril.add_mirror(mirror, "foon/boon") - self.assertUri(self.uril, + uril.add_mirror(mirror) + assert list(uril) == ["me/cows", "WI/cows"] + uril.add_mirror(mirror, "foon/boon") + assert_uri(uril, ["me/cows", "WI/cows", "me/foon/boon", "WI/foon/boon"]) - def test_uris(self): - self.uril.add_uri("blar") - self.assertUri(self.uril, ["blar"]) + def test_uris(self, uril): + uril.add_uri("blar") + assert_uri(uril, ["blar"]) - def test_combined(self): + def test_combined(self, uril): l = ["blarn", "me/cows", "WI/cows", "madison", "belleville/cows", "verona/cows"] - self.uril.add_uri("blarn") - self.uril.add_mirror(fetch.mirror(["me", "WI"], "asdf")) - self.uril.add_uri("madison") - self.uril.add_mirror(fetch.default_mirror( + uril.add_uri("blarn") + uril.add_mirror(fetch.mirror(["me", "WI"], "asdf")) + uril.add_uri("madison") + uril.add_mirror(fetch.default_mirror( ["belleville", "verona"], "foon")) - self.assertUri(self.uril, l) + assert_uri(uril, l) def test_nonzero(self): - self.assertTrue(self.mk_uri_list("asdf")) - self.assertFalse(self.mk_uri_list()) - self.assertFalse(self.mk_uri_list(fetch.mirror((), "mirror"))) + assert self.mk_uri_list("asdf") + assert not self.mk_uri_list() + assert not self.mk_uri_list(fetch.mirror((), "mirror")) def test_len(self): - self.assertLen(self.mk_uri_list(), 0) - self.assertLen(self.mk_uri_list("fdas"), 1) - self.assertLen(self.mk_uri_list(fetch.mirror((), "mirror")), 0) - self.assertLen(self.mk_uri_list(fetch.mirror(("asdf",), "mirror")), 1) + assert len(self.mk_uri_list()) == 0 + assert len(self.mk_uri_list("fdas")) == 1 + assert len(self.mk_uri_list(fetch.mirror((), "mirror"))) == 0 + assert len(self.mk_uri_list(fetch.mirror(("asdf",), "mirror"))) == 1 diff --git a/tests/fs/test_contents.py b/tests/fs/test_contents.py index 173b8594..c5c08dc0 100644 --- a/tests/fs/test_contents.py +++ b/tests/fs/test_contents.py @@ -1,10 +1,8 @@ import os from functools import partial +import pytest from pkgcore.fs import contents, fs -from snakeoil.currying import post_curry -from snakeoil.osutils import pjoin -from snakeoil.test import TestCase mk_file = partial(fs.fsFile, strict=False) mk_dir = partial(fs.fsDir, strict=False) @@ -12,149 +10,133 @@ mk_link = partial(fs.fsLink, strict=False) mk_dev = partial(fs.fsDev, strict=False) mk_fifo = partial(fs.fsFifo, strict=False) -for x in ("File", "Dir", "Link", "Dev", "Fifo"): - globals()["mk_" + x.lower()] = partial( - getattr(fs, f"fs{x}"), strict=False) -del x - -class TestContentsSet(TestCase): - - locals().update((x, globals()[x]) for x in - ("mk_file", "mk_dir", "mk_link", "mk_dev", "mk_fifo")) - - def __init__(self, *a, **kw): - TestCase.__init__(self, *a, **kw) - self.files = list(map(self.mk_file, ["/etc/blah", "/etc/foo", "/etc/dar", - "/tmp/dar", - "/tmp/blah/foo/long/ass/file/name/but/not/that/bad/really"])) - self.dirs = list(map(self.mk_dir, ["/tmp", "/blah", "/tmp/dar", - "/usr/", "/usr/bin"])) - self.links = [fs.fsLink(x, os.path.dirname(x), strict=False) for x in - ["/tmp/foo", "/usr/X11R6/lib", "/nagga/noo"]] - self.devs = list(map(self.mk_dev, - [pjoin("dev", x) for x in ["sda1", "hda", "hda2", "disks/ide1"]])) - self.fifos = list(map(self.mk_fifo, - [pjoin("tmp", y) for y in ("dar", "boo", "bah")])) - self.all = self.dirs + self.links + self.devs + self.fifos +class TestContentsSet: + files = list(map(mk_file, ["/etc/blah", "/etc/foo", "/etc/dar", + "/tmp/dar", + "/tmp/blah/foo/long/ass/file/name/but/not/that/bad/really"])) + dirs = list(map(mk_dir, ["/tmp", "/blah", "/tmp/dar", + "/usr/", "/usr/bin"])) + links = [fs.fsLink(x, os.path.dirname(x), strict=False) for x in + ["/tmp/foo", "/usr/X11R6/lib", "/nagga/noo"]] + devs = list(map(mk_dev, + [f"dev/{x}" for x in ["sda1", "hda", "hda2", "disks/ide1"]])) + fifos = list(map(mk_fifo, + [f"tmp/{y}" for y in ("dar", "boo", "bah")])) + all = dirs + links + devs + fifos def test_init(self): - self.assertEqual(len(self.all), len(contents.contentsSet(self.all))) - self.assertRaises(TypeError, contents.contentsSet, self.all + [1]) + with pytest.raises(TypeError): + contents.contentsSet(self.all + [1]) contents.contentsSet(self.all) contents.contentsSet(self.all, mutable=True) # test to ensure no one screwed up the optional initials # making it mandatory - self.assertEqual(len(contents.contentsSet()), 0) + assert len(contents.contentsSet()) == 0 def test_add(self): cs = contents.contentsSet(self.files + self.dirs, mutable=True) for x in self.links: cs.add(x) - self.assertIn(x, cs) - self.assertEqual( - len(cs), - len(set(x.location for x in self.files + self.dirs + self.links))) - self.assertRaises(AttributeError, - lambda:contents.contentsSet(mutable=False).add(self.devs[0])) - self.assertRaises(TypeError, cs.add, 1) - self.assertRaises(TypeError, cs.add, self.fifos) + assert x in cs + assert len(cs) == len(set(x.location for x in self.files + self.dirs + self.links)) + with pytest.raises(AttributeError): + contents.contentsSet(mutable=False).add(self.devs[0]) + with pytest.raises(TypeError): + cs.add(1) + with pytest.raises(TypeError): + cs.add(self.fifos) def test_remove(self): - self.assertRaises(AttributeError, - contents.contentsSet(mutable=False).remove, self.devs[0]) - self.assertRaises(AttributeError, - contents.contentsSet(mutable=False).remove, 1) + with pytest.raises(AttributeError): + contents.contentsSet(mutable=False).remove(self.devs[0]) + with pytest.raises(AttributeError): + contents.contentsSet(mutable=False).remove(1) cs = contents.contentsSet(self.all, mutable=True) for x in self.all: cs.remove(x) cs = contents.contentsSet(self.all, mutable=True) for location in (x.location for x in self.all): cs.remove(location) - self.assertEqual(len(cs), 0) - self.assertRaises(KeyError, cs.remove, self.all[0]) + assert len(cs) == 0 + with pytest.raises(KeyError): + cs.remove(self.all[0]) def test_contains(self): cs = contents.contentsSet(mutable=True) for x in [y[0] for y in [ self.files, self.dirs, self.links, self.devs, self.fifos]]: - self.assertFalse(x in cs) - self.assertFalse(x.location in cs) + assert x not in cs + assert x.location not in cs cs.add(x) - self.assertTrue(x in cs) - self.assertTrue(x.location in cs) + assert x in cs + assert x.location in cs cs.remove(x) def test_clear(self): cs = contents.contentsSet(self.all, mutable=True) - self.assertTrue(len(cs)) + assert len(cs) > 0 cs.clear() - self.assertEqual(len(cs), 0) + assert len(cs) == 0 def test_len(self): - self.assertEqual(len(contents.contentsSet(self.all)), len(self.all)) - - def iterobj(self, name, obj_class=None, forced_name=None): + assert len(contents.contentsSet(self.all)) == len(self.all) + + fs_types = ( + pytest.param("files", fs.fsFile, id="files"), + pytest.param("dirs", fs.fsDir, id="dirs"), + pytest.param("links", fs.fsLink, id="links"), + pytest.param("devs", fs.fsDev, id="devs"), + pytest.param("fifos", fs.fsFifo, id="fifos"), + ) + + @pytest.mark.parametrize(("name", "obj_class"), fs_types) + def test_iterobj(self, name, obj_class): s = set(getattr(self, name)) cs = contents.contentsSet(s) - if forced_name is None: - forced_name = "iter"+name + forced_name = "iter" + name s2 = set(getattr(cs, forced_name)()) if obj_class is not None: for x in s2: - post_curry(self.assertTrue, obj_class)(x) - self.assertEqual(s, s2) - - if forced_name == "__iter__": - return + # post_curry(self.assertTrue, obj_class)(x) + assert bool(x) + assert s == s2 # inversion tests now. s3 = set(getattr(cs, forced_name)(invert=True)) - if obj_class is not None: - for x in s3: - post_curry(self.assertFalse, obj_class)(x) - - self.assertEqual(s.symmetric_difference(s2), s3) + for x in s3: + # post_curry(self.assertFalse, obj_class)(x) + assert not bool(x) + assert s.symmetric_difference(s2) == s3 - def listobj(self, name, obj_class=None): + @pytest.mark.parametrize(("name", "obj_class"), fs_types) + def test_listobj(self, name, obj_class): valid_list = getattr(self, name) cs = contents.contentsSet(valid_list) test_list = getattr(cs, name)() if obj_class is not None: for x in test_list: - self.assertInstance(x, obj_class) - self.assertEqual(set(test_list), set(valid_list)) - - test_iterfiles = post_curry(iterobj, "files", fs.fsFile) - test_files = post_curry(listobj, "files", fs.fsFile) - - test_iterdirs = post_curry(iterobj, "dirs", fs.fsDir) - test_dirs = post_curry(listobj, "dirs", fs.fsDir) + assert isinstance(x, obj_class) + assert set(test_list) == set(valid_list) - test_iterlinks = post_curry(iterobj, "links", fs.fsLink) - test_links = post_curry(listobj, "links", fs.fsLink) - - test_iterdevs = post_curry(iterobj, "devs", fs.fsDev) - test_devs = post_curry(listobj, "devs", fs.fsDev) - - test_iterfifos = post_curry(iterobj, "fifos", fs.fsFifo) - test_fifos = post_curry(listobj, "fifos", fs.fsFifo) - - test_iter = post_curry(iterobj, "all", forced_name="__iter__") + def test_iterobj_all(self): + s = set(self.all) + assert set(contents.contentsSet(s)) == s def test_check_instance(self): for x in [y[0] for y in [ self.files, self.dirs, self.links, self.devs, self.fifos]]: - self.assertEqual((x.location, x), tuple(contents.check_instance(x))) - self.assertRaises(TypeError, contents.check_instance, 1) + assert tuple(contents.check_instance(x)) == (x.location, x) + with pytest.raises(TypeError): + contents.check_instance(1) def check_set_op(self, name, ret, source=None): if source is None: - source = [[fs.fsDir("/tmp", strict=False)], - [fs.fsFile("/tmp", strict=False)]] + source = ([fs.fsDir("/tmp", strict=False)], + [fs.fsFile("/tmp", strict=False)]) c1, c2 = [contents.contentsSet(x) for x in source] if name.endswith("_update"): @@ -162,9 +144,7 @@ class TestContentsSet(TestCase): c3 = c1 else: c3 = getattr(c1, name)(c2) - self.assertEqual( - set(ret), - set(x.location for x in c3)) + assert set(ret) == {x.location for x in c3} c1, c2 = [contents.contentsSet(x) for x in source] if name.endswith("_update"): @@ -172,177 +152,173 @@ class TestContentsSet(TestCase): c3 = c1 else: c3 = getattr(c1, name)(iter(c2)) - self.assertEqual( - set(ret), - set(x.location for x in c3)) - - test_intersection = post_curry(check_set_op, "intersection", ["/tmp"]) - test_intersection_update = post_curry(check_set_op, - "intersection_update", ["/tmp"]) - - test_difference = post_curry(check_set_op, "difference", []) - test_difference_update = post_curry(check_set_op, - "difference_update", []) - - test_symmetric_difference1 = post_curry( - check_set_op, "symmetric_difference", []) - test_symmetric_difference1_update = post_curry( - check_set_op, "symmetric_difference_update", []) - - fstrings = ("/a", "/b", "/c", "/d") - f = list(map(mk_file, fstrings)) + assert set(ret) == {x.location for x in c3} + + fstrings = {"/a", "/b", "/c", "/d"} + f = tuple(map(mk_file, fstrings)) + + @pytest.mark.parametrize("name, ret, source", ( + pytest.param("intersection", {"/tmp"}, None, id="intersection"), + pytest.param("intersection_update", {"/tmp"}, None, id="intersection_update"), + pytest.param("difference", set(), None, id="difference"), + pytest.param("difference_update", set(), None, id="difference_update"), + pytest.param("symmetric_difference", set(), None, id="symmetric_difference"), + pytest.param("symmetric_difference_update", set(), None, id="symmetric_difference_update"), + + pytest.param("union", {"/tmp"}, None, id="union1"), + pytest.param("union", fstrings, (f[:2], f[2:]), id="union2"), + pytest.param("symmetric_difference", fstrings, (f[:2], f[2:]), id="symmetric_difference2"), + pytest.param("symmetric_difference_update", fstrings, (f[:2], f[2:]), id="symmetric_difference_update2"), + )) + def test_check_set_op(self, name, ret, source): + if source is None: + source = ([fs.fsDir("/tmp", strict=False)], + [fs.fsFile("/tmp", strict=False)]) - test_union1 = post_curry(check_set_op, "union", ["/tmp"]) - test_union2 = post_curry(check_set_op, "union", fstrings, [f[:2], f[2:]]) + c1, c2 = [contents.contentsSet(x) for x in source] + if name.endswith("_update"): + getattr(c1, name)(c2) + c3 = c1 + else: + c3 = getattr(c1, name)(c2) + assert {x.location for x in c3} == ret - test_symmetric_difference2 = post_curry( - check_set_op, "symmetric_difference", fstrings, [f[:2], f[2:]]) - test_symmetric_difference2_update = post_curry( - check_set_op, "symmetric_difference", fstrings, [f[:2], f[2:]]) + c1, c2 = [contents.contentsSet(x) for x in source] + if name.endswith("_update"): + getattr(c1, name)(iter(c2)) + c3 = c1 + else: + c3 = getattr(c1, name)(iter(c2)) + assert {x.location for x in c3} == ret del f, fstrings - def check_complex_set_op(self, name, *test_cases): - for required, data1, data2 in test_cases: - cset1 = contents.contentsSet(data1) - cset2 = contents.contentsSet(data2) - f = getattr(cset1, name) - got = f(cset2) - self.assertEqual( - got, required, - msg=f"{name}: expected {required}, got {got}\ncset1={cset1!r}\ncset2={cset2!r}") - - test_issubset = post_curry( - check_complex_set_op, "issubset", - (True, [mk_file("/foon")], [mk_file("/foon")]), - (False, [mk_file("/foon")], [mk_file("/dev")]), - (False, [mk_file("/dev"), mk_file("/dar")], [mk_file("/dev")]), - (True, [mk_file("/dev"), mk_file("/dar")], - [mk_file("/dev"), mk_file("/dar"), mk_file("/asdf")]) - ) - - - test_issuperset = post_curry( - check_complex_set_op, "issuperset", - (True, [mk_file("/foon")], [mk_file("/foon")]), - (False, [mk_file("/foon")], [mk_file("/dev")]), - (True, [mk_file("/dev"), mk_file("/dar")], [mk_file("/dev")]), - (False, [mk_file("/dev")], [mk_file("/dev"), mk_file("/dev2")]) - ) - - - test_isdisjoin = post_curry( - check_complex_set_op, "isdisjoint", - (False, [mk_file("/foon")], [mk_file("/foon")]), - (True, [mk_file("/foon")], [mk_file("/dev")]), - (False, [mk_file("/dev"), mk_file("/dar")], [mk_file("/dev")]), - (False, [mk_file("/dev"), mk_file("/dar")], - [mk_file("/dev"), mk_file("/dar"), mk_file("/asdf")]), - (False, [mk_file("/dev"), mk_file("/dar")], - [mk_file("/dev"), mk_file("/dar"), mk_file("/asdf")]), - (True, [mk_file("/dev"), mk_file("/dar")], - [mk_file("/dev2"), mk_file("/dar2"), mk_file("/asdf")]), - ) - + def check_complex_set_op(self, name, required, data1, data2): + cset1 = contents.contentsSet(data1) + cset2 = contents.contentsSet(data2) + f = getattr(cset1, name) + got = f(cset2) + assert got == required, \ + f"{name}: expected {required}, got {got}\ncset1={cset1!r}\ncset2={cset2!r}" + + @pytest.mark.parametrize(("required", "data1", "data2"), ( + (True, [mk_file("/foon")], [mk_file("/foon")]), + (False, [mk_file("/foon")], [mk_file("/dev")]), + (False, [mk_file("/dev"), mk_file("/dar")], [mk_file("/dev")]), + (True, [mk_file("/dev"), mk_file("/dar")], + [mk_file("/dev"), mk_file("/dar"), mk_file("/asdf")]), + )) + def test_issubset(self, required, data1, data2): + self.check_complex_set_op("issubset", required, data1, data2) + + @pytest.mark.parametrize(("required", "data1", "data2"), ( + (True, [mk_file("/foon")], [mk_file("/foon")]), + (False, [mk_file("/foon")], [mk_file("/dev")]), + (True, [mk_file("/dev"), mk_file("/dar")], [mk_file("/dev")]), + (False, [mk_file("/dev")], [mk_file("/dev"), mk_file("/dev2")]), + )) + def test_issuperset(self, required, data1, data2): + self.check_complex_set_op("issuperset", required, data1, data2) + + @pytest.mark.parametrize(("required", "data1", "data2"), ( + (False, [mk_file("/foon")], [mk_file("/foon")]), + (True, [mk_file("/foon")], [mk_file("/dev")]), + (False, [mk_file("/dev"), mk_file("/dar")], [mk_file("/dev")]), + (False, [mk_file("/dev"), mk_file("/dar")], + [mk_file("/dev"), mk_file("/dar"), mk_file("/asdf")]), + (False, [mk_file("/dev"), mk_file("/dar")], + [mk_file("/dev"), mk_file("/dar"), mk_file("/asdf")]), + (True, [mk_file("/dev"), mk_file("/dar")], + [mk_file("/dev2"), mk_file("/dar2"), mk_file("/asdf")]), + )) + def test_isdisjoint(self, required, data1, data2): + self.check_complex_set_op("isdisjoint", required, data1, data2) def test_child_nodes(self): - self.assertEqual(sorted(['/usr', '/usr/bin', '/usr/foo']), - sorted(x.location for x in contents.contentsSet( - [self.mk_dir("/usr"), self.mk_dir("/usr/bin"), - self.mk_file("/usr/foo")]))) + assert {'/usr', '/usr/bin', '/usr/foo'} == { + x.location for x in contents.contentsSet( + [mk_dir("/usr"), mk_dir("/usr/bin"), mk_file("/usr/foo")])} def test_map_directory_structure(self): - old = contents.contentsSet([self.mk_dir("/dir"), - self.mk_link("/sym", "dir")]) - new = contents.contentsSet([self.mk_file("/sym/a"), - self.mk_dir("/sym")]) + old = contents.contentsSet([mk_dir("/dir"), + mk_link("/sym", "dir")]) + new = contents.contentsSet([mk_file("/sym/a"), + mk_dir("/sym")]) # verify the machinery is working as expected. ret = new.map_directory_structure(old) - self.assertEqual(sorted(ret), sorted([self.mk_dir("/dir"), - self.mk_file("/dir/a")])) + assert set(ret) == {mk_dir("/dir"), mk_file("/dir/a")} # test recursion next. - old.add(self.mk_link("/dir/sym", "dir2")) - old.add(self.mk_dir("/dir/dir2")) - new.add(self.mk_file("/dir/sym/b")) - new.add(self.mk_dir("/sym/sym")) + old.add(mk_link("/dir/sym", "dir2")) + old.add(mk_dir("/dir/dir2")) + new.add(mk_file("/dir/sym/b")) + new.add(mk_dir("/sym/sym")) ret = new.map_directory_structure(old) - self.assertEqual(sorted(ret), sorted([self.mk_dir("/dir"), - self.mk_file("/dir/a"), self.mk_dir("/dir/dir2"), - self.mk_file("/dir/dir2/b")])) + assert set(ret) == {mk_dir("/dir"), mk_file("/dir/a"), + mk_dir("/dir/dir2"), mk_file("/dir/dir2/b")} def test_add_missing_directories(self): - src = [self.mk_file("/dir1/a"), self.mk_file("/dir2/dir3/b"), - self.mk_dir("/dir1/dir4")] + src = [mk_file("/dir1/a"), mk_file("/dir2/dir3/b"), + mk_dir("/dir1/dir4")] cs = contents.contentsSet(src) cs.add_missing_directories() - self.assertEqual(sorted(x.location for x in cs), - ['/dir1', '/dir1/a', '/dir1/dir4', '/dir2', '/dir2/dir3', - '/dir2/dir3/b']) + assert {x.location for x in cs} == \ + {'/dir1', '/dir1/a', '/dir1/dir4', '/dir2', '/dir2/dir3', '/dir2/dir3/b'} obj = cs['/dir1'] - self.assertEqual(obj.mode, 0o775) + assert obj.mode == 0o775 def test_inode_map(self): def check_it(target): - d = {k: sorted(v) for k, v in cs.inode_map().items()} - target = {k: sorted(v) for k, v in target.items()} - self.assertEqual(d, target) + d = {k: set(v) for k, v in cs.inode_map().items()} + target = {k: set(v) for k, v in target.items()} + assert d == target cs = contents.contentsSet() - f1 = self.mk_file("/f", dev=1, inode=1) + f1 = mk_file("/f", dev=1, inode=1) cs.add(f1) check_it({(1,1):[f1]}) - f2 = self.mk_file("/x", dev=1, inode=2) + f2 = mk_file("/x", dev=1, inode=2) cs.add(f2) check_it({(1,1):[f1], (1,2):[f2]}) - f3 = self.mk_file("/y", dev=2, inode=1) + f3 = mk_file("/y", dev=2, inode=1) cs.add(f3) check_it({(1,1):[f1], (1,2):[f2], (2,1):[f3]}) - f4 = self.mk_file("/z", dev=1, inode=1) + f4 = mk_file("/z", dev=1, inode=1) cs.add(f4) check_it({(1,1):[f1, f4], (1,2):[f2], (2,1):[f3]}) -class Test_offset_rewriting(TestCase): +class Test_offset_rewriting: change_offset = staticmethod(contents.change_offset_rewriter) offset_insert = staticmethod(contents.offset_rewriter) def test_offset_rewriter(self): - f = ["/foon/%i" % x for x in range(10)] - f.extend("/foon/%i/blah" % x for x in range(5)) + f = [f"/foon/{x}" for x in range(10)] + f.extend(f"/foon/{x}/blah" for x in range(5)) f = [fs.fsFile(x, strict=False) for x in f] - self.assertEqual(sorted(x.location for x in f), - sorted(x.location for x in self.offset_insert('/', f))) - self.assertEqual( - sorted(f'/usr{x.location}' for x in f), - sorted(x.location for x in self.offset_insert('/usr', f))) - - def test_it(self): - f = ["/foon/%i" % x for x in range(10)] - f.extend("/foon/%i/blah" % x for x in range(5)) - f = [fs.fsFile(x, strict=False) for x in f] - self.assertEqual(sorted(x.location for x in f), - sorted(y.location for y in self.change_offset('/usr', '/', - (x.change_attributes(location=f'/usr{x.location}') - for x in f) - ))) - self.assertEqual(sorted(x.location for x in f), - sorted(y.location for y in self.change_offset('/usr', '/', - (x.change_attributes(location=f'/usr/{x.location}') - for x in f) - ))) - self.assertEqual(sorted("/usr" + x.location for x in f), - sorted(y.location for y in self.change_offset('/', '/usr', - (x.change_attributes(location=f'/{x.location}') - for x in f) - ))) - - + assert {x.location for x in f} == {x.location for x in self.offset_insert('/', f)} + assert {f'/usr{x.location}' for x in f} == {x.location for x in self.offset_insert('/usr', f)} + def test_change_offset(self): + f = [f"/foon/{x}" for x in range(10)] + f.extend(f"/foon/{x}/blah" for x in range(5)) + f = [fs.fsFile(x, strict=False) for x in f] + assert {x.location for x in f} == { + y.location + for y in self.change_offset('/usr', '/', ( + x.change_attributes(location=f'/usr{x.location}') for x in f))} + assert {x.location for x in f} == { + y.location + for y in self.change_offset('/usr', '/', ( + x.change_attributes(location=f'/usr/{x.location}') for x in f))} + assert {f'/usr{x.location}' for x in f} == { + y.location + for y in self.change_offset('/', '/usr', ( + x.change_attributes(location=f'/{x.location}') for x in f))} diff --git a/tests/package/test_base.py b/tests/package/test_base.py index 5e99f159..09fdf38b 100644 --- a/tests/package/test_base.py +++ b/tests/package/test_base.py @@ -6,14 +6,13 @@ from pkgcore.package import base def fake_pkg(cat='dev-util', pkg='bsdiff', ver='1.0', **attrs): - return SimpleNamespace(**({ - 'category': cat, - 'pkg': pkg, - 'ver': ver, - 'key': f"{cat}/{pkg}", - "cpvstr": f"{cat}/{pkg}-{ver}", - "built": False, - } | attrs)) + attrs.setdefault('category', cat) + attrs.setdefault('pkg', pkg) + attrs.setdefault('ver', ver) + attrs.setdefault('key', f"{cat}/{pkg}") + attrs.setdefault('cpvstr', f"{cat}/{pkg}-{ver}") + attrs.setdefault('built', False) + return SimpleNamespace(**attrs) class mixin: |