From 2eafa60edf0b928ce55582506b58a9fd6a9506c4 Mon Sep 17 00:00:00 2001 From: Stephen Finucane Date: Fri, 31 Mar 2023 10:22:54 +0100 Subject: [PATCH 1/3] Fix invalid docstring Sphinx moans about this: Inline emphasis start-string without end-string. Signed-off-by: Stephen Finucane --- fixtures/fixture.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fixtures/fixture.py b/fixtures/fixture.py index e0ad4c7..a94a214 100644 --- a/fixtures/fixture.py +++ b/fixtures/fixture.py @@ -78,7 +78,7 @@ def addCleanup(self, cleanup, *args, **kwargs): self._clear_cleanups. :param cleanup: A callable to call during cleanUp. - :param *args: Positional args for cleanup. + :param args: Positional args for cleanup. :param kwargs: Keyword args for cleanup. :return: None """ From 9402d8dcdf7b0a1a1e004f56b7bcfc0070fa9f60 Mon Sep 17 00:00:00 2001 From: Stephen Finucane Date: Fri, 31 Mar 2023 10:23:29 +0100 Subject: [PATCH 2/3] Trivial style fixes Mostly stripping errant whitespace. Signed-off-by: Stephen Finucane --- fixtures/__init__.py | 8 +- fixtures/_fixtures/__init__.py | 22 +- fixtures/_fixtures/environ.py | 4 +- fixtures/_fixtures/logger.py | 25 +- fixtures/_fixtures/monkeypatch.py | 7 +- fixtures/_fixtures/packagepath.py | 8 +- fixtures/_fixtures/popen.py | 101 +++++--- fixtures/_fixtures/pythonpackage.py | 8 +- fixtures/_fixtures/pythonpath.py | 10 +- fixtures/_fixtures/streams.py | 6 +- fixtures/_fixtures/tempdir.py | 6 +- fixtures/_fixtures/temphomedir.py | 2 +- fixtures/_fixtures/timeout.py | 4 +- fixtures/callmany.py | 3 +- fixtures/fixture.py | 10 +- fixtures/testcase.py | 11 +- fixtures/tests/__init__.py | 5 +- fixtures/tests/_fixtures/test_environ.py | 9 +- fixtures/tests/_fixtures/test_logger.py | 23 +- fixtures/tests/_fixtures/test_mockpatch.py | 15 +- fixtures/tests/_fixtures/test_monkeypatch.py | 218 +++++++++++------- fixtures/tests/_fixtures/test_packagepath.py | 7 +- fixtures/tests/_fixtures/test_popen.py | 64 +++-- .../tests/_fixtures/test_pythonpackage.py | 21 +- fixtures/tests/_fixtures/test_pythonpath.py | 7 +- fixtures/tests/_fixtures/test_streams.py | 5 +- fixtures/tests/_fixtures/test_tempdir.py | 17 +- fixtures/tests/_fixtures/test_temphomedir.py | 4 +- fixtures/tests/_fixtures/test_timeout.py | 18 +- fixtures/tests/_fixtures/test_warnings.py | 13 +- fixtures/tests/helpers.py | 6 +- fixtures/tests/test_callmany.py | 11 +- fixtures/tests/test_fixture.py | 86 +++++-- fixtures/tests/test_testcase.py | 36 ++- 34 files changed, 511 insertions(+), 289 deletions(-) diff --git a/fixtures/__init__.py b/fixtures/__init__.py index a4b9808..ad2e33f 100644 --- a/fixtures/__init__.py +++ b/fixtures/__init__.py @@ -37,6 +37,7 @@ # If the releaselevel is 'final', then the tarball will be major.minor.micro. # Otherwise it is major.minor.micro~$(revno). from pbr.version import VersionInfo + _version = VersionInfo('fixtures') __version__ = _version.semantic_version().version_tuple() version = _version.release_string() @@ -76,7 +77,7 @@ 'WarningsFilter', '__version__', 'version', - ] +] from fixtures.fixture import ( @@ -86,7 +87,7 @@ MethodFixture, MultipleExceptions, SetupError, - ) +) from fixtures._fixtures import ( ByteStream, DetailStream, @@ -112,12 +113,13 @@ TimeoutException, WarningsCapture, WarningsFilter, - ) +) from fixtures.testcase import TestWithFixtures def test_suite(): import fixtures.tests + return fixtures.tests.test_suite() diff --git a/fixtures/_fixtures/__init__.py b/fixtures/_fixtures/__init__.py index a1bca03..0359bfc 100644 --- a/fixtures/_fixtures/__init__.py +++ b/fixtures/_fixtures/__init__.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2010, 2011, Robert Collins -# +# # 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 @@ -47,22 +47,22 @@ from fixtures._fixtures.environ import ( EnvironmentVariable, EnvironmentVariableFixture, - ) +) from fixtures._fixtures.logger import ( FakeLogger, LoggerFixture, LogHandler, - ) +) from fixtures._fixtures.mockpatch import ( MockPatch, MockPatchMultiple, MockPatchObject, - ) +) from fixtures._fixtures.monkeypatch import MonkeyPatch from fixtures._fixtures.popen import ( FakePopen, PopenFixture, - ) +) from fixtures._fixtures.packagepath import PackagePathEntry from fixtures._fixtures.pythonpackage import PythonPackage from fixtures._fixtures.pythonpath import PythonPathEntry @@ -70,19 +70,19 @@ ByteStream, DetailStream, StringStream, - ) +) from fixtures._fixtures.tempdir import ( NestedTempfile, TempDir, - ) +) from fixtures._fixtures.temphomedir import ( TempHomeDir, - ) +) from fixtures._fixtures.timeout import ( Timeout, TimeoutException, - ) +) from fixtures._fixtures.warnings import ( WarningsCapture, WarningsFilter, - ) +) diff --git a/fixtures/_fixtures/environ.py b/fixtures/_fixtures/environ.py index e4275f9..6052f0d 100644 --- a/fixtures/_fixtures/environ.py +++ b/fixtures/_fixtures/environ.py @@ -15,8 +15,8 @@ __all__ = [ 'EnvironmentVariable', - 'EnvironmentVariableFixture' - ] + 'EnvironmentVariableFixture', +] import os diff --git a/fixtures/_fixtures/logger.py b/fixtures/_fixtures/logger.py index 6f9f0a2..f405e38 100644 --- a/fixtures/_fixtures/logger.py +++ b/fixtures/_fixtures/logger.py @@ -23,7 +23,7 @@ 'FakeLogger', 'LoggerFixture', 'LogHandler', - ] +] class LogHandler(Fixture): @@ -62,6 +62,7 @@ def _setUp(self): class StreamHandlerRaiseException(StreamHandler): """Handler class that will raise an exception on formatting errors.""" + def handleError(self, record): _, value, tb = sys.exc_info() raise value.with_traceback(tb) @@ -70,8 +71,15 @@ def handleError(self, record): class FakeLogger(Fixture): """Replace a logger and capture its output.""" - def __init__(self, name="", level=INFO, format=None, - datefmt=None, nuke_handlers=True, formatter=None): + def __init__( + self, + name="", + level=INFO, + format=None, + datefmt=None, + nuke_handlers=True, + formatter=None, + ): """Create a FakeLogger fixture. :param name: The name of the logger to replace. Defaults to "". @@ -106,11 +114,16 @@ def _setUp(self): self._output = output handler = StreamHandlerRaiseException(output) if self._format: - formatter = (self._formatter or Formatter) + formatter = self._formatter or Formatter handler.setFormatter(formatter(self._format, self._datefmt)) self.useFixture( - LogHandler(handler, name=self._name, level=self._level, - nuke_handlers=self._nuke_handlers)) + LogHandler( + handler, + name=self._name, + level=self._level, + nuke_handlers=self._nuke_handlers, + ) + ) @property def output(self): diff --git a/fixtures/_fixtures/monkeypatch.py b/fixtures/_fixtures/monkeypatch.py index 3d9545e..1e4bd87 100644 --- a/fixtures/_fixtures/monkeypatch.py +++ b/fixtures/_fixtures/monkeypatch.py @@ -14,7 +14,7 @@ # limitations under that license. __all__ = [ - 'MonkeyPatch' + 'MonkeyPatch', ] import functools @@ -23,7 +23,7 @@ from fixtures import Fixture -_class_types = (type, ) +_class_types = (type,) def _coerce_values(obj, name, new_value, sentinel): @@ -144,7 +144,8 @@ def _setUp(self): current = getattr(current, component) sentinel = object() new_value, old_value = _coerce_values( - current, attribute, self.new_value, sentinel) + current, attribute, self.new_value, sentinel + ) if self.new_value is self.delete: if old_value is not sentinel: diff --git a/fixtures/_fixtures/packagepath.py b/fixtures/_fixtures/packagepath.py index 86b7925..739dab5 100644 --- a/fixtures/_fixtures/packagepath.py +++ b/fixtures/_fixtures/packagepath.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2011, Robert Collins -# +# # 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 @@ -14,8 +14,8 @@ # limitations under that license. __all__ = [ - 'PackagePathEntry' - ] + 'PackagePathEntry', +] import sys diff --git a/fixtures/_fixtures/popen.py b/fixtures/_fixtures/popen.py index a099854..469fdcc 100644 --- a/fixtures/_fixtures/popen.py +++ b/fixtures/_fixtures/popen.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2010, 2011, Robert Collins -# +# # 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 @@ -15,8 +15,8 @@ __all__ = [ 'FakePopen', - 'PopenFixture' - ] + 'PopenFixture', +] import random import subprocess @@ -90,7 +90,7 @@ class FakePopen(Fixture): _unpassed = object() - def __init__(self, get_info=lambda _:{}): + def __init__(self, get_info=lambda _: {}): """Create a PopenFixture :param get_info: Optional callback to control the behaviour of the @@ -100,7 +100,7 @@ def __init__(self, get_info=lambda _:{}): dict, making it possible to detect the difference between 'passed with a default value' and 'not passed at all'. - e.g. + e.g. def get_info(proc_args): self.assertEqual(subprocess.PIPE, proc_args['stdin']) return {'stdin': StringIO('foobar')} @@ -123,47 +123,94 @@ def _setUp(self): # The method has the correct signature so we error appropriately if called # wrongly. - def __call__(self, args, bufsize=_unpassed, executable=_unpassed, - stdin=_unpassed, stdout=_unpassed, stderr=_unpassed, - preexec_fn=_unpassed, close_fds=_unpassed, shell=_unpassed, - cwd=_unpassed, env=_unpassed, universal_newlines=_unpassed, - startupinfo=_unpassed, creationflags=_unpassed, - restore_signals=_unpassed, start_new_session=_unpassed, - pass_fds=_unpassed, *, group=_unpassed, extra_groups=_unpassed, - user=_unpassed, umask=_unpassed, encoding=_unpassed, - errors=_unpassed, text=_unpassed, pipesize=_unpassed, - process_group=_unpassed): + def __call__( + self, + args, + bufsize=_unpassed, + executable=_unpassed, + stdin=_unpassed, + stdout=_unpassed, + stderr=_unpassed, + preexec_fn=_unpassed, + close_fds=_unpassed, + shell=_unpassed, + cwd=_unpassed, + env=_unpassed, + universal_newlines=_unpassed, + startupinfo=_unpassed, + creationflags=_unpassed, + restore_signals=_unpassed, + start_new_session=_unpassed, + pass_fds=_unpassed, + *, + group=_unpassed, + extra_groups=_unpassed, + user=_unpassed, + umask=_unpassed, + encoding=_unpassed, + errors=_unpassed, + text=_unpassed, + pipesize=_unpassed, + process_group=_unpassed + ): # Reject arguments introduced by newer versions of Python in older # versions; this makes it harder to accidentally hide compatibility # problems using test doubles. if sys.version_info < (3, 7) and text is not FakePopen._unpassed: raise TypeError( "FakePopen.__call__() got an unexpected keyword argument " - "'text'") + "'text'" + ) if sys.version_info < (3, 9): for arg_name in "group", "extra_groups", "user", "umask": if locals()[arg_name] is not FakePopen._unpassed: raise TypeError( "FakePopen.__call__() got an unexpected keyword " - "argument '{}'".format(arg_name)) + "argument '{}'".format(arg_name) + ) if sys.version_info < (3, 10) and pipesize is not FakePopen._unpassed: raise TypeError( "FakePopen.__call__() got an unexpected keyword argument " - "'pipesize'") - if sys.version_info < (3, 11) and process_group is not FakePopen._unpassed: + "'pipesize'" + ) + if ( + sys.version_info < (3, 11) + and process_group is not FakePopen._unpassed + ): raise TypeError( "FakePopen.__call__() got an unexpected keyword argument " - "'process_group'") + "'process_group'" + ) proc_args = dict(args=args) local = locals() for param in [ - "bufsize", "executable", "stdin", "stdout", "stderr", - "preexec_fn", "close_fds", "shell", "cwd", "env", - "universal_newlines", "startupinfo", "creationflags", - "restore_signals", "start_new_session", "pass_fds", "group", - "extra_groups", "user", "umask", "encoding", "errors", "text", - "pipesize", "process_group"]: + "bufsize", + "executable", + "stdin", + "stdout", + "stderr", + "preexec_fn", + "close_fds", + "shell", + "cwd", + "env", + "universal_newlines", + "startupinfo", + "creationflags", + "restore_signals", + "start_new_session", + "pass_fds", + "group", + "extra_groups", + "user", + "umask", + "encoding", + "errors", + "text", + "pipesize", + "process_group", + ]: if local[param] is not FakePopen._unpassed: proc_args[param] = local[param] proc_info = self.get_info(proc_args) diff --git a/fixtures/_fixtures/pythonpackage.py b/fixtures/_fixtures/pythonpackage.py index 97ccc16..7488bd8 100644 --- a/fixtures/_fixtures/pythonpackage.py +++ b/fixtures/_fixtures/pythonpackage.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2010, Robert Collins -# +# # 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 @@ -14,8 +14,8 @@ # limitations under that license. __all__ = [ - 'PythonPackage' - ] + 'PythonPackage', +] import os.path diff --git a/fixtures/_fixtures/pythonpath.py b/fixtures/_fixtures/pythonpath.py index ca11a43..fb2c4c5 100644 --- a/fixtures/_fixtures/pythonpath.py +++ b/fixtures/_fixtures/pythonpath.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2011, Robert Collins -# +# # 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 @@ -14,8 +14,8 @@ # limitations under that license. __all__ = [ - 'PythonPathEntry' - ] + 'PythonPathEntry', +] import sys @@ -24,7 +24,7 @@ class PythonPathEntry(Fixture): """Add a path to sys.path. - + If the path is already in sys.path, sys.path will not be altered. """ diff --git a/fixtures/_fixtures/streams.py b/fixtures/_fixtures/streams.py index c0fb60a..767d63b 100644 --- a/fixtures/_fixtures/streams.py +++ b/fixtures/_fixtures/streams.py @@ -17,7 +17,7 @@ 'ByteStream', 'DetailStream', 'StringStream', - ] +] import io @@ -47,8 +47,8 @@ def _setUp(self): write_stream, read_stream = self._stream_factory() self.stream = write_stream self.addDetail( - self._detail_name, - content_from_stream(read_stream, seek_offset=0)) + self._detail_name, content_from_stream(read_stream, seek_offset=0) + ) def _byte_stream_factory(): diff --git a/fixtures/_fixtures/tempdir.py b/fixtures/_fixtures/tempdir.py index 78b4d3e..68fb855 100644 --- a/fixtures/_fixtures/tempdir.py +++ b/fixtures/_fixtures/tempdir.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2010, Robert Collins -# +# # 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 @@ -16,7 +16,7 @@ __all__ = [ 'NestedTempfile', 'TempDir', - ] +] import os import shutil diff --git a/fixtures/_fixtures/temphomedir.py b/fixtures/_fixtures/temphomedir.py index 2fcceb9..43fc5cd 100644 --- a/fixtures/_fixtures/temphomedir.py +++ b/fixtures/_fixtures/temphomedir.py @@ -15,7 +15,7 @@ __all__ = [ 'TempHomeDir', - ] +] import fixtures from fixtures._fixtures.tempdir import TempDir diff --git a/fixtures/_fixtures/timeout.py b/fixtures/_fixtures/timeout.py index 9c6fb99..cee339b 100644 --- a/fixtures/_fixtures/timeout.py +++ b/fixtures/_fixtures/timeout.py @@ -6,7 +6,7 @@ # 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 @@ -24,7 +24,7 @@ __all__ = [ 'Timeout', 'TimeoutException', - ] +] class TimeoutException(Exception): diff --git a/fixtures/callmany.py b/fixtures/callmany.py index b1785b4..e17c935 100644 --- a/fixtures/callmany.py +++ b/fixtures/callmany.py @@ -15,7 +15,7 @@ __all__ = [ 'CallMany', - ] +] import sys @@ -23,6 +23,7 @@ try: from testtools import MultipleExceptions except ImportError: + class MultipleExceptions(Exception): """Report multiple exc_info tuples in self.args.""" diff --git a/fixtures/fixture.py b/fixtures/fixture.py index a94a214..fe028b5 100644 --- a/fixtures/fixture.py +++ b/fixtures/fixture.py @@ -20,7 +20,7 @@ 'MethodFixture', 'MultipleExceptions', 'SetupError', - ] +] import itertools import sys @@ -29,7 +29,7 @@ CallMany, # Deprecated, imported for compatibility. MultipleExceptions, - ) +) try: @@ -305,9 +305,9 @@ def setup_fn(): return 42 The result of setup_fn is assigned to the fn_result attribute bu FunctionFixture.setUp. - :param cleanup_fn: Optional callable which takes a single parameter, which - must be that which is returned from the setup_fn. This is called - from cleanUp. + :param cleanup_fn: Optional callable which takes a single parameter, + which must be that which is returned from the setup_fn. This is + called from cleanUp. :param reset_fn: Optional callable which takes a single parameter like cleanup_fn, but also returns a new object for use as the fn_result: if defined this replaces the use of cleanup_fn and setup_fn when diff --git a/fixtures/testcase.py b/fixtures/testcase.py index d7999f3..426ff62 100644 --- a/fixtures/testcase.py +++ b/fixtures/testcase.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2010, Robert Collins -# +# # 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 @@ -15,7 +15,7 @@ __all__ = [ 'TestWithFixtures', - ] +] import unittest @@ -41,8 +41,9 @@ def useFixture(self, fixture): it. """ use_details = ( - gather_details is not None and - getattr(self, "addDetail", None) is not None) + gather_details is not None + and getattr(self, "addDetail", None) is not None + ) try: fixture.setUp() except: diff --git a/fixtures/tests/__init__.py b/fixtures/tests/__init__.py index 827091e..bb2e23e 100644 --- a/fixtures/tests/__init__.py +++ b/fixtures/tests/__init__.py @@ -28,12 +28,13 @@ def load_tests(loader, standard_tests, pattern): 'callmany', 'fixture', 'testcase', - ] + ] prefix = "fixtures.tests.test_" test_mod_names = [prefix + test_module for test_module in test_modules] standard_tests.addTests(loader.loadTestsFromNames(test_mod_names)) standard_tests.addTests( - loader.loadTestsFromName('fixtures.tests._fixtures')) + loader.loadTestsFromName('fixtures.tests._fixtures') + ) doctest.set_unittest_reportflags(doctest.REPORT_ONLY_FIRST_FAILURE) standard_tests.addTest(doctest.DocFileSuite("../../README.rst")) return standard_tests diff --git a/fixtures/tests/_fixtures/test_environ.py b/fixtures/tests/_fixtures/test_environ.py index 64594c9..27b7eb9 100644 --- a/fixtures/tests/_fixtures/test_environ.py +++ b/fixtures/tests/_fixtures/test_environ.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2010, 2011, Robert Collins -# +# # 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 @@ -21,7 +21,6 @@ class TestEnvironmentVariable(testtools.TestCase, TestWithFixtures): - def test_setup_ignores_missing(self): fixture = EnvironmentVariable('FIXTURES_TEST_VAR') os.environ.pop('FIXTURES_TEST_VAR', '') @@ -52,7 +51,7 @@ def test_cleanup_deletes_when_missing(self): with fixture: os.environ['FIXTURES_TEST_VAR'] = 'foo' self.assertEqual(None, os.environ.get('FIXTURES_TEST_VAR')) - + def test_cleanup_deletes_when_set(self): fixture = EnvironmentVariable('FIXTURES_TEST_VAR', 'bar') os.environ.pop('FIXTURES_TEST_VAR', '') @@ -66,7 +65,7 @@ def test_cleanup_restores_when_missing(self): with fixture: os.environ.pop('FIXTURES_TEST_VAR', '') self.assertEqual('bar', os.environ.get('FIXTURES_TEST_VAR')) - + def test_cleanup_restores_when_set(self): fixture = EnvironmentVariable('FIXTURES_TEST_VAR') os.environ['FIXTURES_TEST_VAR'] = 'bar' diff --git a/fixtures/tests/_fixtures/test_logger.py b/fixtures/tests/_fixtures/test_logger.py index 5a28246..95703f0 100644 --- a/fixtures/tests/_fixtures/test_logger.py +++ b/fixtures/tests/_fixtures/test_logger.py @@ -24,7 +24,7 @@ FakeLogger, LogHandler, TestWithFixtures, - ) +) # A simple custom formatter that prepends Foo to all log messages, for @@ -37,7 +37,6 @@ def format(self, record): class FakeLoggerTest(TestCase, TestWithFixtures): - def setUp(self): super(FakeLoggerTest, self).setUp() self.logger = logging.getLogger() @@ -93,23 +92,25 @@ def test_custom_format(self): self.assertEqual("test_logger\n", fixture.output) def test_custom_datefmt(self): - fixture = FakeLogger(format="%(asctime)s %(module)s", - datefmt="%Y") + fixture = FakeLogger(format="%(asctime)s %(module)s", datefmt="%Y") self.useFixture(fixture) logging.info("message") self.assertEqual( - time.strftime("%Y test_logger\n", time.localtime()), - fixture.output) + time.strftime("%Y test_logger\n", time.localtime()), fixture.output + ) def test_custom_formatter(self): - fixture = FakeLogger(format="%(asctime)s %(module)s", - formatter=FooFormatter, - datefmt="%Y") + fixture = FakeLogger( + format="%(asctime)s %(module)s", + formatter=FooFormatter, + datefmt="%Y", + ) self.useFixture(fixture) logging.info("message") self.assertEqual( time.strftime("Foo %Y test_logger\n", time.localtime()), - fixture.output) + fixture.output, + ) def test_logging_output_included_in_details(self): fixture = FakeLogger() @@ -152,9 +153,7 @@ def test_output_can_be_reset(self): class LogHandlerTest(TestCase, TestWithFixtures): - class CustomHandler(logging.Handler): - def __init__(self, *args, **kwargs): """Create the instance, and add a records attribute.""" logging.Handler.__init__(self, *args, **kwargs) diff --git a/fixtures/tests/_fixtures/test_mockpatch.py b/fixtures/tests/_fixtures/test_mockpatch.py index ee7706a..5ac4699 100644 --- a/fixtures/tests/_fixtures/test_mockpatch.py +++ b/fixtures/tests/_fixtures/test_mockpatch.py @@ -13,7 +13,7 @@ # under the License. -import mock # Yes, we only test the rolling backport +import mock # Yes, we only test the rolling backport import testtools from fixtures import ( @@ -46,15 +46,18 @@ def test_mock_patch_without_replacement(self): class TestMockMultiple(testtools.TestCase): def test_mock_multiple_with_replacement(self): - self.useFixture(MockPatchMultiple('%s.Foo' % (__name__), - bar=mocking_bar)) + self.useFixture( + MockPatchMultiple('%s.Foo' % (__name__), bar=mocking_bar) + ) instance = Foo() self.assertEqual(instance.bar(), 'mocked!') def test_mock_patch_without_replacement(self): - self.useFixture(MockPatchMultiple( - '%s.Foo' % (__name__), - bar=MockPatchMultiple.DEFAULT)) + self.useFixture( + MockPatchMultiple( + '%s.Foo' % (__name__), bar=MockPatchMultiple.DEFAULT + ) + ) instance = Foo() self.assertIsInstance(instance.bar(), mock.MagicMock) diff --git a/fixtures/tests/_fixtures/test_monkeypatch.py b/fixtures/tests/_fixtures/test_monkeypatch.py index fa08b24..34a3ec2 100644 --- a/fixtures/tests/_fixtures/test_monkeypatch.py +++ b/fixtures/tests/_fixtures/test_monkeypatch.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2010, Robert Collins -# +# # 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 @@ -23,53 +23,81 @@ reference = 23 -NEW_PY39_CLASSMETHOD = ( - sys.version_info[:2] in ((3, 9), (3,10)) - and not hasattr(sys, "pypy_version_info")) +NEW_PY39_CLASSMETHOD = sys.version_info[:2] in ( + (3, 9), + (3, 10), +) and not hasattr(sys, "pypy_version_info") + class C(object): def foo(self, arg): return arg + @staticmethod - def foo_static(): pass + def foo_static(): + pass + @classmethod - def foo_cls(cls): pass + def foo_cls(cls): + pass + class D(object): - def bar(self): pass + def bar(self): + pass + def bar_two_args(self, arg=None): return (self, arg) + @classmethod def bar_cls(cls): return cls + @classmethod def bar_cls_args(cls, *args): return (cls,) + args + @staticmethod def bar_static(): pass + @staticmethod def bar_static_args(*args): return args + def bar_self_referential(self, *args, **kwargs): self.bar() + INST_C = C() + def fake(*args): return args -def fake2(arg): pass -def fake_no_args(): pass -def fake_no_args2(): pass + + +def fake2(arg): + pass + + +def fake_no_args(): + pass + + +def fake_no_args2(): + pass + + @staticmethod -def fake_static(): pass +def fake_static(): + pass class TestMonkeyPatch(testtools.TestCase, TestWithFixtures): - def test_patch_and_restore(self): fixture = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.reference', 45) + 'fixtures.tests._fixtures.test_monkeypatch.reference', 45 + ) self.assertEqual(23, reference) fixture.setUp() try: @@ -80,7 +108,8 @@ def test_patch_and_restore(self): def test_patch_missing_attribute(self): fixture = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.new_attr', True) + 'fixtures.tests._fixtures.test_monkeypatch.new_attr', True + ) self.assertFalse('new_attr' in globals()) fixture.setUp() try: @@ -92,7 +121,8 @@ def test_patch_missing_attribute(self): def test_delete_existing_attribute(self): fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.reference', - MonkeyPatch.delete) + MonkeyPatch.delete, + ) self.assertEqual(23, reference) fixture.setUp() try: @@ -104,7 +134,8 @@ def test_delete_existing_attribute(self): def test_delete_missing_attribute(self): fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.new_attr', - MonkeyPatch.delete) + MonkeyPatch.delete, + ) self.assertFalse('new_attr' in globals()) fixture.setUp() try: @@ -113,8 +144,9 @@ def test_delete_missing_attribute(self): fixture.cleanUp() self.assertFalse('new_attr' in globals()) - def _check_restored_static_or_class_method(self, oldmethod, oldmethod_inst, - klass, methodname): + def _check_restored_static_or_class_method( + self, oldmethod, oldmethod_inst, klass, methodname + ): restored_method = getattr(klass, methodname) restored_method_inst = getattr(klass(), methodname) self.assertEqual(oldmethod, restored_method) @@ -129,69 +161,78 @@ def test_patch_staticmethod_with_staticmethod(self): oldmethod_inst = C().foo_static fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo_static', - D.bar_static) + D.bar_static, + ) with fixture: C.foo_static() C().foo_static() - self._check_restored_static_or_class_method(oldmethod, oldmethod_inst, - C, 'foo_static') + self._check_restored_static_or_class_method( + oldmethod, oldmethod_inst, C, 'foo_static' + ) def test_patch_staticmethod_with_classmethod(self): oldmethod = C.foo_static oldmethod_inst = C().foo_static fixture = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.C.foo_static', - D.bar_cls) + 'fixtures.tests._fixtures.test_monkeypatch.C.foo_static', D.bar_cls + ) with fixture: C.foo_static() C().foo_static() - self._check_restored_static_or_class_method(oldmethod, oldmethod_inst, - C, 'foo_static') + self._check_restored_static_or_class_method( + oldmethod, oldmethod_inst, C, 'foo_static' + ) def test_patch_staticmethod_with_function(self): oldmethod = C.foo_static oldmethod_inst = C().foo_static fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo_static', - fake_no_args) + fake_no_args, + ) with fixture: C.foo_static() C().foo_static() - self._check_restored_static_or_class_method(oldmethod, oldmethod_inst, - C, 'foo_static') + self._check_restored_static_or_class_method( + oldmethod, oldmethod_inst, C, 'foo_static' + ) def test_patch_staticmethod_with_boundmethod(self): oldmethod = C.foo_static oldmethod_inst = C().foo_static fixture = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.C.foo_static', - D().bar) + 'fixtures.tests._fixtures.test_monkeypatch.C.foo_static', D().bar + ) with fixture: C.foo_static() C().foo_static() - self._check_restored_static_or_class_method(oldmethod, oldmethod_inst, - C, 'foo_static') + self._check_restored_static_or_class_method( + oldmethod, oldmethod_inst, C, 'foo_static' + ) def test_patch_classmethod_with_staticmethod(self): oldmethod = C.foo_cls oldmethod_inst = C().foo_cls fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo_cls', - D.bar_static_args) + D.bar_static_args, + ) with fixture: (cls,) = C.foo_cls() self.expectThat(cls, Is(C)) (cls,) = C().foo_cls() self.expectThat(cls, Is(C)) - self._check_restored_static_or_class_method(oldmethod, oldmethod_inst, - C, 'foo_cls') + self._check_restored_static_or_class_method( + oldmethod, oldmethod_inst, C, 'foo_cls' + ) def test_patch_classmethod_with_classmethod(self): oldmethod = C.foo_cls oldmethod_inst = C().foo_cls fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo_cls', - D.bar_cls_args) + D.bar_cls_args, + ) with fixture: # Python 3.9 changes the behavior of the classmethod decorator so # that it now honours the descriptor binding protocol [1]. @@ -201,9 +242,9 @@ def test_patch_classmethod_with_classmethod(self): # # https://bugs.python.org/issue19072 if NEW_PY39_CLASSMETHOD: - cls, = C.foo_cls() + (cls,) = C.foo_cls() self.expectThat(cls, Is(D)) - cls, = C().foo_cls() + (cls,) = C().foo_cls() self.expectThat(cls, Is(D)) else: cls, target_class = C.foo_cls() @@ -213,22 +254,24 @@ def test_patch_classmethod_with_classmethod(self): self.expectThat(cls, Is(D)) self.expectThat(target_class, Is(C)) self._check_restored_static_or_class_method( - oldmethod, oldmethod_inst, C, 'foo_cls') + oldmethod, oldmethod_inst, C, 'foo_cls' + ) def test_patch_classmethod_with_function(self): oldmethod = C.foo_cls oldmethod_inst = C().foo_cls fixture = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.C.foo_cls', - fake) + 'fixtures.tests._fixtures.test_monkeypatch.C.foo_cls', fake + ) with fixture: (cls,) = C.foo_cls() self.expectThat(cls, Is(C)) (cls, arg) = C().foo_cls(1) self.expectThat(cls, Is(C)) self.assertEqual(1, arg) - self._check_restored_static_or_class_method(oldmethod, oldmethod_inst, - C, 'foo_cls') + self._check_restored_static_or_class_method( + oldmethod, oldmethod_inst, C, 'foo_cls' + ) def test_patch_classmethod_with_boundmethod(self): oldmethod = C.foo_cls @@ -236,7 +279,8 @@ def test_patch_classmethod_with_boundmethod(self): d = D() fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo_cls', - d.bar_two_args) + d.bar_two_args, + ) with fixture: slf, cls = C.foo_cls() self.expectThat(slf, Is(d)) @@ -253,13 +297,15 @@ def test_patch_classmethod_with_boundmethod(self): else: self.expectThat(cls, Is(C)) self._check_restored_static_or_class_method( - oldmethod, oldmethod_inst, C, 'foo_cls') + oldmethod, oldmethod_inst, C, 'foo_cls' + ) def test_patch_function_with_staticmethod(self): oldmethod = fake_no_args fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.fake_no_args', - D.bar_static) + D.bar_static, + ) with fixture: fake_no_args() self.assertEqual(oldmethod, fake_no_args) @@ -267,8 +313,8 @@ def test_patch_function_with_staticmethod(self): def test_patch_function_with_classmethod(self): oldmethod = fake_no_args fixture = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.fake_no_args', - D.bar_cls) + 'fixtures.tests._fixtures.test_monkeypatch.fake_no_args', D.bar_cls + ) with fixture: fake_no_args() self.assertEqual(oldmethod, fake_no_args) @@ -277,7 +323,8 @@ def test_patch_function_with_function(self): oldmethod = fake_no_args fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.fake_no_args', - fake_no_args2) + fake_no_args2, + ) with fixture: fake_no_args() self.assertEqual(oldmethod, fake_no_args) @@ -286,7 +333,8 @@ def test_patch_function_with_partial(self): oldmethod = fake_no_args fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.fake_no_args', - functools.partial(fake, 1)) + functools.partial(fake, 1), + ) with fixture: (ret,) = fake_no_args() self.assertEqual(1, ret) @@ -295,8 +343,8 @@ def test_patch_function_with_partial(self): def test_patch_function_with_boundmethod(self): oldmethod = fake_no_args fixture = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.fake_no_args', - D().bar) + 'fixtures.tests._fixtures.test_monkeypatch.fake_no_args', D().bar + ) with fixture: fake_no_args() self.assertEqual(oldmethod, fake_no_args) @@ -305,7 +353,8 @@ def test_patch_boundmethod_with_staticmethod(self): oldmethod = INST_C.foo fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.INST_C.foo', - D.bar_static) + D.bar_static, + ) with fixture: INST_C.foo() self.assertEqual(oldmethod, INST_C.foo) @@ -313,8 +362,8 @@ def test_patch_boundmethod_with_staticmethod(self): def test_patch_boundmethod_with_classmethod(self): oldmethod = INST_C.foo fixture = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.INST_C.foo', - D.bar_cls) + 'fixtures.tests._fixtures.test_monkeypatch.INST_C.foo', D.bar_cls + ) with fixture: INST_C.foo() self.assertEqual(oldmethod, INST_C.foo) @@ -323,7 +372,8 @@ def test_patch_boundmethod_with_function(self): oldmethod = INST_C.foo fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.INST_C.foo', - fake_no_args) + fake_no_args, + ) with fixture: INST_C.foo() self.assertEqual(oldmethod, INST_C.foo) @@ -331,8 +381,8 @@ def test_patch_boundmethod_with_function(self): def test_patch_boundmethod_with_boundmethod(self): oldmethod = INST_C.foo fixture = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.INST_C.foo', - D().bar) + 'fixtures.tests._fixtures.test_monkeypatch.INST_C.foo', D().bar + ) with fixture: INST_C.foo() self.assertEqual(oldmethod, INST_C.foo) @@ -343,7 +393,8 @@ def test_patch_unboundmethod_with_staticmethod(self): oldmethod = C.foo fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo', - D.bar_static_args) + D.bar_static_args, + ) with fixture: target_self, arg = INST_C.foo(1) self.expectThat(target_self, Is(INST_C)) @@ -353,8 +404,8 @@ def test_patch_unboundmethod_with_staticmethod(self): def test_patch_unboundmethod_with_classmethod(self): oldmethod = C.foo fixture = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.C.foo', - D.bar_cls_args) + 'fixtures.tests._fixtures.test_monkeypatch.C.foo', D.bar_cls_args + ) with fixture: c = C() cls, target_self, arg = c.foo(1) @@ -366,8 +417,8 @@ def test_patch_unboundmethod_with_classmethod(self): def test_patch_unboundmethod_with_function(self): oldmethod = C.foo fixture = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.C.foo', - fake) + 'fixtures.tests._fixtures.test_monkeypatch.C.foo', fake + ) with fixture: c = C() target_self, arg = c.foo(1) @@ -379,8 +430,8 @@ def test_patch_unboundmethod_with_boundmethod(self): oldmethod = C.foo d = D() fixture = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.C.foo', - d.bar_two_args) + 'fixtures.tests._fixtures.test_monkeypatch.C.foo', d.bar_two_args + ) with fixture: c = C() slf, target_self = c.foo() @@ -392,11 +443,11 @@ def test_double_patch_instancemethod(self): oldmethod = C.foo oldmethod_inst = C().foo fixture1 = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.C.foo', - fake) + 'fixtures.tests._fixtures.test_monkeypatch.C.foo', fake + ) fixture2 = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.C.foo', - fake2) + 'fixtures.tests._fixtures.test_monkeypatch.C.foo', fake2 + ) with fixture1: with fixture2: C().foo() @@ -410,39 +461,44 @@ def test_double_patch_staticmethod(self): oldmethod_inst = C().foo_static fixture1 = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo_static', - fake_no_args) + fake_no_args, + ) fixture2 = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo_static', - fake_static) + fake_static, + ) with fixture1: with fixture2: C.foo_static() C().foo_static() - self._check_restored_static_or_class_method(oldmethod, oldmethod_inst, - C, 'foo_static') + self._check_restored_static_or_class_method( + oldmethod, oldmethod_inst, C, 'foo_static' + ) def test_double_patch_classmethod(self): oldmethod = C.foo_cls oldmethod_inst = C().foo_cls fixture1 = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.C.foo_cls', - fake) + 'fixtures.tests._fixtures.test_monkeypatch.C.foo_cls', fake + ) fixture2 = MonkeyPatch( - 'fixtures.tests._fixtures.test_monkeypatch.C.foo_cls', - fake2) + 'fixtures.tests._fixtures.test_monkeypatch.C.foo_cls', fake2 + ) with fixture1: with fixture2: C.foo_cls() C().foo_cls() - self._check_restored_static_or_class_method(oldmethod, oldmethod_inst, - C, 'foo_cls') + self._check_restored_static_or_class_method( + oldmethod, oldmethod_inst, C, 'foo_cls' + ) def test_patch_c_foo_with_instance_d_bar_self_referential(self): oldmethod = C.foo oldmethod_inst = C().foo fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo', - D().bar_self_referential) + D().bar_self_referential, + ) with fixture: C().foo() self.assertEqual(oldmethod, C.foo) diff --git a/fixtures/tests/_fixtures/test_packagepath.py b/fixtures/tests/_fixtures/test_packagepath.py index 6833fdc..3cccdc8 100644 --- a/fixtures/tests/_fixtures/test_packagepath.py +++ b/fixtures/tests/_fixtures/test_packagepath.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2011, Robert Collins -# +# # 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 @@ -19,11 +19,10 @@ from fixtures import ( PackagePathEntry, TempDir, - ) +) class TestPackagePathEntry(testtools.TestCase): - def test_adds_missing_to_end_package_path(self): uniquedir = self.useFixture(TempDir()).path fixture = PackagePathEntry('fixtures', uniquedir) diff --git a/fixtures/tests/_fixtures/test_popen.py b/fixtures/tests/_fixtures/test_popen.py index e9ab074..7b204d6 100644 --- a/fixtures/tests/_fixtures/test_popen.py +++ b/fixtures/tests/_fixtures/test_popen.py @@ -25,7 +25,6 @@ class TestFakePopen(testtools.TestCase, TestWithFixtures): - def test_installs_restores_global(self): fixture = FakePopen() popen = subprocess.Popen @@ -42,8 +41,12 @@ def test___call___is_recorded(self): self.assertEqual(1, len(fixture.procs)) self.assertEqual( dict( - args=['foo', 'bar'], bufsize=1, executable=None, - stdin='in', stdout='out', stderr='err', + args=['foo', 'bar'], + bufsize=1, + executable=None, + stdin='in', + stdout='out', + stderr='err', ), proc._args, ) @@ -51,20 +54,33 @@ def test___call___is_recorded(self): def test_inject_content_stdout(self): def get_info(args): return {'stdout': 'stdout'} + fixture = self.useFixture(FakePopen(get_info)) proc = fixture(['foo']) self.assertEqual('stdout', proc.stdout) def test_handles_all_Popen_args(self): all_args = dict( - args="args", bufsize="bufsize", executable="executable", - stdin="stdin", stdout="stdout", stderr="stderr", - preexec_fn="preexec_fn", close_fds="close_fds", shell="shell", - cwd="cwd", env="env", universal_newlines="universal_newlines", - startupinfo="startupinfo", creationflags="creationflags", + args="args", + bufsize="bufsize", + executable="executable", + stdin="stdin", + stdout="stdout", + stderr="stderr", + preexec_fn="preexec_fn", + close_fds="close_fds", + shell="shell", + cwd="cwd", + env="env", + universal_newlines="universal_newlines", + startupinfo="startupinfo", + creationflags="creationflags", restore_signals="restore_signals", - start_new_session="start_new_session", pass_fds="pass_fds", - encoding="encoding", errors="errors") + start_new_session="start_new_session", + pass_fds="pass_fds", + encoding="encoding", + errors="errors", + ) if sys.version_info >= (3, 7): all_args["text"] = "text" if sys.version_info >= (3, 9): @@ -85,40 +101,46 @@ def get_info(proc_args): fixture(**all_args) @testtools.skipUnless( - sys.version_info < (3, 7), "only relevant on Python <3.7") + sys.version_info < (3, 7), "only relevant on Python <3.7" + ) def test_rejects_3_7_args_on_older_versions(self): fixture = self.useFixture(FakePopen(lambda proc_args: {})) with testtools.ExpectedException( - TypeError, r".* got an unexpected keyword argument 'text'"): + TypeError, r".* got an unexpected keyword argument 'text'" + ): fixture(args="args", text=True) @testtools.skipUnless( - sys.version_info < (3, 9), "only relevant on Python <3.9") + sys.version_info < (3, 9), "only relevant on Python <3.9" + ) def test_rejects_3_9_args_on_older_versions(self): fixture = self.useFixture(FakePopen(lambda proc_args: {})) for arg_name in ("group", "extra_groups", "user", "umask"): kwargs = {arg_name: arg_name} expected_message = ( - r".* got an unexpected keyword argument '{}'".format(arg_name)) + r".* got an unexpected keyword argument '{}'".format(arg_name) + ) with testtools.ExpectedException(TypeError, expected_message): fixture(args="args", **kwargs) @testtools.skipUnless( - sys.version_info < (3, 10), "only relevant on Python <3.10") + sys.version_info < (3, 10), "only relevant on Python <3.10" + ) def test_rejects_3_10_args_on_older_versions(self): fixture = self.useFixture(FakePopen(lambda proc_args: {})) with testtools.ExpectedException( - TypeError, - r".* got an unexpected keyword argument 'pipesize'"): + TypeError, r".* got an unexpected keyword argument 'pipesize'" + ): fixture(args="args", pipesize=1024) @testtools.skipUnless( - sys.version_info < (3, 11), "only relevant on Python <3.11") + sys.version_info < (3, 11), "only relevant on Python <3.11" + ) def test_rejects_3_11_args_on_older_versions(self): fixture = self.useFixture(FakePopen(lambda proc_args: {})) with testtools.ExpectedException( - TypeError, - r".* got an unexpected keyword argument 'process_group'"): + TypeError, r".* got an unexpected keyword argument 'process_group'" + ): fixture(args="args", process_group=42) def test_function_signature(self): @@ -165,6 +187,7 @@ def test_function_signature(self): def test_custom_returncode(self): def get_info(proc_args): return dict(returncode=1) + proc = self.useFixture(FakePopen(get_info))(['foo']) self.assertEqual(None, proc.returncode) self.assertEqual(1, proc.wait()) @@ -178,7 +201,6 @@ def test_with_popen_custom(self): class TestFakeProcess(testtools.TestCase): - def test_wait(self): proc = FakeProcess({}, {}) proc.returncode = 45 diff --git a/fixtures/tests/_fixtures/test_pythonpackage.py b/fixtures/tests/_fixtures/test_pythonpackage.py index 41ac1b6..fa4db4f 100644 --- a/fixtures/tests/_fixtures/test_pythonpackage.py +++ b/fixtures/tests/_fixtures/test_pythonpackage.py @@ -21,7 +21,6 @@ class TestPythonPackage(testtools.TestCase, TestWithFixtures): - def test_has_tempdir(self): fixture = PythonPackage('foo', []) fixture.setUp() @@ -29,15 +28,18 @@ def test_has_tempdir(self): self.assertTrue(os.path.isdir(fixture.base)) finally: fixture.cleanUp() - + def test_writes_package(self): fixture = PythonPackage('foo', [('bar.py', b'woo')]) fixture.setUp() try: - self.assertEqual('', open(os.path.join(fixture.base, 'foo', - '__init__.py')).read()) - self.assertEqual('woo', open(os.path.join(fixture.base, 'foo', - 'bar.py')).read()) + self.assertEqual( + '', + open(os.path.join(fixture.base, 'foo', '__init__.py')).read(), + ) + self.assertEqual( + 'woo', open(os.path.join(fixture.base, 'foo', 'bar.py')).read() + ) finally: fixture.cleanUp() @@ -45,7 +47,10 @@ def test_no__init__(self): fixture = PythonPackage('foo', [('bar.py', b'woo')], init=False) fixture.setUp() try: - self.assertFalse(os.path.exists(os.path.join(fixture.base, 'foo', - '__init__.py'))) + self.assertFalse( + os.path.exists( + os.path.join(fixture.base, 'foo', '__init__.py') + ) + ) finally: fixture.cleanUp() diff --git a/fixtures/tests/_fixtures/test_pythonpath.py b/fixtures/tests/_fixtures/test_pythonpath.py index 5bb6851..233e4a8 100644 --- a/fixtures/tests/_fixtures/test_pythonpath.py +++ b/fixtures/tests/_fixtures/test_pythonpath.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2011, Robert Collins -# +# # 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 @@ -20,11 +20,10 @@ from fixtures import ( PythonPathEntry, TempDir, - ) +) class TestPythonPathEntry(testtools.TestCase): - def test_adds_missing_to_end_sys_path(self): uniquedir = self.useFixture(TempDir()).path fixture = PythonPathEntry(uniquedir) diff --git a/fixtures/tests/_fixtures/test_streams.py b/fixtures/tests/_fixtures/test_streams.py index 5d1c20d..6d5f333 100644 --- a/fixtures/tests/_fixtures/test_streams.py +++ b/fixtures/tests/_fixtures/test_streams.py @@ -20,17 +20,15 @@ ByteStream, DetailStream, StringStream, - ) +) class DetailStreamTest(TestCase): - def test_doc_mentions_deprecated(self): self.assertThat(DetailStream.__doc__, Contains('Deprecated')) class TestByteStreams(TestCase): - def test_empty_detail_stream(self): detail_name = 'test' fixture = ByteStream(detail_name) @@ -66,7 +64,6 @@ def test_stream_content_reset(self): class TestStringStreams(TestCase): - def test_empty_detail_stream(self): detail_name = 'test' fixture = StringStream(detail_name) diff --git a/fixtures/tests/_fixtures/test_tempdir.py b/fixtures/tests/_fixtures/test_tempdir.py index d0def55..f6bb912 100644 --- a/fixtures/tests/_fixtures/test_tempdir.py +++ b/fixtures/tests/_fixtures/test_tempdir.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2010, Robert Collins -# +# # 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 @@ -22,11 +22,10 @@ from fixtures import ( NestedTempfile, TempDir, - ) +) class TestTempDir(testtools.TestCase): - def test_basic(self): fixture = TempDir() sentinel = object() @@ -50,22 +49,23 @@ def test_join(self): temp_dir = self.useFixture(TempDir()) root = temp_dir.path relpath = 'foo/bar/baz' - self.assertEqual( - os.path.join(root, relpath), temp_dir.join(relpath)) + self.assertEqual(os.path.join(root, relpath), temp_dir.join(relpath)) def test_join_multiple_children(self): temp_dir = self.useFixture(TempDir()) root = temp_dir.path self.assertEqual( os.path.join(root, 'foo', 'bar', 'baz'), - temp_dir.join('foo', 'bar', 'baz')) + temp_dir.join('foo', 'bar', 'baz'), + ) def test_join_naughty_children(self): temp_dir = self.useFixture(TempDir()) root = temp_dir.path self.assertEqual( os.path.abspath(os.path.join(root, '..', 'bar', 'baz')), - temp_dir.join('..', 'bar', 'baz')) + temp_dir.join('..', 'bar', 'baz'), + ) class NestedTempfileTest(testtools.TestCase): @@ -88,6 +88,7 @@ def test_exception(self): # the code running in context raises an exception. class ContrivedException(Exception): pass + try: with NestedTempfile(): nested_tempdir = tempfile.tempdir diff --git a/fixtures/tests/_fixtures/test_temphomedir.py b/fixtures/tests/_fixtures/test_temphomedir.py index 339ce2c..2cbe30e 100644 --- a/fixtures/tests/_fixtures/test_temphomedir.py +++ b/fixtures/tests/_fixtures/test_temphomedir.py @@ -21,10 +21,10 @@ from fixtures import ( TempDir, TempHomeDir, - ) +) -class TestTempDir(testtools.TestCase): +class TestTempDir(testtools.TestCase): def test_basic(self): fixture = TempHomeDir() sentinel = object() diff --git a/fixtures/tests/_fixtures/test_timeout.py b/fixtures/tests/_fixtures/test_timeout.py index 3239746..7e7ba97 100644 --- a/fixtures/tests/_fixtures/test_timeout.py +++ b/fixtures/tests/_fixtures/test_timeout.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (C) 2011, Martin Pool -# +# # 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 @@ -19,7 +19,7 @@ import testtools from testtools.testcase import ( TestSkipped, - ) +) from testtools.matchers import raises import fixtures @@ -29,17 +29,18 @@ def sample_timeout_passes(): with fixtures.Timeout(100, gentle=True): pass # Timeout shouldn't fire + def sample_long_delay_with_gentle_timeout(): with fixtures.Timeout(1, gentle=True): time.sleep(100) # Expected to be killed here. + def sample_long_delay_with_harsh_timeout(): with fixtures.Timeout(1, gentle=False): time.sleep(100) # Expected to be killed here. class TestTimeout(testtools.TestCase, fixtures.TestWithFixtures): - def requireUnix(self): if getattr(signal, 'alarm', None) is None: raise TestSkipped("no alarm() function") @@ -51,16 +52,19 @@ def test_timeout_passes(self): def test_timeout_gentle(self): self.requireUnix() self.assertRaises( - fixtures.TimeoutException, - sample_long_delay_with_gentle_timeout) + fixtures.TimeoutException, sample_long_delay_with_gentle_timeout + ) def test_timeout_harsh(self): self.requireUnix() # This will normally kill the whole process, which would be # inconvenient. Let's hook the alarm here so we can observe it. - class GotAlarm(Exception):pass + class GotAlarm(Exception): + pass + def sigalrm_handler(signum, frame): raise GotAlarm() + old_handler = signal.signal(signal.SIGALRM, sigalrm_handler) self.addCleanup(signal.signal, signal.SIGALRM, old_handler) self.assertThat(sample_long_delay_with_harsh_timeout, raises(GotAlarm)) diff --git a/fixtures/tests/_fixtures/test_warnings.py b/fixtures/tests/_fixtures/test_warnings.py index 4b037be..7eb7b8d 100644 --- a/fixtures/tests/_fixtures/test_warnings.py +++ b/fixtures/tests/_fixtures/test_warnings.py @@ -19,7 +19,6 @@ class TestWarningsCapture(testtools.TestCase, fixtures.TestWithFixtures): - def test_capture_reuse(self): # DeprecationWarnings are hidden by default in Python 3.2+, enable them # https://docs.python.org/3/library/warnings.html#default-warning-filter @@ -52,9 +51,13 @@ def test_capture_category(self): w = self.useFixture(fixtures.WarningsCapture()) categories = [ - DeprecationWarning, Warning, UserWarning, - SyntaxWarning, RuntimeWarning, - UnicodeWarning, FutureWarning, + DeprecationWarning, + Warning, + UserWarning, + SyntaxWarning, + RuntimeWarning, + UnicodeWarning, + FutureWarning, ] for category in categories: warnings.warn("test", category) @@ -65,7 +68,6 @@ def test_capture_category(self): class TestWarningsFilter(testtools.TestCase, fixtures.TestWithFixtures): - def test_filter(self): fixture = fixtures.WarningsFilter( [ @@ -89,7 +91,6 @@ def test_filter(self): self.assertEqual(1, len(w)) def test_filters_restored(self): - class CustomWarning(Warning): pass diff --git a/fixtures/tests/helpers.py b/fixtures/tests/helpers.py index ae0d8d3..e509ae7 100644 --- a/fixtures/tests/helpers.py +++ b/fixtures/tests/helpers.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2010, Robert Collins -# +# # 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 @@ -15,8 +15,8 @@ import fixtures -class LoggingFixture(fixtures.Fixture): +class LoggingFixture(fixtures.Fixture): def __init__(self, suffix='', calls=None): super(LoggingFixture, self).__init__() if calls is None: diff --git a/fixtures/tests/test_callmany.py b/fixtures/tests/test_callmany.py index 7d66335..2111d4e 100644 --- a/fixtures/tests/test_callmany.py +++ b/fixtures/tests/test_callmany.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2010, Robert Collins -# +# # 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 @@ -21,15 +21,17 @@ class TestCallMany(testtools.TestCase): - def test__call__raise_errors_false_callsall_returns_exceptions(self): calls = [] + def raise_exception1(): calls.append('1') raise Exception('woo') + def raise_exception2(): calls.append('2') raise Exception('woo') + call = CallMany() call.push(raise_exception2) call.push(raise_exception1) @@ -52,12 +54,15 @@ def test_exit_propagates_exceptions(self): def test_exit_runs_all_raises_first_exception(self): calls = [] + def raise_exception1(): calls.append('1') raise Exception('woo') + def raise_exception2(): calls.append('2') raise Exception('hoo') + call = CallMany() call.push(raise_exception2) call.push(raise_exception1) diff --git a/fixtures/tests/test_fixture.py b/fixtures/tests/test_fixture.py index 66ac848..41a76d4 100644 --- a/fixtures/tests/test_fixture.py +++ b/fixtures/tests/test_fixture.py @@ -24,21 +24,23 @@ from fixtures.tests.helpers import LoggingFixture -require_gather_details = skipIf(gather_details is None, - "gather_details() is not available.") +require_gather_details = skipIf( + gather_details is None, "gather_details() is not available." +) # Note: the cleanup related tests are strictly speaking redundant, IFF they are # replaced with contract tests for correct use of CallMany. class TestFixture(testtools.TestCase): - def test_resetCallsSetUpCleanUp(self): calls = [] + class FixtureWithSetupOnly(fixtures.Fixture): def setUp(self): super(FixtureWithSetupOnly, self).setUp() calls.append('setUp') self.addCleanup(calls.append, 'cleanUp') + fixture = FixtureWithSetupOnly() fixture.setUp() fixture.reset() @@ -49,9 +51,11 @@ def test_reset_raises_if_cleanup_raises(self): class FixtureWithSetupOnly(fixtures.Fixture): def do_raise(self): raise Exception('foo') + def setUp(self): super(FixtureWithSetupOnly, self).setUp() self.addCleanup(self.do_raise) + fixture = FixtureWithSetupOnly() fixture.setUp() exc = self.assertRaises(Exception, fixture.reset) @@ -59,17 +63,21 @@ def setUp(self): def test_cleanUp_raise_first_false_callscleanups_returns_exceptions(self): calls = [] + def raise_exception1(): calls.append('1') raise Exception('woo') + def raise_exception2(): calls.append('2') raise Exception('woo') + class FixtureWithException(fixtures.Fixture): def setUp(self): super(FixtureWithException, self).setUp() self.addCleanup(raise_exception2) self.addCleanup(raise_exception1) + fixture = FixtureWithException() fixture.setUp() exceptions = fixture.cleanUp(raise_first=False) @@ -91,17 +99,21 @@ def test_exit_propagates_exceptions(self): def test_exit_runs_all_raises_first_exception(self): calls = [] + def raise_exception1(): calls.append('1') raise Exception('woo') + def raise_exception2(): calls.append('2') raise Exception('hoo') + class FixtureWithException(fixtures.Fixture): def setUp(self): super(FixtureWithException, self).setUp() self.addCleanup(raise_exception2) self.addCleanup(raise_exception1) + fixture = FixtureWithException() fixture.__enter__() exc = self.assertRaises(Exception, fixture.__exit__, None, None, None) @@ -117,49 +129,59 @@ def test_useFixture(self): parent.cleanUp() self.assertEqual( ['setUp-outer', 'setUp-inner', 'cleanUp-inner', 'cleanUp-outer'], - parent.calls) + parent.calls, + ) @require_gather_details def test_useFixture_details_captured_from_setUp(self): # Details added during fixture set-up are gathered even if setUp() # fails with an unknown exception. - class SomethingBroke(Exception): pass + class SomethingBroke(Exception): + pass + class BrokenFixture(fixtures.Fixture): def setUp(self): super(BrokenFixture, self).setUp() self.addDetail('content', text_content("foobar")) raise SomethingBroke() + broken_fixture = BrokenFixture() + class SimpleFixture(fixtures.Fixture): def setUp(self): super(SimpleFixture, self).setUp() self.useFixture(broken_fixture) + simple_fixture = SimpleFixture() self.assertRaises(SomethingBroke, simple_fixture.setUp) self.assertEqual( - {"content": text_content("foobar")}, - broken_fixture.getDetails()) + {"content": text_content("foobar")}, broken_fixture.getDetails() + ) self.assertEqual( - {"content": text_content("foobar")}, - simple_fixture.getDetails()) + {"content": text_content("foobar")}, simple_fixture.getDetails() + ) @require_gather_details def test_useFixture_details_captured_from_setUp_MultipleExceptions(self): # Details added during fixture set-up are gathered even if setUp() # fails with (cleanly - with MultipleExceptions / SetupError). - class SomethingBroke(Exception): pass + class SomethingBroke(Exception): + pass + class BrokenFixture(fixtures.Fixture): def _setUp(self): self.addDetail('content', text_content("foobar")) raise SomethingBroke() + class SimpleFixture(fixtures.Fixture): def _setUp(self): self.useFixture(BrokenFixture()) + simple = SimpleFixture() e = self.assertRaises(fixtures.MultipleExceptions, simple.setUp) self.assertEqual( - {"content": text_content("foobar")}, - e.args[-1][1].args[0]) + {"content": text_content("foobar")}, e.args[-1][1].args[0] + ) def test_getDetails(self): fixture = fixtures.Fixture() @@ -191,8 +213,13 @@ def test_duplicate_details_are_disambiguated(self): # Note that we add the detail *after* using the fixture: the parent # has to query just-in-time. child.addDetail('foo', 'child-content') - self.assertEqual({'foo': 'parent-content', - 'foo-1': 'child-content',}, parent.getDetails()) + self.assertEqual( + { + 'foo': 'parent-content', + 'foo-1': 'child-content', + }, + parent.getDetails(), + ) def test_addDetail(self): fixture = fixtures.Fixture() @@ -213,6 +240,7 @@ def setUp(self): super(Subclass, self).setUp() self.fred = 1 self.addCleanup(setattr, self, 'fred', 2) + with Subclass() as f: self.assertEqual(1, f.fred) self.assertEqual(2, f.fred) @@ -223,6 +251,7 @@ class Subclass(fixtures.Fixture): def _setUp(self): self.fred = 1 self.addCleanup(setattr, self, 'fred', 2) + with Subclass() as f: self.assertEqual(1, f.fred) self.assertEqual(2, f.fred) @@ -233,7 +262,8 @@ def test__setUp_fails(self): class Subclass(fixtures.Fixture): def _setUp(self): self.addDetail('log', text_content('stuff')) - 1/0 + 1 / 0 + f = Subclass() e = self.assertRaises(fixtures.MultipleExceptions, f.setUp) self.assertRaises(TypeError, f.cleanUp) @@ -247,8 +277,9 @@ def test__setUp_fails_cleanUp_fails(self): class Subclass(fixtures.Fixture): def _setUp(self): self.addDetail('log', text_content('stuff')) - self.addCleanup(lambda: 1/0) + self.addCleanup(lambda: 1 / 0) raise Exception('fred') + f = Subclass() e = self.assertRaises(fixtures.MultipleExceptions, f.setUp) self.assertRaises(TypeError, f.cleanUp) @@ -260,13 +291,17 @@ def _setUp(self): def test_setup_failures_with_base_exception(self): # when _setUp fails with a BaseException (or subclass thereof) that # exception is propagated as is, but we still call cleanups etc. - class MyBase(BaseException):pass + class MyBase(BaseException): + pass + log = [] + class Subclass(fixtures.Fixture): def _setUp(self): self.addDetail('log', text_content('stuff')) self.addCleanup(log.append, 'cleaned') raise MyBase('fred') + f = Subclass() self.assertRaises(MyBase, f.setUp) self.assertRaises(TypeError, f.cleanUp) @@ -274,7 +309,6 @@ def _setUp(self): class TestFunctionFixture(testtools.TestCase): - def test_setup_only(self): fixture = fixtures.FunctionFixture(lambda: 42) fixture.setUp() @@ -294,11 +328,14 @@ def test_cleanup(self): def test_reset(self): results = [] expected = [21, 7] + def setUp(): return expected.pop(0) + def reset(result): results.append(('reset', result)) return expected.pop(0) + fixture = fixtures.FunctionFixture(setUp, results.append, reset) fixture.setUp() self.assertEqual([], results) @@ -310,10 +347,10 @@ def reset(result): class TestMethodFixture(testtools.TestCase): - def test_no_setup_cleanup(self): class Stub: pass + fixture = fixtures.MethodFixture(Stub()) fixture.setUp() fixture.reset() @@ -324,6 +361,7 @@ def test_setup_only(self): class Stub: def setUp(self): self.value = 42 + fixture = fixtures.MethodFixture(Stub()) fixture.setUp() self.assertEqual(42, fixture.obj.value) @@ -333,8 +371,10 @@ def setUp(self): def test_cleanup_only(self): class Stub: value = None + def tearDown(self): self.value = 42 + fixture = fixtures.MethodFixture(Stub()) fixture.setUp() self.assertEqual(None, fixture.obj.value) @@ -346,8 +386,10 @@ def test_cleanup(self): class Stub: def setUp(self): self.value = 42 + def tearDown(self): self.value = 84 + fixture = fixtures.MethodFixture(Stub()) fixture.setUp() self.assertEqual(42, fixture.obj.value) @@ -359,6 +401,7 @@ def test_custom_setUp(self): class Stub: def mysetup(self): self.value = 42 + obj = Stub() fixture = fixtures.MethodFixture(obj, setup=obj.mysetup) fixture.setUp() @@ -369,8 +412,10 @@ def mysetup(self): def test_custom_cleanUp(self): class Stub: value = 42 + def mycleanup(self): self.value = None + obj = Stub() fixture = fixtures.MethodFixture(obj, cleanup=obj.mycleanup) fixture.setUp() @@ -383,10 +428,13 @@ def test_reset(self): class Stub: def setUp(self): self.value = 42 + def tearDown(self): self.value = 84 + def reset(self): self.value = 126 + obj = Stub() fixture = fixtures.MethodFixture(obj, reset=obj.reset) fixture.setUp() diff --git a/fixtures/tests/test_testcase.py b/fixtures/tests/test_testcase.py index 3f186c5..91f4c62 100644 --- a/fixtures/tests/test_testcase.py +++ b/fixtures/tests/test_testcase.py @@ -1,12 +1,12 @@ # fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2010, Robert Collins -# +# # 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 @@ -25,12 +25,13 @@ class TestTestWithFixtures(unittest.TestCase): - def test_useFixture(self): fixture = LoggingFixture() + class SimpleTest(testtools.TestCase, TestWithFixtures): def test_foo(self): self.useFixture(fixture) + result = unittest.TestResult() SimpleTest('test_foo').run(result) self.assertTrue(result.wasSuccessful()) @@ -38,13 +39,17 @@ def test_foo(self): def test_useFixture_uses_raise_first(self): calls = [] + def raiser(ignored): calls.append('called') raise Exception('foo') - fixture = fixtures.FunctionFixture(lambda:None, raiser) + + fixture = fixtures.FunctionFixture(lambda: None, raiser) + class SimpleTest(testtools.TestCase, TestWithFixtures): def test_foo(self): self.useFixture(fixture) + result = unittest.TestResult() SimpleTest('test_foo').run(result) self.assertFalse(result.wasSuccessful()) @@ -54,44 +59,57 @@ def test_foo(self): def test_useFixture_details_captured_from_setUp(self): # Details added during fixture set-up are gathered even if setUp() # fails with an exception. - class SomethingBroke(Exception): pass + class SomethingBroke(Exception): + pass + class BrokenFixture(fixtures.Fixture): def setUp(self): super(BrokenFixture, self).setUp() self.addDetail('content', text_content("foobar")) raise SomethingBroke() + broken_fixture = BrokenFixture() + class DetailedTestCase(TestWithFixtures, testtools.TestCase): def setUp(self): super(DetailedTestCase, self).setUp() self.useFixture(broken_fixture) + def test(self): pass + detailed_test_case = DetailedTestCase("test") self.assertRaises(SomethingBroke, detailed_test_case.setUp) self.assertEqual( - {"content": text_content("foobar")}, - broken_fixture.getDetails()) + {"content": text_content("foobar")}, broken_fixture.getDetails() + ) self.assertEqual( {"content": text_content("foobar")}, - detailed_test_case.getDetails()) + detailed_test_case.getDetails(), + ) @skipIf(gather_details is None, "gather_details() is not available.") def test_useFixture_details_not_captured_from_setUp(self): # Details added during fixture set-up are not gathered if the test # case does not have the ability to accept those details. - class SomethingBroke(Exception): pass + class SomethingBroke(Exception): + pass + class BrokenFixture(fixtures.Fixture): def setUp(self): super(BrokenFixture, self).setUp() self.addDetail('content', text_content("foobar")) raise SomethingBroke() + broken_fixture = BrokenFixture() + class NonDetailedTestCase(TestWithFixtures, unittest.TestCase): def setUp(self): super(NonDetailedTestCase, self).setUp() self.useFixture(broken_fixture) + def test(self): pass + non_detailed_test_case = NonDetailedTestCase("test") self.assertRaises(SomethingBroke, non_detailed_test_case.setUp) From 7e9120c5efca9a77fd0992dce4edf8abdd87928c Mon Sep 17 00:00:00 2001 From: Stephen Finucane Date: Fri, 31 Mar 2023 11:07:48 +0100 Subject: [PATCH 3/3] Add .git-blame-ignore-revs file Allows us to ignore style-only changes on the code base. GitHub automatically respects this [1] and git itself can be configured to do so [2]. [1] https://github.blog/changelog/2022-03-24-ignore-commits-in-the-blame-view-beta/ [2] https://stackoverflow.com/q/70435937/ Signed-off-by: Stephen Finucane --- .git-blame-ignore-revs | 1 + 1 file changed, 1 insertion(+) create mode 100644 .git-blame-ignore-revs diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..c186f4b --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1 @@ +9402d8dcdf7b0a1a1e004f56b7bcfc0070fa9f60