Skip to content

Commit effb75c

Browse files
authored
Merge pull request #19 from testing-cabal/ruff-format
Format with ruff
2 parents f6db73f + 7843a45 commit effb75c

File tree

11 files changed

+356
-265
lines changed

11 files changed

+356
-265
lines changed

.github/workflows/python-package.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ jobs:
2727
- name: Lint with ruff
2828
run: |
2929
ruff check .
30+
- name: Format with ruff
31+
run: |
32+
ruff format --check .
3033
- name: Test with testtools
3134
run: |
3235
python -m testtools.run testresources.tests.test_suite

doc/example.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@
22
# of resources by test cases.
33
#
44
# Copyright (c) 2005-2010 Testresources Contributors
5-
#
5+
#
66
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
77
# license at the users choice. A copy of both licenses are available in the
88
# project source as Apache-2.0 and BSD. You may not use this file except in
99
# compliance with one of these two licences.
10-
#
10+
#
1111
# Unless required by applicable law or agreed to in writing, software distributed
1212
# under these licenses is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
1313
# CONDITIONS OF ANY KIND, either express or implied. See the license you chose
@@ -21,7 +21,6 @@
2121

2222

2323
class SampleTestResource(TestResourceManager):
24-
2524
setUpCost = 2
2625
tearDownCost = 2
2726

@@ -34,8 +33,7 @@ class MyResource(object):
3433

3534

3635
class SampleWithDependencies(TestResourceManager):
37-
38-
resources = [('foo', SampleTestResource()), ('bar', SampleTestResource())]
36+
resources = [("foo", SampleTestResource()), ("bar", SampleTestResource())]
3937

4038
def make(self, dependency_resources):
4139
# dependency_resources will be {'foo': result_of_make_in_foo, 'bar':

setup.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22

33
import setuptools
44

5-
setuptools.setup(setup_requires=['pbr>=1.3'], pbr=True)
5+
setuptools.setup(setup_requires=["pbr>=1.3"], pbr=True)

testresources/__init__.py

Lines changed: 46 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import heapq
2121
import inspect
2222
import unittest
23+
2324
try:
2425
from collections.abc import MutableSet
2526
except ImportError:
@@ -42,13 +43,15 @@
4243
# Otherwise it is major.minor.micro~$(revno).
4344

4445
from pbr.version import VersionInfo
45-
_version = VersionInfo('testresources')
46+
47+
_version = VersionInfo("testresources")
4648
__version__ = _version.semantic_version().version_tuple()
4749
version = _version.release_string()
4850

4951

5052
def test_suite():
5153
import testresources.tests
54+
5255
return testresources.tests.test_suite()
5356

5457

@@ -111,7 +114,7 @@ def _kruskals_graph_MST(graph):
111114
# combine g1 and g2 into g1
112115
graphs -= 1
113116
for from_node, to_nodes in g2.items():
114-
#remember its symmetric, don't need to do 'to'.
117+
# remember its symmetric, don't need to do 'to'.
115118
forest[from_node] = g1
116119
g1.setdefault(from_node, {}).update(to_nodes)
117120
# add edge
@@ -161,8 +164,7 @@ def split_by_resources(tests):
161164
resource_set_tests = {no_resources: []}
162165
for test in tests:
163166
resources = getattr(test, "resources", ())
164-
all_resources = list(resource.neededResources()
165-
for _, resource in resources)
167+
all_resources = list(resource.neededResources() for _, resource in resources)
166168
resource_set = set()
167169
for resource_list in all_resources:
168170
resource_set.update(resource_list)
@@ -206,8 +208,8 @@ class _OrderedSet(MutableSet):
206208

207209
def __init__(self, iterable=None):
208210
self.end = end = []
209-
end += [None, end, end] # sentinel node for doubly linked list
210-
self.map = {} # key --> [key, prev, next]
211+
end += [None, end, end] # sentinel node for doubly linked list
212+
self.map = {} # key --> [key, prev, next]
211213
if iterable is not None:
212214
self |= iterable
213215

@@ -274,8 +276,7 @@ def addTest(self, test_case_or_suite):
274276
self.adsorbSuite(test)
275277
else:
276278
for test in tests:
277-
unittest.TestSuite.addTest(
278-
self, test_case_or_suite.__class__([test]))
279+
unittest.TestSuite.addTest(self, test_case_or_suite.__class__([test]))
279280

280281
def cost_of_switching(self, old_resource_set, new_resource_set):
281282
"""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):
290291
"""
291292
new_resources = new_resource_set - old_resource_set
292293
gone_resources = old_resource_set - new_resource_set
293-
return (sum(resource.setUpCost for resource in new_resources) +
294-
sum(resource.tearDownCost for resource in gone_resources))
294+
return sum(resource.setUpCost for resource in new_resources) + sum(
295+
resource.tearDownCost for resource in gone_resources
296+
)
295297

296298
def switch(self, old_resource_set, new_resource_set, result):
297299
"""Switch from 'old_resource_set' to 'new_resource_set'.
@@ -321,7 +323,7 @@ def run(self, result):
321323
for test in self._tests:
322324
if result.shouldStop:
323325
break
324-
resources = getattr(test, 'resources', [])
326+
resources = getattr(test, "resources", [])
325327
new_resources = _OrderedSet()
326328
for name, resource in resources:
327329
new_resources.update(resource.neededResources())
@@ -357,8 +359,7 @@ def sortTests(self):
357359
resource_set_graph = _resource_graph(resource_set_tests)
358360
no_resources = frozenset()
359361
# A list of resource_set_tests, all fully internally connected.
360-
partitions = _strongly_connected_components(resource_set_graph,
361-
no_resources)
362+
partitions = _strongly_connected_components(resource_set_graph, no_resources)
362363
result = []
363364
for partition in partitions:
364365
# we process these at the end for no particularly good reason (it
@@ -384,30 +385,31 @@ def _getGraph(self, resource_sets):
384385
"""
385386
no_resources = frozenset()
386387
graph = {}
387-
root = set(['root'])
388+
root = set(["root"])
388389
# bottom = set(['bottom'])
389390
for from_set in resource_sets:
390391
graph[from_set] = {}
391392
if from_set == root:
392393
from_resources = no_resources
393-
#elif from_set == bottom:
394+
# elif from_set == bottom:
394395
# continue # no links from bottom
395396
else:
396397
from_resources = from_set
397398
for to_set in resource_sets:
398399
if from_set is to_set:
399400
continue # no self-edges
400-
#if to_set == bottom:
401+
# if to_set == bottom:
401402
# if from_set == root:
402403
# continue # no short cuts!
403404
# to_resources = no_resources
404-
#el
405+
# el
405406
if to_set == root:
406407
continue # no links to root
407408
else:
408409
to_resources = to_set
409410
graph[from_set][to_set] = self.cost_of_switching(
410-
from_resources, to_resources)
411+
from_resources, to_resources
412+
)
411413
return graph
412414

413415
def _makeOrder(self, partition):
@@ -419,7 +421,7 @@ def _makeOrder(self, partition):
419421
# http://en.wikipedia.org/wiki/Travelling_salesman_problem#Metric_TSP
420422

421423
# We need a root
422-
root = frozenset(['root'])
424+
root = frozenset(["root"])
423425
partition.add(root)
424426
# and an end
425427
# partition.add(frozenset(['bottom']))
@@ -428,7 +430,7 @@ def _makeOrder(self, partition):
428430
digraph = self._getGraph(partition)
429431
# build a prime map
430432
primes = {}
431-
prime = frozenset(['prime'])
433+
prime = frozenset(["prime"])
432434
for node in digraph:
433435
primes[node] = node.union(prime)
434436
graph = _digraph_to_graph(digraph, primes)
@@ -480,14 +482,14 @@ def _makeOrder(self, partition):
480482
return order[1:]
481483

482484

483-
OptimisingTestSuite.known_suite_classes = (
484-
unittest.TestSuite, OptimisingTestSuite)
485+
OptimisingTestSuite.known_suite_classes = (unittest.TestSuite, OptimisingTestSuite)
485486
if unittest2 is not None:
486487
OptimisingTestSuite.known_suite_classes += (unittest2.TestSuite,)
487488

488489

489490
class TestLoader(unittest.TestLoader):
490491
"""Custom TestLoader to set the right TestSuite class."""
492+
491493
suiteClass = OptimisingTestSuite
492494

493495

@@ -624,8 +626,7 @@ def make(self, dependency_resources):
624626
for the resources specified as dependencies.
625627
:return: The made resource.
626628
"""
627-
raise NotImplementedError(
628-
"Override make to construct resources.")
629+
raise NotImplementedError("Override make to construct resources.")
629630

630631
def neededResources(self):
631632
"""Return the resources needed for this resource, including self.
@@ -647,7 +648,7 @@ def reset(self, old_resource, result=None):
647648
is part of the public interface, but _make_all and _clean_all is not.
648649
649650
Note that if a resource A holds a lock or other blocking thing on
650-
a dependency D, reset will result in this call sequence over a
651+
a dependency D, reset will result in this call sequence over a
651652
getResource(), dirty(), getResource(), finishedWith(), finishedWith()
652653
sequence:
653654
B.make(), A.make(), B.reset(), A.reset(), A.clean(), B.clean()
@@ -679,8 +680,7 @@ def reset(self, old_resource, result=None):
679680
self._call_result_method_if_exists(result, "startResetResource", self)
680681
dependency_resources = {}
681682
for name, mgr in self.resources:
682-
dependency_resources[name] = mgr.reset(
683-
getattr(old_resource, name), result)
683+
dependency_resources[name] = mgr.reset(getattr(old_resource, name), result)
684684
resource = self._reset(old_resource, dependency_resources)
685685
for name, value in dependency_resources.items():
686686
setattr(resource, name, value)
@@ -723,6 +723,8 @@ def _setResource(self, new_resource):
723723
"""Set the current resource to a new value."""
724724
self._currentResource = new_resource
725725
self._dirty = False
726+
727+
726728
TestResource = TestResourceManager
727729

728730

@@ -741,9 +743,13 @@ class GenericResource(TestResourceManager):
741743
method.
742744
"""
743745

744-
def __init__(self, resource_factory, setup_method_name='setUp',
745-
teardown_method_name='tearDown',
746-
id_attribute_name="__name__"):
746+
def __init__(
747+
self,
748+
resource_factory,
749+
setup_method_name="setUp",
750+
teardown_method_name="tearDown",
751+
id_attribute_name="__name__",
752+
):
747753
"""Create a GenericResource
748754
749755
:param resource_factory: A factory to create a new resource.
@@ -779,7 +785,8 @@ def id(self):
779785
"""
780786
return "%s[%s]" % (
781787
super(GenericResource, self).id(),
782-
getattr(self.resource_factory, self.id_attribute_name))
788+
getattr(self.resource_factory, self.id_attribute_name),
789+
)
783790

784791

785792
class FixtureResource(TestResourceManager):
@@ -823,8 +830,7 @@ def id(self):
823830
824831
The default is to call str(fixture) to get such information.
825832
"""
826-
return "%s[%s]" % (
827-
super(FixtureResource, self).id(), str(self.fixture))
833+
return "%s[%s]" % (super(FixtureResource, self).id(), str(self.fixture))
828834

829835
def _reset(self, resource, dependency_resources):
830836
self.fixture.reset()
@@ -833,7 +839,7 @@ def _reset(self, resource, dependency_resources):
833839
def isDirty(self):
834840
return True
835841

836-
_dirty = property(lambda _:True, lambda _, _1:None)
842+
_dirty = property(lambda _: True, lambda _, _1: None)
837843

838844

839845
class ResourcedTestCase(unittest.TestCase):
@@ -901,8 +907,9 @@ def neededResources(resources):
901907
result = []
902908

903909
for resource in resources:
904-
dependencies = neededResources([
905-
dependency for name, dependency in resource.resources])
910+
dependencies = neededResources(
911+
[dependency for name, dependency in resource.resources]
912+
)
906913
for resource in dependencies + [resource]:
907914
if resource in seen:
908915
continue
@@ -924,10 +931,9 @@ def _get_result():
924931
"""
925932
stack = inspect.stack()
926933
for frame in stack[2:]:
927-
if frame[3] in ('run', '__call__'):
934+
if frame[3] in ("run", "__call__"):
928935
# Not all frames called 'run' will be unittest. It could be a
929936
# reactor in trial, for instance.
930-
result = frame[0].f_locals.get('result')
931-
if (result is not None and
932-
getattr(result, 'startTest', None) is not None):
937+
result = frame[0].f_locals.get("result")
938+
if result is not None and getattr(result, "startTest", None) is not None:
933939
return result

testresources/tests/TestUtil.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,17 @@
2323
class LogCollector(logging.Handler):
2424
def __init__(self):
2525
logging.Handler.__init__(self)
26-
self.records=[]
26+
self.records = []
27+
2728
def emit(self, record):
2829
self.records.append(record.getMessage())
2930

3031

3132
def makeCollectingLogger():
3233
"""I make a logger instance that collects its logs for programmatic analysis
3334
-> (logger, collector)"""
34-
logger=logging.Logger("collector")
35-
handler=LogCollector()
35+
logger = logging.Logger("collector")
36+
handler = LogCollector()
3637
handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
3738
logger.addHandler(handler)
3839
return logger, handler
@@ -44,7 +45,7 @@ def visitTests(suite, visitor):
4445
visitor.visitCase(suite)
4546
return
4647
for test in suite._tests:
47-
#Abusing types to avoid monkey patching unittest.TestCase.
48+
# Abusing types to avoid monkey patching unittest.TestCase.
4849
# Maybe that would be better?
4950
try:
5051
test.visit(visitor)
@@ -55,7 +56,10 @@ def visitTests(suite, visitor):
5556
visitor.visitSuite(test)
5657
visitTests(test, visitor)
5758
else:
58-
print("unvisitable non-unittest.TestCase element %r (%r)" % (test, test.__class__))
59+
print(
60+
"unvisitable non-unittest.TestCase element %r (%r)"
61+
% (test, test.__class__)
62+
)
5963

6064

6165
class TestSuite(unittest.TestSuite):
@@ -72,11 +76,15 @@ def visit(self, visitor):
7276

7377
class TestLoader(unittest.TestLoader):
7478
"""Custome TestLoader to set the right TestSuite class."""
79+
7580
suiteClass = TestSuite
7681

82+
7783
class TestVisitor(object):
7884
"""A visitor for Tests"""
85+
7986
def visitSuite(self, aTestSuite):
8087
pass
88+
8189
def visitCase(self, aTestCase):
8290
pass

0 commit comments

Comments
 (0)