From 476370788e0d8f28df51188de3c7ee17668d153e Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 22 Apr 2025 10:25:37 +0000 Subject: [PATCH 1/3] use python3 --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 940c636..eec81a5 100755 --- a/setup.py +++ b/setup.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 import setuptools From 907fab2525b9a07f5104c3d9b90c251da9c61aa8 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 22 Apr 2025 10:25:54 +0000 Subject: [PATCH 2/3] ruff format --- doc/example.py | 8 +- setup.py | 2 +- testresources/__init__.py | 86 ++++--- testresources/tests/TestUtil.py | 18 +- testresources/tests/__init__.py | 9 +- .../tests/test_optimising_test_suite.py | 236 ++++++++++-------- testresources/tests/test_resource_graph.py | 84 ++++--- .../tests/test_resourced_test_case.py | 56 +++-- testresources/tests/test_test_loader.py | 5 +- testresources/tests/test_test_resource.py | 112 +++++---- 10 files changed, 352 insertions(+), 264 deletions(-) diff --git a/doc/example.py b/doc/example.py index 01c45aa..ab3891a 100644 --- a/doc/example.py +++ b/doc/example.py @@ -2,12 +2,12 @@ # of resources by test cases. # # Copyright (c) 2005-2010 Testresources Contributors -# +# # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not use this file except in # compliance with one of these two licences. -# +# # Unless required by applicable law or agreed to in writing, software distributed # under these licenses is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the license you chose @@ -21,7 +21,6 @@ class SampleTestResource(TestResourceManager): - setUpCost = 2 tearDownCost = 2 @@ -34,8 +33,7 @@ class MyResource(object): class SampleWithDependencies(TestResourceManager): - - resources = [('foo', SampleTestResource()), ('bar', SampleTestResource())] + resources = [("foo", SampleTestResource()), ("bar", SampleTestResource())] def make(self, dependency_resources): # dependency_resources will be {'foo': result_of_make_in_foo, 'bar': diff --git a/setup.py b/setup.py index eec81a5..93383e1 100755 --- a/setup.py +++ b/setup.py @@ -2,4 +2,4 @@ import setuptools -setuptools.setup(setup_requires=['pbr>=1.3'], pbr=True) +setuptools.setup(setup_requires=["pbr>=1.3"], pbr=True) diff --git a/testresources/__init__.py b/testresources/__init__.py index 31e2671..1eb5d89 100644 --- a/testresources/__init__.py +++ b/testresources/__init__.py @@ -20,6 +20,7 @@ import heapq import inspect import unittest + try: from collections.abc import MutableSet except ImportError: @@ -42,13 +43,15 @@ # Otherwise it is major.minor.micro~$(revno). from pbr.version import VersionInfo -_version = VersionInfo('testresources') + +_version = VersionInfo("testresources") __version__ = _version.semantic_version().version_tuple() version = _version.release_string() def test_suite(): import testresources.tests + return testresources.tests.test_suite() @@ -111,7 +114,7 @@ def _kruskals_graph_MST(graph): # combine g1 and g2 into g1 graphs -= 1 for from_node, to_nodes in g2.items(): - #remember its symmetric, don't need to do 'to'. + # remember its symmetric, don't need to do 'to'. forest[from_node] = g1 g1.setdefault(from_node, {}).update(to_nodes) # add edge @@ -161,8 +164,7 @@ def split_by_resources(tests): resource_set_tests = {no_resources: []} for test in tests: resources = getattr(test, "resources", ()) - all_resources = list(resource.neededResources() - for _, resource in resources) + all_resources = list(resource.neededResources() for _, resource in resources) resource_set = set() for resource_list in all_resources: resource_set.update(resource_list) @@ -206,8 +208,8 @@ class _OrderedSet(MutableSet): def __init__(self, iterable=None): self.end = end = [] - end += [None, end, end] # sentinel node for doubly linked list - self.map = {} # key --> [key, prev, next] + end += [None, end, end] # sentinel node for doubly linked list + self.map = {} # key --> [key, prev, next] if iterable is not None: self |= iterable @@ -274,8 +276,7 @@ def addTest(self, test_case_or_suite): self.adsorbSuite(test) else: for test in tests: - unittest.TestSuite.addTest( - self, test_case_or_suite.__class__([test])) + unittest.TestSuite.addTest(self, test_case_or_suite.__class__([test])) def cost_of_switching(self, old_resource_set, new_resource_set): """Cost of switching from 'old_resource_set' to 'new_resource_set'. @@ -290,8 +291,9 @@ def cost_of_switching(self, old_resource_set, new_resource_set): """ new_resources = new_resource_set - old_resource_set gone_resources = old_resource_set - new_resource_set - return (sum(resource.setUpCost for resource in new_resources) + - sum(resource.tearDownCost for resource in gone_resources)) + return sum(resource.setUpCost for resource in new_resources) + sum( + resource.tearDownCost for resource in gone_resources + ) def switch(self, old_resource_set, new_resource_set, result): """Switch from 'old_resource_set' to 'new_resource_set'. @@ -321,7 +323,7 @@ def run(self, result): for test in self._tests: if result.shouldStop: break - resources = getattr(test, 'resources', []) + resources = getattr(test, "resources", []) new_resources = _OrderedSet() for name, resource in resources: new_resources.update(resource.neededResources()) @@ -357,8 +359,7 @@ def sortTests(self): resource_set_graph = _resource_graph(resource_set_tests) no_resources = frozenset() # A list of resource_set_tests, all fully internally connected. - partitions = _strongly_connected_components(resource_set_graph, - no_resources) + partitions = _strongly_connected_components(resource_set_graph, no_resources) result = [] for partition in partitions: # we process these at the end for no particularly good reason (it @@ -384,30 +385,31 @@ def _getGraph(self, resource_sets): """ no_resources = frozenset() graph = {} - root = set(['root']) + root = set(["root"]) # bottom = set(['bottom']) for from_set in resource_sets: graph[from_set] = {} if from_set == root: from_resources = no_resources - #elif from_set == bottom: + # elif from_set == bottom: # continue # no links from bottom else: from_resources = from_set for to_set in resource_sets: if from_set is to_set: continue # no self-edges - #if to_set == bottom: + # if to_set == bottom: # if from_set == root: # continue # no short cuts! # to_resources = no_resources - #el + # el if to_set == root: continue # no links to root else: to_resources = to_set graph[from_set][to_set] = self.cost_of_switching( - from_resources, to_resources) + from_resources, to_resources + ) return graph def _makeOrder(self, partition): @@ -419,7 +421,7 @@ def _makeOrder(self, partition): # http://en.wikipedia.org/wiki/Travelling_salesman_problem#Metric_TSP # We need a root - root = frozenset(['root']) + root = frozenset(["root"]) partition.add(root) # and an end # partition.add(frozenset(['bottom'])) @@ -428,7 +430,7 @@ def _makeOrder(self, partition): digraph = self._getGraph(partition) # build a prime map primes = {} - prime = frozenset(['prime']) + prime = frozenset(["prime"]) for node in digraph: primes[node] = node.union(prime) graph = _digraph_to_graph(digraph, primes) @@ -480,14 +482,14 @@ def _makeOrder(self, partition): return order[1:] -OptimisingTestSuite.known_suite_classes = ( - unittest.TestSuite, OptimisingTestSuite) +OptimisingTestSuite.known_suite_classes = (unittest.TestSuite, OptimisingTestSuite) if unittest2 is not None: OptimisingTestSuite.known_suite_classes += (unittest2.TestSuite,) class TestLoader(unittest.TestLoader): """Custom TestLoader to set the right TestSuite class.""" + suiteClass = OptimisingTestSuite @@ -624,8 +626,7 @@ def make(self, dependency_resources): for the resources specified as dependencies. :return: The made resource. """ - raise NotImplementedError( - "Override make to construct resources.") + raise NotImplementedError("Override make to construct resources.") def neededResources(self): """Return the resources needed for this resource, including self. @@ -647,7 +648,7 @@ def reset(self, old_resource, result=None): is part of the public interface, but _make_all and _clean_all is not. Note that if a resource A holds a lock or other blocking thing on - a dependency D, reset will result in this call sequence over a + a dependency D, reset will result in this call sequence over a getResource(), dirty(), getResource(), finishedWith(), finishedWith() sequence: B.make(), A.make(), B.reset(), A.reset(), A.clean(), B.clean() @@ -679,8 +680,7 @@ def reset(self, old_resource, result=None): self._call_result_method_if_exists(result, "startResetResource", self) dependency_resources = {} for name, mgr in self.resources: - dependency_resources[name] = mgr.reset( - getattr(old_resource, name), result) + dependency_resources[name] = mgr.reset(getattr(old_resource, name), result) resource = self._reset(old_resource, dependency_resources) for name, value in dependency_resources.items(): setattr(resource, name, value) @@ -723,6 +723,8 @@ def _setResource(self, new_resource): """Set the current resource to a new value.""" self._currentResource = new_resource self._dirty = False + + TestResource = TestResourceManager @@ -741,9 +743,13 @@ class GenericResource(TestResourceManager): method. """ - def __init__(self, resource_factory, setup_method_name='setUp', - teardown_method_name='tearDown', - id_attribute_name="__name__"): + def __init__( + self, + resource_factory, + setup_method_name="setUp", + teardown_method_name="tearDown", + id_attribute_name="__name__", + ): """Create a GenericResource :param resource_factory: A factory to create a new resource. @@ -779,7 +785,8 @@ def id(self): """ return "%s[%s]" % ( super(GenericResource, self).id(), - getattr(self.resource_factory, self.id_attribute_name)) + getattr(self.resource_factory, self.id_attribute_name), + ) class FixtureResource(TestResourceManager): @@ -823,8 +830,7 @@ def id(self): The default is to call str(fixture) to get such information. """ - return "%s[%s]" % ( - super(FixtureResource, self).id(), str(self.fixture)) + return "%s[%s]" % (super(FixtureResource, self).id(), str(self.fixture)) def _reset(self, resource, dependency_resources): self.fixture.reset() @@ -833,7 +839,7 @@ def _reset(self, resource, dependency_resources): def isDirty(self): return True - _dirty = property(lambda _:True, lambda _, _1:None) + _dirty = property(lambda _: True, lambda _, _1: None) class ResourcedTestCase(unittest.TestCase): @@ -901,8 +907,9 @@ def neededResources(resources): result = [] for resource in resources: - dependencies = neededResources([ - dependency for name, dependency in resource.resources]) + dependencies = neededResources( + [dependency for name, dependency in resource.resources] + ) for resource in dependencies + [resource]: if resource in seen: continue @@ -924,10 +931,9 @@ def _get_result(): """ stack = inspect.stack() for frame in stack[2:]: - if frame[3] in ('run', '__call__'): + if frame[3] in ("run", "__call__"): # Not all frames called 'run' will be unittest. It could be a # reactor in trial, for instance. - result = frame[0].f_locals.get('result') - if (result is not None and - getattr(result, 'startTest', None) is not None): + result = frame[0].f_locals.get("result") + if result is not None and getattr(result, "startTest", None) is not None: return result diff --git a/testresources/tests/TestUtil.py b/testresources/tests/TestUtil.py index e60d431..7a34051 100644 --- a/testresources/tests/TestUtil.py +++ b/testresources/tests/TestUtil.py @@ -23,7 +23,8 @@ class LogCollector(logging.Handler): def __init__(self): logging.Handler.__init__(self) - self.records=[] + self.records = [] + def emit(self, record): self.records.append(record.getMessage()) @@ -31,8 +32,8 @@ def emit(self, record): def makeCollectingLogger(): """I make a logger instance that collects its logs for programmatic analysis -> (logger, collector)""" - logger=logging.Logger("collector") - handler=LogCollector() + logger = logging.Logger("collector") + handler = LogCollector() handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s")) logger.addHandler(handler) return logger, handler @@ -44,7 +45,7 @@ def visitTests(suite, visitor): visitor.visitCase(suite) return for test in suite._tests: - #Abusing types to avoid monkey patching unittest.TestCase. + # Abusing types to avoid monkey patching unittest.TestCase. # Maybe that would be better? try: test.visit(visitor) @@ -55,7 +56,10 @@ def visitTests(suite, visitor): visitor.visitSuite(test) visitTests(test, visitor) else: - print("unvisitable non-unittest.TestCase element %r (%r)" % (test, test.__class__)) + print( + "unvisitable non-unittest.TestCase element %r (%r)" + % (test, test.__class__) + ) class TestSuite(unittest.TestSuite): @@ -72,11 +76,15 @@ def visit(self, visitor): class TestLoader(unittest.TestLoader): """Custome TestLoader to set the right TestSuite class.""" + suiteClass = TestSuite + class TestVisitor(object): """A visitor for Tests""" + def visitSuite(self, aTestSuite): pass + def visitCase(self, aTestCase): pass diff --git a/testresources/tests/__init__.py b/testresources/tests/__init__.py index 644ace4..94aa8c7 100644 --- a/testresources/tests/__init__.py +++ b/testresources/tests/__init__.py @@ -2,12 +2,12 @@ # of resources by test cases. # # Copyright (c) 2005-2010 Testresources Contributors -# +# # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not use this file except in # compliance with one of these two licences. -# +# # Unless required by applicable law or agreed to in writing, software distributed # under these licenses is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the license you chose @@ -19,19 +19,20 @@ from testresources.tests import TestUtil + def test_suite(): import testresources.tests.test_optimising_test_suite import testresources.tests.test_resourced_test_case import testresources.tests.test_test_loader import testresources.tests.test_test_resource import testresources.tests.test_resource_graph + result = TestUtil.TestSuite() result.addTest(testresources.tests.test_test_loader.test_suite()) result.addTest(testresources.tests.test_test_resource.test_suite()) result.addTest(testresources.tests.test_resourced_test_case.test_suite()) result.addTest(testresources.tests.test_resource_graph.test_suite()) - result.addTest( - testresources.tests.test_optimising_test_suite.test_suite()) + result.addTest(testresources.tests.test_optimising_test_suite.test_suite()) return result diff --git a/testresources/tests/test_optimising_test_suite.py b/testresources/tests/test_optimising_test_suite.py index e924cc1..65e9258 100644 --- a/testresources/tests/test_optimising_test_suite.py +++ b/testresources/tests/test_optimising_test_suite.py @@ -2,12 +2,12 @@ # of resources by test cases. # # Copyright (c) 2005-2010 Testresources Contributors -# +# # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not use this file except in # compliance with one of these two licences. -# +# # Unless required by applicable law or agreed to in writing, software distributed # under these licenses is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the license you chose @@ -21,6 +21,7 @@ from testresources import split_by_resources from testresources.tests import ResultWithResourceExtensions import unittest + try: import unittest2 except ImportError: @@ -29,6 +30,7 @@ def test_suite(): from testresources.tests import TestUtil + loader = TestUtil.TestLoader() result = loader.loadTestsFromName(__name__) return result @@ -38,8 +40,8 @@ class CustomSuite(unittest.TestSuite): """Custom TestSuite that's comparable using == and !=.""" def __eq__(self, other): - return (self.__class__ == other.__class__ - and self._tests == other._tests) + return self.__class__ == other.__class__ and self._tests == other._tests + def __ne__(self, other): return not self.__eq__(other) @@ -55,32 +57,35 @@ def __init__(self): def clean(self, resource): self.cleans += 1 - self.calls.append(('clean', resource)) + self.calls.append(("clean", resource)) def make(self, dependency_resources): self.makes += 1 resource = "boo %d" % self.makes - self.calls.append(('make', resource)) + self.calls.append(("make", resource)) return resource class TestOptimisingTestSuite(testtools.TestCase): - def makeTestCase(self, test_running_hook=None): """Make a normal TestCase.""" + class TestCaseForTesting(unittest.TestCase): def runTest(self): if test_running_hook: test_running_hook(self) - return TestCaseForTesting('runTest') + + return TestCaseForTesting("runTest") def makeResourcedTestCase(self, resource_manager, test_running_hook): """Make a ResourcedTestCase.""" + class ResourcedTestCaseForTesting(testresources.ResourcedTestCase): def runTest(self): test_running_hook(self) - test_case = ResourcedTestCaseForTesting('runTest') - test_case.resources = [('_default', resource_manager)] + + test_case = ResourcedTestCaseForTesting("runTest") + test_case.resources = [("_default", resource_manager)] return test_case def setUp(self): @@ -127,8 +132,8 @@ def testAddFlattensStandardSuiteStructure(self): case2 = self.makeTestCase() case3 = self.makeTestCase() suite = unittest.TestSuite( - [unittest.TestSuite([case1, unittest.TestSuite([case2])]), - case3]) + [unittest.TestSuite([case1, unittest.TestSuite([case2])]), case3] + ) self.optimising_suite.addTest(suite) self.assertEqual([case1, case2, case3], self.optimising_suite._tests) @@ -142,7 +147,8 @@ def testAddDistributesNonStandardSuiteStructure(self): self.optimising_suite.addTest(suite) self.assertEqual( [CustomSuite([case1]), CustomSuite([inner_suite])], - self.optimising_suite._tests) + self.optimising_suite._tests, + ) def testAddPullsNonStandardSuitesUp(self): # addTest flattens standard TestSuites, even those that contain custom @@ -152,15 +158,18 @@ def testAddPullsNonStandardSuitesUp(self): case2 = self.makeTestCase() inner_suite = CustomSuite([case1, case2]) self.optimising_suite.addTest( - unittest.TestSuite([unittest.TestSuite([inner_suite])])) + unittest.TestSuite([unittest.TestSuite([inner_suite])]) + ) self.assertEqual( - [CustomSuite([case1]), CustomSuite([case2])], - self.optimising_suite._tests) + [CustomSuite([case1]), CustomSuite([case2])], self.optimising_suite._tests + ) def testSingleCaseResourceAcquisition(self): sample_resource = MakeCounter() + def getResourceCount(test): self.assertEqual(sample_resource._uses, 2) + case = self.makeResourcedTestCase(sample_resource, getResourceCount) self.optimising_suite.addTest(case) result = unittest.TestResult() @@ -171,8 +180,10 @@ def getResourceCount(test): def testResourceReuse(self): make_counter = MakeCounter() + def getResourceCount(test): self.assertEqual(make_counter._uses, 2) + case = self.makeResourcedTestCase(make_counter, getResourceCount) case2 = self.makeResourcedTestCase(make_counter, getResourceCount) self.optimising_suite.addTest(case) @@ -187,8 +198,8 @@ def getResourceCount(test): def testResultPassedToResources(self): resource_manager = MakeCounter() - test_case = self.makeTestCase(lambda x:None) - test_case.resources = [('_default', resource_manager)] + test_case = self.makeTestCase(lambda x: None) + test_case.resources = [("_default", resource_manager)] self.optimising_suite.addTest(test_case) result = ResultWithResourceExtensions() self.optimising_suite.run(result) @@ -217,14 +228,19 @@ def sortTests(self): def testResourcesDroppedForNonResourcedTestCase(self): sample_resource = MakeCounter() + def resourced_case_hook(test): self.assertTrue(sample_resource._uses > 0) - self.optimising_suite.addTest(self.makeResourcedTestCase( - sample_resource, resourced_case_hook)) + + self.optimising_suite.addTest( + self.makeResourcedTestCase(sample_resource, resourced_case_hook) + ) + def normal_case_hook(test): # The resource should not be acquired when the normal test # runs. self.assertEqual(sample_resource._uses, 0) + self.optimising_suite.addTest(self.makeTestCase(normal_case_hook)) result = unittest.TestResult() self.optimising_suite.run(result) @@ -235,8 +251,10 @@ def normal_case_hook(test): def testDirtiedResourceNotRecreated(self): make_counter = MakeCounter() + def dirtyResource(test): make_counter.dirtied(test._default) + case = self.makeResourcedTestCase(make_counter, dirtyResource) self.optimising_suite.addTest(case) result = unittest.TestResult() @@ -248,11 +266,14 @@ def dirtyResource(test): def testDirtiedResourceCleanedUp(self): make_counter = MakeCounter() + def testOne(test): - make_counter.calls.append('test one') + make_counter.calls.append("test one") make_counter.dirtied(test._default) + def testTwo(test): - make_counter.calls.append('test two') + make_counter.calls.append("test two") + case1 = self.makeResourcedTestCase(make_counter, testOne) case2 = self.makeResourcedTestCase(make_counter, testTwo) self.optimising_suite.addTest(case1) @@ -262,13 +283,17 @@ def testTwo(test): self.assertEqual(result.testsRun, 2) self.assertEqual(result.wasSuccessful(), True) # Two resources should have been created and cleaned up - self.assertEqual(make_counter.calls, - [('make', 'boo 1'), - 'test one', - ('clean', 'boo 1'), - ('make', 'boo 2'), - 'test two', - ('clean', 'boo 2')]) + self.assertEqual( + make_counter.calls, + [ + ("make", "boo 1"), + "test one", + ("clean", "boo 1"), + ("make", "boo 2"), + "test two", + ("clean", "boo 2"), + ], + ) def testSwitchConsidersDependencies(self): """ @@ -280,6 +305,7 @@ def testSwitchConsidersDependencies(self): class Resource(testresources.TestResource): """Dummy resource.""" + def __init__(self, name): super(Resource, self).__init__() self.name = name @@ -292,34 +318,34 @@ def clean(self, resource): cleans.append(resource.name) # Create two resources, the second depending on the first. - resource_one = Resource('one') - resource_two = Resource('two') - resource_two.resources = [('one', resource_one)] + resource_one = Resource("one") + resource_two = Resource("two") + resource_two.resources = [("one", resource_one)] test_case = self.makeTestCase(lambda x: None) - test_case.resources = [('two', resource_two)] + test_case.resources = [("two", resource_two)] self.optimising_suite.addTest(test_case) result = unittest.TestResult() self.optimising_suite.run(result) # The first resource was made before the second - self.assertEqual(makes, ['one', 'two']) + self.assertEqual(makes, ["one", "two"]) # The second resource was cleaned before the first - self.assertEqual(cleans, ['two', 'one']) + self.assertEqual(cleans, ["two", "one"]) class TestSplitByResources(testtools.TestCase): """Tests for split_by_resources.""" def makeTestCase(self): - return unittest.TestCase('run') + return unittest.TestCase("run") def makeResourcedTestCase(self, has_resource=True): - case = testresources.ResourcedTestCase('run') + case = testresources.ResourcedTestCase("run") if has_resource: - case.resources = [('resource', testresources.TestResource())] + case.resources = [("resource", testresources.TestResource())] return case def testNoTests(self): @@ -334,31 +360,33 @@ def testJustResourcedCases(self): resourced_case = self.makeResourcedTestCase() resource = resourced_case.resources[0][1] resource_set_tests = split_by_resources([resourced_case]) - self.assertEqual({frozenset(): [], - frozenset([resource]): [resourced_case]}, - resource_set_tests) + self.assertEqual( + {frozenset(): [], frozenset([resource]): [resourced_case]}, + resource_set_tests, + ) def testMultipleResources(self): resource1 = testresources.TestResource() resource2 = testresources.TestResource() resourced_case = self.makeResourcedTestCase(has_resource=False) - resourced_case.resources = [('resource1', resource1), - ('resource2', resource2)] + resourced_case.resources = [("resource1", resource1), ("resource2", resource2)] resource_set_tests = split_by_resources([resourced_case]) - self.assertEqual({frozenset(): [], - frozenset([resource1, resource2]): [resourced_case]}, - resource_set_tests) + self.assertEqual( + {frozenset(): [], frozenset([resource1, resource2]): [resourced_case]}, + resource_set_tests, + ) def testDependentResources(self): resource1 = testresources.TestResource() resource2 = testresources.TestResource() - resource1.resources = [('foo', resource2)] + resource1.resources = [("foo", resource2)] resourced_case = self.makeResourcedTestCase(has_resource=False) - resourced_case.resources = [('resource1', resource1)] + resourced_case.resources = [("resource1", resource1)] resource_set_tests = split_by_resources([resourced_case]) - self.assertEqual({frozenset(): [], - frozenset([resource1, resource2]): [resourced_case]}, - resource_set_tests) + self.assertEqual( + {frozenset(): [], frozenset([resource1, resource2]): [resourced_case]}, + resource_set_tests, + ) def testResourcedCaseWithNoResources(self): resourced_case = self.makeResourcedTestCase(has_resource=False) @@ -367,15 +395,15 @@ def testResourcedCaseWithNoResources(self): def testMixThemUp(self): normal_cases = [self.makeTestCase() for i in range(3)] - normal_cases.extend([ - self.makeResourcedTestCase(has_resource=False) for i in range(3)]) + normal_cases.extend( + [self.makeResourcedTestCase(has_resource=False) for i in range(3)] + ) resourced_cases = [self.makeResourcedTestCase() for i in range(3)] all_cases = normal_cases + resourced_cases # XXX: Maybe I shouldn't be using random here. random.shuffle(all_cases) resource_set_tests = split_by_resources(all_cases) - self.assertEqual(set(normal_cases), - set(resource_set_tests[frozenset()])) + self.assertEqual(set(normal_cases), set(resource_set_tests[frozenset()])) for case in resourced_cases: resource = case.resources[0][1] self.assertEqual([case], resource_set_tests[frozenset([resource])]) @@ -403,8 +431,7 @@ def testSameResources(self): a = self.makeResource() b = self.makeResource() self.assertEqual(0, self.suite.cost_of_switching(set([a]), set([a]))) - self.assertEqual( - 0, self.suite.cost_of_switching(set([a, b]), set([a, b]))) + self.assertEqual(0, self.suite.cost_of_switching(set([a, b]), set([a, b]))) # XXX: The next few tests demonstrate the current behaviour of the system. # We'll change them later. @@ -413,16 +440,14 @@ def testNewResources(self): a = self.makeResource() b = self.makeResource() self.assertEqual(1, self.suite.cost_of_switching(set(), set([a]))) - self.assertEqual( - 1, self.suite.cost_of_switching(set([a]), set([a, b]))) + self.assertEqual(1, self.suite.cost_of_switching(set([a]), set([a, b]))) self.assertEqual(2, self.suite.cost_of_switching(set(), set([a, b]))) def testOldResources(self): a = self.makeResource() b = self.makeResource() self.assertEqual(1, self.suite.cost_of_switching(set([a]), set())) - self.assertEqual( - 1, self.suite.cost_of_switching(set([a, b]), set([a]))) + self.assertEqual(1, self.suite.cost_of_switching(set([a, b]), set([a]))) self.assertEqual(2, self.suite.cost_of_switching(set([a, b]), set())) def testCombo(self): @@ -430,8 +455,7 @@ def testCombo(self): b = self.makeResource() c = self.makeResource() self.assertEqual(2, self.suite.cost_of_switching(set([a]), set([b]))) - self.assertEqual( - 2, self.suite.cost_of_switching(set([a, c]), set([b, c]))) + self.assertEqual(2, self.suite.cost_of_switching(set([a, c]), set([b, c]))) class TestCostGraph(testtools.TestCase): @@ -464,28 +488,37 @@ def testTwoCasesInGraph(self): suite = testresources.OptimisingTestSuite() graph = suite._getGraph([no_resources, set1, set2]) - self.assertEqual({no_resources: {set1: 2, set2: 1}, - set1: {no_resources: 2, set2: 1}, - set2: {no_resources: 1, set1: 1 }}, graph) + self.assertEqual( + { + no_resources: {set1: 2, set2: 1}, + set1: {no_resources: 2, set2: 1}, + set2: {no_resources: 1, set1: 1}, + }, + graph, + ) class TestGraphStuff(testtools.TestCase): - def setUp(self): super(TestGraphStuff, self).setUp() + class MockTest(unittest.TestCase): def __repr__(self): """The representation is the tests name. This makes it easier to debug sorting failures. """ - return self.id().split('.')[-1] + return self.id().split(".")[-1] + def test_one(self): pass + def test_two(self): pass + def test_three(self): pass + def test_four(self): pass @@ -550,10 +583,8 @@ def testBasicSortTests(self): resource_two.tearDownCost = 5 resource_three = testresources.TestResource() - self.case1.resources = [ - ("_one", resource_one), ("_two", resource_two)] - self.case2.resources = [ - ("_two", resource_two), ("_three", resource_three)] + self.case1.resources = [("_one", resource_one), ("_two", resource_two)] + self.case2.resources = [("_two", resource_two), ("_three", resource_three)] self.case3.resources = [("_three", resource_three)] # acceptable sorted orders are: # 1, 2, 3, 4 @@ -561,17 +592,20 @@ def testBasicSortTests(self): for permutation in self._permute_four(self.cases): self.assertIn( - self.sortTests(permutation), [ + self.sortTests(permutation), + [ [self.case1, self.case2, self.case3, self.case4], - [self.case3, self.case2, self.case1, self.case4]], - "failed with permutation %s" % (permutation,)) + [self.case3, self.case2, self.case1, self.case4], + ], + "failed with permutation %s" % (permutation,), + ) def testGlobalMinimum(self): # When a local minimum leads to a global non-minum, the global # non-minimum is still reached. We construct this by having a resource # that appears very cheap (it has a low setup cost) but is very # expensive to tear down. Then we have it be used twice: the global - # minimum depends on only tearing it down once. To prevent it + # minimum depends on only tearing it down once. To prevent it # accidentally being chosen twice, we make one use of it be # on its own, and another with a resource to boost its cost, # finally we put a resource which is more expensive to setup @@ -610,14 +644,11 @@ def testGlobalMinimum(self): [self.case1, self.case3, self.case2, self.case4], [self.case2, self.case3, self.case1, self.case4], [self.case3, self.case2, self.case1, self.case4], - ] + ] - self.case1.resources = [ - ("_one", resource_one)] - self.case2.resources = [ - ("_two", resource_two)] - self.case3.resources = [("_two", resource_two), - ("_three", resource_three)] + self.case1.resources = [("_one", resource_one)] + self.case2.resources = [("_two", resource_two)] + self.case3.resources = [("_two", resource_two), ("_three", resource_three)] for permutation in self._permute_four(self.cases): self.assertIn(self.sortTests(permutation), acceptable_orders) @@ -635,10 +666,12 @@ def testSortIsStableWithinGroups(self): sorted = self.sortTests(permutation) self.assertEqual( permutation.index(self.case1) < permutation.index(self.case2), - sorted.index(self.case1) < sorted.index(self.case2)) + sorted.index(self.case1) < sorted.index(self.case2), + ) self.assertEqual( permutation.index(self.case3) < permutation.index(self.case4), - sorted.index(self.case3) < sorted.index(self.case4)) + sorted.index(self.case3) < sorted.index(self.case4), + ) def testSortingTwelveIndependentIsFast(self): # Given twelve independent resource sets, my patience is not exhausted. @@ -647,13 +680,12 @@ def testSortingTwelveIndependentIsFast(self): managers.append(testresources.TestResourceManager()) # Add more sample tests cases = [self.case1, self.case2, self.case3, self.case4] - for pos in range(5,13): - cases.append( - testtools.clone_test_with_new_id(cases[0], 'case%d' % pos)) + for pos in range(5, 13): + cases.append(testtools.clone_test_with_new_id(cases[0], "case%d" % pos)) # We care that this is fast in this test, so we don't need to have # overlapping resource usage for case, manager in zip(cases, managers): - case.resources = [('_resource', manager)] + case.resources = [("_resource", manager)] # Any sort is ok, as long as its the right length :) result = self.sortTests(cases) self.assertEqual(12, len(result)) @@ -665,14 +697,13 @@ def testSortingTwelveOverlappingIsFast(self): managers.append(testresources.TestResourceManager()) # Add more sample tests cases = [self.case1, self.case2, self.case3, self.case4] - for pos in range(5,13): - cases.append( - testtools.clone_test_with_new_id(cases[0], 'case%d' % pos)) + for pos in range(5, 13): + cases.append(testtools.clone_test_with_new_id(cases[0], "case%d" % pos)) tempdir = testresources.TestResourceManager() # give all tests a tempdir, enough to provoke a single partition in # the current code. for case, manager in zip(cases, managers): - case.resources = [('_resource', manager), ('tempdir', tempdir)] + case.resources = [("_resource", manager), ("tempdir", tempdir)] # Any sort is ok, as long as its the right length :) result = self.sortTests(cases) self.assertEqual(12, len(result)) @@ -690,7 +721,7 @@ def testSortConsidersDependencies(self): # In a dependency naive sort, we will have test3 between test1 and # test2 always. In a dependency aware sort, test1 and two will # always group. - + resource_one = testresources.TestResource() resource_two = testresources.TestResource() resource_one_common = testresources.TestResource() @@ -707,9 +738,18 @@ def testSortConsidersDependencies(self): resource_one.resources.append(("dep1", dep)) resource_two.resources.append(("dep2", dep)) - self.case1.resources = [("withdep", resource_one), ("common", resource_one_common)] - self.case2.resources = [("withdep", resource_two), ("common", resource_two_common)] - self.case3.resources = [("_one", resource_one_common), ("_two", resource_two_common)] + self.case1.resources = [ + ("withdep", resource_one), + ("common", resource_one_common), + ] + self.case2.resources = [ + ("withdep", resource_two), + ("common", resource_two_common), + ] + self.case3.resources = [ + ("_one", resource_one_common), + ("_two", resource_two_common), + ] self.case4.resources = [] acceptable_orders = [ @@ -717,7 +757,7 @@ def testSortConsidersDependencies(self): [self.case2, self.case1, self.case3, self.case4], [self.case3, self.case1, self.case2, self.case4], [self.case3, self.case2, self.case1, self.case4], - ] + ] for permutation in self._permute_four(self.cases): self.assertIn(self.sortTests(permutation), acceptable_orders) diff --git a/testresources/tests/test_resource_graph.py b/testresources/tests/test_resource_graph.py index ebf4fa0..7a3c928 100644 --- a/testresources/tests/test_resource_graph.py +++ b/testresources/tests/test_resource_graph.py @@ -3,12 +3,12 @@ # of resources by test cases. # # Copyright (c) 2005-2010 Testresources Contributors -# +# # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not use this file except in # compliance with one of these two licences. -# +# # Unless required by applicable law or agreed to in writing, software distributed # under these licenses is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the license you chose @@ -25,24 +25,24 @@ def test_suite(): from testresources.tests import TestUtil + loader = TestUtil.TestLoader() result = loader.loadTestsFromName(__name__) return result class TestResourceGraph(testtools.TestCase): - def test_empty(self): no_resources = frozenset() resource_sets = [no_resources] - self.assertEqual({no_resources:set([])}, _resource_graph(resource_sets)) + self.assertEqual({no_resources: set([])}, _resource_graph(resource_sets)) def test_discrete(self): resset1 = frozenset([testresources.TestResourceManager()]) resset2 = frozenset([testresources.TestResourceManager()]) resource_sets = [resset1, resset2] result = _resource_graph(resource_sets) - self.assertEqual({resset1:set([]), resset2:set([])}, result) + self.assertEqual({resset1: set([]), resset2: set([])}, result) def test_overlapping(self): res1 = testresources.TestResourceManager() @@ -53,14 +53,16 @@ def test_overlapping(self): resource_sets = [resset1, resset2, resset3] result = _resource_graph(resource_sets) self.assertEqual( - {resset1:set([resset3]), - resset2:set([resset3]), - resset3:set([resset1, resset2])}, - result) + { + resset1: set([resset3]), + resset2: set([resset3]), + resset3: set([resset1, resset2]), + }, + result, + ) class TestDigraphToGraph(testtools.TestCase): - def test_wikipedia_example(self): """Converting a digraph mirrors it in the XZ axis (matrix view). @@ -70,37 +72,36 @@ def test_wikipedia_example(self): # A B C # A 1 2 # B 6 3 - # C 5 4 + # C 5 4 A = "A" Ap = "A'" B = "B" Bp = "B'" C = "C" Cp = "C'" - digraph = {A:{ B:1, C:2}, - B:{A:6, C:3}, - C:{A:5, B:4 }} + digraph = {A: {B: 1, C: 2}, B: {A: 6, C: 3}, C: {A: 5, B: 4}} # and the output # A B C A' B' C' # A 0 6 5 # B 1 0 4 # C 2 3 0 - # A' 0 1 2 - # B' 6 0 3 + # A' 0 1 2 + # B' 6 0 3 # C' 5 4 0 expected = { - A :{ Ap:0, Bp:6, Cp:5}, - B :{ Ap:1, Bp:0, Cp:4}, - C :{ Ap:2, Bp:3, Cp:0}, - Ap:{A:0, B:1, C:2 }, - Bp:{A:6, B:0, C:3 }, - Cp:{A:5, B:4, C:0 }} - self.assertEqual(expected, - testresources._digraph_to_graph(digraph, {A:Ap, B:Bp, C:Cp})) + A: {Ap: 0, Bp: 6, Cp: 5}, + B: {Ap: 1, Bp: 0, Cp: 4}, + C: {Ap: 2, Bp: 3, Cp: 0}, + Ap: {A: 0, B: 1, C: 2}, + Bp: {A: 6, B: 0, C: 3}, + Cp: {A: 5, B: 4, C: 0}, + } + self.assertEqual( + expected, testresources._digraph_to_graph(digraph, {A: Ap, B: Bp, C: Cp}) + ) class TestKruskalsMST(testtools.TestCase): - def test_wikipedia_example(self): """Performing KruskalsMST on a graph returns a spanning tree. @@ -114,24 +115,25 @@ def test_wikipedia_example(self): F = "F" G = "G" graph = { - A:{ B:7, D:5}, - B:{A:7, C:8, D:9, E:7}, - C:{ B:8, E:5}, - D:{A:5, B:9, E:15, F:6}, - E:{ B:7, C:5, D:15, F:8, G:9}, - F:{ D:6, E:8, G:11}, - G:{ E:9, F:11}} + A: {B: 7, D: 5}, + B: {A: 7, C: 8, D: 9, E: 7}, + C: {B: 8, E: 5}, + D: {A: 5, B: 9, E: 15, F: 6}, + E: {B: 7, C: 5, D: 15, F: 8, G: 9}, + F: {D: 6, E: 8, G: 11}, + G: {E: 9, F: 11}, + } expected = { - A:{ B:7, D:5}, - B:{A:7, E:7}, - C:{ E:5}, - D:{A:5, F:6}, - E:{ B:7, C:5, G:9}, - F:{ D:6}, - G:{ E:9}} + A: {B: 7, D: 5}, + B: {A: 7, E: 7}, + C: {E: 5}, + D: {A: 5, F: 6}, + E: {B: 7, C: 5, G: 9}, + F: {D: 6}, + G: {E: 9}, + } result = testresources._kruskals_graph_MST(graph) e_weight = sum(sum(row.values()) for row in expected.values()) r_weight = sum(sum(row.values()) for row in result.values()) self.assertEqual(e_weight, r_weight) - self.assertEqual(expected, - testresources._kruskals_graph_MST(graph)) + self.assertEqual(expected, testresources._kruskals_graph_MST(graph)) diff --git a/testresources/tests/test_resourced_test_case.py b/testresources/tests/test_resourced_test_case.py index 3c8a1b3..2209b8d 100644 --- a/testresources/tests/test_resourced_test_case.py +++ b/testresources/tests/test_resourced_test_case.py @@ -2,12 +2,12 @@ # of resources by test cases. # # Copyright (c) 2005-2010 Testresources Contributors -# +# # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not use this file except in # compliance with one of these two licences. -# +# # Unless required by applicable law or agreed to in writing, software distributed # under these licenses is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the license you chose @@ -43,25 +43,29 @@ class MockResourceInstance(object): class TestResourcedTestCase(testtools.TestCase): - def setUp(self): super(TestResourcedTestCase, self).setUp() + class Example(testresources.ResourcedTestCase): def test_example(self): pass - self.resourced_case = Example('test_example') + + self.resourced_case = Example("test_example") self.resource = self.getUniqueString() self.resource_manager = MockResource(self.resource) def testSetUpUsesSuper(self): class OtherBaseCase(unittest.TestCase): setUpCalled = False + def setUp(self): self.setUpCalled = True super(OtherBaseCase, self).setUp() + class OurCase(testresources.ResourcedTestCase, OtherBaseCase): def runTest(self): pass + ourCase = OurCase() ourCase.setUp() self.assertTrue(ourCase.setUpCalled) @@ -69,12 +73,15 @@ def runTest(self): def testTearDownUsesSuper(self): class OtherBaseCase(unittest.TestCase): tearDownCalled = False + def tearDown(self): self.tearDownCalled = True super(OtherBaseCase, self).setUp() + class OurCase(testresources.ResourcedTestCase, OtherBaseCase): def runTest(self): pass + ourCase = OurCase() ourCase.setUp() ourCase.tearDown() @@ -92,37 +99,41 @@ def testResultPassedToResources(self): def testSetUpResourcesSingle(self): # setUpResources installs the resources listed in ResourcedTestCase. self.resourced_case.resources = [("foo", self.resource_manager)] - testresources.setUpResources(self.resourced_case, - self.resourced_case.resources, None) + testresources.setUpResources( + self.resourced_case, self.resourced_case.resources, None + ) self.assertEqual(self.resource, self.resourced_case.foo) def testSetUpResourcesMultiple(self): # setUpResources installs the resources listed in ResourcedTestCase. self.resourced_case.resources = [ - ('foo', self.resource_manager), - ('bar', MockResource('bar_resource'))] - testresources.setUpResources(self.resourced_case, - self.resourced_case.resources, None) + ("foo", self.resource_manager), + ("bar", MockResource("bar_resource")), + ] + testresources.setUpResources( + self.resourced_case, self.resourced_case.resources, None + ) self.assertEqual(self.resource, self.resourced_case.foo) - self.assertEqual('bar_resource', self.resourced_case.bar) + self.assertEqual("bar_resource", self.resourced_case.bar) def testSetUpResourcesSetsUpDependences(self): resource = MockResourceInstance() self.resource_manager = MockResource(resource) - self.resourced_case.resources = [('foo', self.resource_manager)] + self.resourced_case.resources = [("foo", self.resource_manager)] # Give the 'foo' resource access to a 'bar' resource - self.resource_manager.resources.append( - ('bar', MockResource('bar_resource'))) - testresources.setUpResources(self.resourced_case, - self.resourced_case.resources, None) + self.resource_manager.resources.append(("bar", MockResource("bar_resource"))) + testresources.setUpResources( + self.resourced_case, self.resourced_case.resources, None + ) self.assertEqual(resource, self.resourced_case.foo) - self.assertEqual('bar_resource', self.resourced_case.foo.bar) + self.assertEqual("bar_resource", self.resourced_case.foo.bar) def testSetUpUsesResource(self): # setUpResources records a use of each declared resource. self.resourced_case.resources = [("foo", self.resource_manager)] - testresources.setUpResources(self.resourced_case, - self.resourced_case.resources, None) + testresources.setUpResources( + self.resourced_case, self.resourced_case.resources, None + ) self.assertEqual(self.resource_manager._uses, 1) def testTearDownResourcesDeletesResourceAttributes(self): @@ -141,12 +152,11 @@ def testTearDownResourcesStopsUsingResource(self): def testTearDownResourcesStopsUsingDependencies(self): resource = MockResourceInstance() - dep1 = MockResource('bar_resource') + dep1 = MockResource("bar_resource") self.resource_manager = MockResource(resource) - self.resourced_case.resources = [('foo', self.resource_manager)] + self.resourced_case.resources = [("foo", self.resource_manager)] # Give the 'foo' resource access to a 'bar' resource - self.resource_manager.resources.append( - ('bar', dep1)) + self.resource_manager.resources.append(("bar", dep1)) self.resourced_case.setUpResources() self.resourced_case.tearDownResources() self.assertEqual(dep1._uses, 0) diff --git a/testresources/tests/test_test_loader.py b/testresources/tests/test_test_loader.py index 7434949..8359a63 100644 --- a/testresources/tests/test_test_loader.py +++ b/testresources/tests/test_test_loader.py @@ -2,12 +2,12 @@ # of resources by test cases. # # Copyright (c) 2005-2010 Testresources Contributors -# +# # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not use this file except in # compliance with one of these two licences. -# +# # Unless required by applicable law or agreed to in writing, software distributed # under these licenses is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the license you chose @@ -27,7 +27,6 @@ def test_suite(): class TestTestLoader(testtools.TestCase): - def testSuiteType(self): # The testresources TestLoader loads tests into an # OptimisingTestSuite. diff --git a/testresources/tests/test_test_resource.py b/testresources/tests/test_test_resource.py index 1ba3b16..2501707 100644 --- a/testresources/tests/test_test_resource.py +++ b/testresources/tests/test_test_resource.py @@ -2,12 +2,12 @@ # of resources by test cases. # # Copyright (c) 2005-2010 Testresources Contributors -# +# # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not use this file except in # compliance with one of these two licences. -# +# # Unless required by applicable law or agreed to in writing, software distributed # under these licenses is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the license you chose @@ -22,7 +22,7 @@ from testresources.tests import ( ResultWithResourceExtensions, ResultWithoutResourceExtensions, - ) +) def test_suite(): @@ -32,7 +32,6 @@ def test_suite(): class MockResourceInstance(object): - def __init__(self, name): self._name = name @@ -74,7 +73,6 @@ def _reset(self, resource, dependency_resources): class TestTestResource(testtools.TestCase): - def testUnimplementedGetResource(self): # By default, TestResource raises NotImplementedError on getResource # because make is not defined initially. @@ -175,7 +173,7 @@ def testIsDirtyIsTrueIfDependenciesChanged(self): resource_manager.resources.append(("dep3", dep3)) r = resource_manager.getResource() dep2.dirtied(r.dep2) - r2 =dep2.getResource() + r2 = dep2.getResource() self.assertTrue(resource_manager.isDirty()) resource_manager.finishedWith(r) dep2.finishedWith(r2) @@ -384,8 +382,10 @@ def testFinishedActivityForResourceWithExtensions(self): result = ResultWithResourceExtensions() resource_manager = MockResource() r = resource_manager.getResource() - expected = [("clean", "start", resource_manager), - ("clean", "stop", resource_manager)] + expected = [ + ("clean", "start", resource_manager), + ("clean", "stop", resource_manager), + ] resource_manager.finishedWith(r, result) self.assertEqual(expected, result._calls) @@ -399,8 +399,10 @@ def testGetActivityForResourceWithExtensions(self): result = ResultWithResourceExtensions() resource_manager = MockResource() r = resource_manager.getResource(result) - expected = [("make", "start", resource_manager), - ("make", "stop", resource_manager)] + expected = [ + ("make", "start", resource_manager), + ("make", "stop", resource_manager), + ] resource_manager.finishedWith(r) self.assertEqual(expected, result._calls) @@ -419,9 +421,10 @@ def testResetActivityForResourceWithoutExtensions(self): def testResetActivityForResourceWithExtensions(self): result = ResultWithResourceExtensions() resource_manager = MockResource() - expected = [("reset", "start", resource_manager), + expected = [ + ("reset", "start", resource_manager), ("reset", "stop", resource_manager), - ] + ] resource_manager.getResource() r = resource_manager.getResource() resource_manager.dirtied(r) @@ -434,64 +437,84 @@ def testResetActivityForResourceWithExtensions(self): def testId(self): resource_manager = testresources.TestResource() - self.assertEqual( - "testresources.TestResourceManager", resource_manager.id()) + self.assertEqual("testresources.TestResourceManager", resource_manager.id()) class TestGenericResource(testtools.TestCase): - def test_default_uses_setUp_tearDown(self): calls = [] + class Wrapped: def setUp(self): - calls.append('setUp') + calls.append("setUp") + def tearDown(self): - calls.append('tearDown') + calls.append("tearDown") + mgr = testresources.GenericResource(Wrapped) resource = mgr.getResource() - self.assertEqual(['setUp'], calls) + self.assertEqual(["setUp"], calls) mgr.finishedWith(resource) - self.assertEqual(['setUp', 'tearDown'], calls) + self.assertEqual(["setUp", "tearDown"], calls) self.assertIsInstance(resource, Wrapped) def test_dependencies_passed_to_factory(self): calls = [] + class Wrapped: def __init__(self, **args): calls.append(args) - def setUp(self):pass - def tearDown(self):pass + + def setUp(self): + pass + + def tearDown(self): + pass + class Trivial(testresources.TestResource): def __init__(self, thing): testresources.TestResource.__init__(self) self.thing = thing - def make(self, dependency_resources):return self.thing - def clean(self, resource):pass + + def make(self, dependency_resources): + return self.thing + + def clean(self, resource): + pass + mgr = testresources.GenericResource(Wrapped) - mgr.resources = [('foo', Trivial('foo')), ('bar', Trivial('bar'))] + mgr.resources = [("foo", Trivial("foo")), ("bar", Trivial("bar"))] resource = mgr.getResource() - self.assertEqual([{'foo':'foo', 'bar':'bar'}], calls) + self.assertEqual([{"foo": "foo", "bar": "bar"}], calls) mgr.finishedWith(resource) def test_setup_teardown_controllable(self): calls = [] + class Wrapped: def start(self): - calls.append('setUp') + calls.append("setUp") + def stop(self): - calls.append('tearDown') - mgr = testresources.GenericResource(Wrapped, - setup_method_name='start', teardown_method_name='stop') + calls.append("tearDown") + + mgr = testresources.GenericResource( + Wrapped, setup_method_name="start", teardown_method_name="stop" + ) resource = mgr.getResource() - self.assertEqual(['setUp'], calls) + self.assertEqual(["setUp"], calls) mgr.finishedWith(resource) - self.assertEqual(['setUp', 'tearDown'], calls) + self.assertEqual(["setUp", "tearDown"], calls) self.assertIsInstance(resource, Wrapped) def test_always_dirty(self): class Wrapped: - def setUp(self):pass - def tearDown(self):pass + def setUp(self): + pass + + def tearDown(self): + pass + mgr = testresources.GenericResource(Wrapped) resource = mgr.getResource() self.assertTrue(mgr.isDirty()) @@ -499,23 +522,25 @@ def tearDown(self):pass def testId(self): class Wrapped: - def setUp(self):pass - def tearDown(self):pass + def setUp(self): + pass + + def tearDown(self): + pass + mgr = testresources.GenericResource(Wrapped) - self.assertEqual( - "testresources.GenericResource[Wrapped]", mgr.id()) + self.assertEqual("testresources.GenericResource[Wrapped]", mgr.id()) class TestFixtureResource(testtools.TestCase): - def test_uses_setUp_cleanUp(self): fixture = LoggingFixture() mgr = testresources.FixtureResource(fixture) resource = mgr.getResource() self.assertEqual(fixture, resource) - self.assertEqual(['setUp'], fixture.calls) + self.assertEqual(["setUp"], fixture.calls) mgr.finishedWith(resource) - self.assertEqual(['setUp', 'cleanUp'], fixture.calls) + self.assertEqual(["setUp", "cleanUp"], fixture.calls) def test_always_dirty(self): fixture = LoggingFixture() @@ -530,13 +555,12 @@ def test_reset_called(self): resource = mgr.getResource() mgr.reset(resource) mgr.finishedWith(resource) - self.assertEqual( - ['setUp', 'reset', 'cleanUp'], fixture.calls) + self.assertEqual(["setUp", "reset", "cleanUp"], fixture.calls) def testId(self): class MyLoggingFixture(LoggingFixture): def __str__(self): return "my-logger" + mgr = testresources.FixtureResource(MyLoggingFixture()) - self.assertEqual( - "testresources.FixtureResource[my-logger]", mgr.id()) + self.assertEqual("testresources.FixtureResource[my-logger]", mgr.id()) From 7843a4590f866a51ff448dc6df303be8c92c24a9 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 22 Apr 2025 10:26:55 +0000 Subject: [PATCH 3/3] Enforce ruff formatting in github --- .github/workflows/python-package.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml index 8bb0fae..ee0bdd6 100644 --- a/.github/workflows/python-package.yml +++ b/.github/workflows/python-package.yml @@ -27,6 +27,9 @@ jobs: - name: Lint with ruff run: | ruff check . + - name: Format with ruff + run: | + ruff format --check . - name: Test with testtools run: | python -m testtools.run testresources.tests.test_suite