From ee03e31831900c3a7aba9f94a9693a833a3ab9de Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 30 Dec 2020 11:56:09 +0200 Subject: [PATCH] [pre-commit.ci] pre-commit autoupdate (#8201) * [pre-commit.ci] pre-commit autoupdate * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * manual fixes after configuration update * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Anthony Sottile --- .pre-commit-config.yaml | 20 +++++----- doc/en/doctest.rst | 2 +- doc/en/writing_plugins.rst | 3 +- doc/en/xunit_setup.rst | 14 +++---- scripts/prepare-release-pr.py | 10 ++++- scripts/release-on-comment.py | 5 ++- src/_pytest/_code/code.py | 6 +-- src/_pytest/_io/saferepr.py | 7 +++- src/_pytest/cacheprovider.py | 3 +- src/_pytest/capture.py | 10 ++++- src/_pytest/compat.py | 3 +- src/_pytest/config/__init__.py | 39 ++++++++++++++----- src/_pytest/config/findpaths.py | 4 +- src/_pytest/doctest.py | 19 ++++++--- src/_pytest/fixtures.py | 21 +++++++--- src/_pytest/freeze_support.py | 3 +- src/_pytest/hookspec.py | 25 +++++++----- src/_pytest/junitxml.py | 2 +- src/_pytest/logging.py | 6 ++- src/_pytest/main.py | 8 ++-- src/_pytest/mark/__init__.py | 5 ++- src/_pytest/mark/expression.py | 10 +++-- src/_pytest/mark/structures.py | 8 +--- src/_pytest/monkeypatch.py | 14 +++++-- src/_pytest/nodes.py | 5 ++- src/_pytest/pytester.py | 19 ++++++--- src/_pytest/python.py | 11 ++++-- src/_pytest/reports.py | 2 +- src/_pytest/terminal.py | 7 +++- src/_pytest/threadexception.py | 4 +- src/_pytest/tmpdir.py | 5 ++- .../test_compare_recursive_dataclasses.py | 10 ++++- testing/io/test_terminalwriter.py | 15 +++++-- testing/python/approx.py | 3 +- testing/python/metafunc.py | 10 ++++- testing/test_capture.py | 3 +- testing/test_debugging.py | 4 +- testing/test_doctest.py | 4 +- testing/test_mark.py | 13 +++++-- testing/test_mark_expression.py | 18 +++++++-- testing/test_monkeypatch.py | 4 +- testing/test_pluginmanager.py | 4 +- testing/test_runner_xunit.py | 4 +- testing/test_stepwise.py | 7 +++- testing/test_warnings.py | 2 +- 45 files changed, 280 insertions(+), 121 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 68cc3273b..c8e19b283 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,16 +1,16 @@ repos: - repo: https://github.com/psf/black - rev: 19.10b0 + rev: 20.8b1 hooks: - id: black args: [--safe, --quiet] - repo: https://github.com/asottile/blacken-docs - rev: v1.8.0 + rev: v1.9.1 hooks: - id: blacken-docs - additional_dependencies: [black==19.10b0] + additional_dependencies: [black==20.8b1] - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v3.2.0 + rev: v3.4.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer @@ -21,7 +21,7 @@ repos: exclude: _pytest/(debugging|hookspec).py language_version: python3 - repo: https://gitlab.com/pycqa/flake8 - rev: 3.8.3 + rev: 3.8.4 hooks: - id: flake8 language_version: python3 @@ -29,23 +29,21 @@ repos: - flake8-typing-imports==1.9.0 - flake8-docstrings==1.5.0 - repo: https://github.com/asottile/reorder_python_imports - rev: v2.3.5 + rev: v2.3.6 hooks: - id: reorder-python-imports args: ['--application-directories=.:src', --py36-plus] - repo: https://github.com/asottile/pyupgrade - rev: v2.7.2 + rev: v2.7.4 hooks: - id: pyupgrade args: [--py36-plus] - repo: https://github.com/asottile/setup-cfg-fmt - rev: v1.11.0 + rev: v1.16.0 hooks: - id: setup-cfg-fmt - # TODO: when upgrading setup-cfg-fmt this can be removed - args: [--max-py-version=3.9] - repo: https://github.com/pre-commit/pygrep-hooks - rev: v1.6.0 + rev: v1.7.0 hooks: - id: python-use-type-annotations - repo: https://github.com/pre-commit/mirrors-mypy diff --git a/doc/en/doctest.rst b/doc/en/doctest.rst index f8d010679..486868bb8 100644 --- a/doc/en/doctest.rst +++ b/doc/en/doctest.rst @@ -48,7 +48,7 @@ and functions, including from test modules: # content of mymodule.py def something(): - """ a doctest in a docstring + """a doctest in a docstring >>> something() 42 """ diff --git a/doc/en/writing_plugins.rst b/doc/en/writing_plugins.rst index 908366d52..f53f561cf 100644 --- a/doc/en/writing_plugins.rst +++ b/doc/en/writing_plugins.rst @@ -762,8 +762,7 @@ declaring the hook functions directly in your plugin module, for example: """Simple plugin to defer pytest-xdist hook functions.""" def pytest_testnodedown(self, node, error): - """standard xdist hook function. - """ + """standard xdist hook function.""" def pytest_configure(config): diff --git a/doc/en/xunit_setup.rst b/doc/en/xunit_setup.rst index 8b3366f62..4fea863be 100644 --- a/doc/en/xunit_setup.rst +++ b/doc/en/xunit_setup.rst @@ -36,7 +36,7 @@ which will usually be called once for all the functions: def teardown_module(module): - """ teardown any state that was previously setup with a setup_module + """teardown any state that was previously setup with a setup_module method. """ @@ -52,14 +52,14 @@ and after all test methods of the class are called: @classmethod def setup_class(cls): - """ setup any state specific to the execution of the given class (which + """setup any state specific to the execution of the given class (which usually contains tests). """ @classmethod def teardown_class(cls): - """ teardown any state that was previously setup with a call to + """teardown any state that was previously setup with a call to setup_class. """ @@ -71,13 +71,13 @@ Similarly, the following methods are called around each method invocation: .. code-block:: python def setup_method(self, method): - """ setup any state tied to the execution of the given method in a + """setup any state tied to the execution of the given method in a class. setup_method is invoked for every test method of a class. """ def teardown_method(self, method): - """ teardown any state that was previously setup with a setup_method + """teardown any state that was previously setup with a setup_method call. """ @@ -89,13 +89,13 @@ you can also use the following functions to implement fixtures: .. code-block:: python def setup_function(function): - """ setup any state tied to the execution of the given function. + """setup any state tied to the execution of the given function. Invoked for every test function in the module. """ def teardown_function(function): - """ teardown any state that was previously setup with a setup_function + """teardown any state that was previously setup with a setup_function call. """ diff --git a/scripts/prepare-release-pr.py b/scripts/prepare-release-pr.py index 538a5af5a..296de46ea 100644 --- a/scripts/prepare-release-pr.py +++ b/scripts/prepare-release-pr.py @@ -90,7 +90,10 @@ def prepare_release_pr(base_branch: str, is_major: bool, token: str) -> None: cmdline = ["tox", "-e", "release", "--", version, "--skip-check-links"] print("Running", " ".join(cmdline)) run( - cmdline, text=True, check=True, capture_output=True, + cmdline, + text=True, + check=True, + capture_output=True, ) oauth_url = f"https://{token}:x-oauth-basic@github.com/{SLUG}.git" @@ -105,7 +108,10 @@ def prepare_release_pr(base_branch: str, is_major: bool, token: str) -> None: body = PR_BODY.format(version=version) repo = login(token) pr = repo.create_pull( - f"Prepare release {version}", base=base_branch, head=release_branch, body=body, + f"Prepare release {version}", + base=base_branch, + head=release_branch, + body=body, ) print(f"Pull request {Fore.CYAN}{pr.url}{Fore.RESET} created.") diff --git a/scripts/release-on-comment.py b/scripts/release-on-comment.py index 44431a4fc..f8af9c0fc 100644 --- a/scripts/release-on-comment.py +++ b/scripts/release-on-comment.py @@ -153,7 +153,10 @@ def trigger_release(payload_path: Path, token: str) -> None: cmdline = ["tox", "-e", "release", "--", version, "--skip-check-links"] print("Running", " ".join(cmdline)) run( - cmdline, text=True, check=True, capture_output=True, + cmdline, + text=True, + check=True, + capture_output=True, ) oauth_url = f"https://{token}:x-oauth-basic@github.com/{SLUG}.git" diff --git a/src/_pytest/_code/code.py b/src/_pytest/_code/code.py index 043a23a79..b85217560 100644 --- a/src/_pytest/_code/code.py +++ b/src/_pytest/_code/code.py @@ -272,9 +272,9 @@ class TracebackEntry: Mostly for internal use. """ - tbh: Union[bool, Callable[[Optional[ExceptionInfo[BaseException]]], bool]] = ( - False - ) + tbh: Union[ + bool, Callable[[Optional[ExceptionInfo[BaseException]]], bool] + ] = False for maybe_ns_dct in (self.frame.f_locals, self.frame.f_globals): # in normal cases, f_locals and f_globals are dictionaries # however via `exec(...)` / `eval(...)` they can be other types diff --git a/src/_pytest/_io/saferepr.py b/src/_pytest/_io/saferepr.py index 5eb1e0889..440b8cbbb 100644 --- a/src/_pytest/_io/saferepr.py +++ b/src/_pytest/_io/saferepr.py @@ -107,7 +107,12 @@ class AlwaysDispatchingPrettyPrinter(pprint.PrettyPrinter): if objid in context or p is None: # Type ignored because _format is private. super()._format( # type: ignore[misc] - object, stream, indent, allowance, context, level, + object, + stream, + indent, + allowance, + context, + level, ) return diff --git a/src/_pytest/cacheprovider.py b/src/_pytest/cacheprovider.py index 03acd0310..480319c03 100755 --- a/src/_pytest/cacheprovider.py +++ b/src/_pytest/cacheprovider.py @@ -219,7 +219,8 @@ class LFPluginCollWrapper: # Sort any lf-paths to the beginning. lf_paths = self.lfplugin._last_failed_paths res.result = sorted( - res.result, key=lambda x: 0 if Path(str(x.fspath)) in lf_paths else 1, + res.result, + key=lambda x: 0 if Path(str(x.fspath)) in lf_paths else 1, ) return diff --git a/src/_pytest/capture.py b/src/_pytest/capture.py index 086302658..355f42591 100644 --- a/src/_pytest/capture.py +++ b/src/_pytest/capture.py @@ -556,7 +556,11 @@ class MultiCapture(Generic[AnyStr]): def __repr__(self) -> str: return "".format( - self.out, self.err, self.in_, self._state, self._in_suspended, + self.out, + self.err, + self.in_, + self._state, + self._in_suspended, ) def start_capturing(self) -> None: @@ -843,7 +847,9 @@ class CaptureFixture(Generic[AnyStr]): def _start(self) -> None: if self._capture is None: self._capture = MultiCapture( - in_=None, out=self.captureclass(1), err=self.captureclass(2), + in_=None, + out=self.captureclass(1), + err=self.captureclass(2), ) self._capture.start_capturing() diff --git a/src/_pytest/compat.py b/src/_pytest/compat.py index c7f86ea9c..0b87c7bbc 100644 --- a/src/_pytest/compat.py +++ b/src/_pytest/compat.py @@ -143,7 +143,8 @@ def getfuncargnames( parameters = signature(function).parameters except (ValueError, TypeError) as e: fail( - f"Could not determine arguments of {function!r}: {e}", pytrace=False, + f"Could not determine arguments of {function!r}: {e}", + pytrace=False, ) arg_names = tuple( diff --git a/src/_pytest/config/__init__.py b/src/_pytest/config/__init__.py index 760b0f55c..c029c29a3 100644 --- a/src/_pytest/config/__init__.py +++ b/src/_pytest/config/__init__.py @@ -104,7 +104,9 @@ class ExitCode(enum.IntEnum): class ConftestImportFailure(Exception): def __init__( - self, path: Path, excinfo: Tuple[Type[Exception], Exception, TracebackType], + self, + path: Path, + excinfo: Tuple[Type[Exception], Exception, TracebackType], ) -> None: super().__init__(path, excinfo) self.path = path @@ -269,7 +271,9 @@ def get_config( config = Config( pluginmanager, invocation_params=Config.InvocationParams( - args=args or (), plugins=plugins, dir=Path.cwd(), + args=args or (), + plugins=plugins, + dir=Path.cwd(), ), ) @@ -364,7 +368,10 @@ class PytestPluginManager(PluginManager): encoding: str = getattr(err, "encoding", "utf8") try: err = open( - os.dup(err.fileno()), mode=err.mode, buffering=1, encoding=encoding, + os.dup(err.fileno()), + mode=err.mode, + buffering=1, + encoding=encoding, ) except Exception: pass @@ -516,7 +523,9 @@ class PytestPluginManager(PluginManager): @lru_cache(maxsize=128) def _getconftestmodules( - self, path: Path, importmode: Union[str, ImportMode], + self, + path: Path, + importmode: Union[str, ImportMode], ) -> List[types.ModuleType]: if self._noconftest: return [] @@ -541,7 +550,10 @@ class PytestPluginManager(PluginManager): return clist def _rget_with_confmod( - self, name: str, path: Path, importmode: Union[str, ImportMode], + self, + name: str, + path: Path, + importmode: Union[str, ImportMode], ) -> Tuple[types.ModuleType, Any]: modules = self._getconftestmodules(path, importmode) for mod in reversed(modules): @@ -552,7 +564,9 @@ class PytestPluginManager(PluginManager): raise KeyError(name) def _importconftest( - self, conftestpath: Path, importmode: Union[str, ImportMode], + self, + conftestpath: Path, + importmode: Union[str, ImportMode], ) -> types.ModuleType: # Use a resolved Path object as key to avoid loading the same conftest # twice with build systems that create build directories containing @@ -590,7 +604,9 @@ class PytestPluginManager(PluginManager): return mod def _check_non_top_pytest_plugins( - self, mod: types.ModuleType, conftestpath: Path, + self, + mod: types.ModuleType, + conftestpath: Path, ) -> None: if ( hasattr(mod, "pytest_plugins") @@ -1227,7 +1243,11 @@ class Config: if Version(minver) > Version(pytest.__version__): raise pytest.UsageError( "%s: 'minversion' requires pytest-%s, actual pytest-%s'" - % (self.inipath, minver, pytest.__version__,) + % ( + self.inipath, + minver, + pytest.__version__, + ) ) def _validate_config_options(self) -> None: @@ -1502,7 +1522,8 @@ class Config: "(are you using python -O?)\n" ) self.issue_config_time_warning( - PytestConfigWarning(warning_text), stacklevel=3, + PytestConfigWarning(warning_text), + stacklevel=3, ) def _warn_about_skipped_plugins(self) -> None: diff --git a/src/_pytest/config/findpaths.py b/src/_pytest/config/findpaths.py index 2edf54536..05f21ece5 100644 --- a/src/_pytest/config/findpaths.py +++ b/src/_pytest/config/findpaths.py @@ -83,9 +83,7 @@ def load_config_dict_from_file( def locate_config( args: Iterable[Path], -) -> Tuple[ - Optional[Path], Optional[Path], Dict[str, Union[str, List[str]]], -]: +) -> Tuple[Optional[Path], Optional[Path], Dict[str, Union[str, List[str]]]]: """Search in the list of arguments for a valid ini-file for pytest, and return a tuple of (rootdir, inifile, cfg-dict).""" config_names = [ diff --git a/src/_pytest/doctest.py b/src/_pytest/doctest.py index 24f888257..255ca80b9 100644 --- a/src/_pytest/doctest.py +++ b/src/_pytest/doctest.py @@ -121,7 +121,9 @@ def pytest_unconfigure() -> None: def pytest_collect_file( - fspath: Path, path: py.path.local, parent: Collector, + fspath: Path, + path: py.path.local, + parent: Collector, ) -> Optional[Union["DoctestModule", "DoctestTextfile"]]: config = parent.config if fspath.suffix == ".py": @@ -193,7 +195,11 @@ def _init_runner_class() -> Type["doctest.DocTestRunner"]: self.continue_on_failure = continue_on_failure def report_failure( - self, out, test: "doctest.DocTest", example: "doctest.Example", got: str, + self, + out, + test: "doctest.DocTest", + example: "doctest.Example", + got: str, ) -> None: failure = doctest.DocTestFailure(test, example, got) if self.continue_on_failure: @@ -303,13 +309,14 @@ class DoctestItem(pytest.Item): # TODO: Type ignored -- breaks Liskov Substitution. def repr_failure( # type: ignore[override] - self, excinfo: ExceptionInfo[BaseException], + self, + excinfo: ExceptionInfo[BaseException], ) -> Union[str, TerminalRepr]: import doctest failures: Optional[ Sequence[Union[doctest.DocTestFailure, doctest.UnexpectedException]] - ] = (None) + ] = None if isinstance( excinfo.value, (doctest.DocTestFailure, doctest.UnexpectedException) ): @@ -510,7 +517,9 @@ class DoctestModule(pytest.Module): obj = getattr(obj, "fget", obj) # Type ignored because this is a private function. return doctest.DocTestFinder._find_lineno( # type: ignore - self, obj, source_lines, + self, + obj, + source_lines, ) def _find( diff --git a/src/_pytest/fixtures.py b/src/_pytest/fixtures.py index d3ec1296a..53f33d3e1 100644 --- a/src/_pytest/fixtures.py +++ b/src/_pytest/fixtures.py @@ -238,7 +238,7 @@ _Key = Tuple[object, ...] def get_parametrized_fixture_keys(item: nodes.Item, scopenum: int) -> Iterator[_Key]: """Return list of keys for all parametrized arguments which match - the specified scope. """ + the specified scope.""" assert scopenum < scopenum_function # function try: callspec = item.callspec # type: ignore[attr-defined] @@ -443,7 +443,7 @@ class FixtureRequest: fixtureinfo: FuncFixtureInfo = pyfuncitem._fixtureinfo self._arg2fixturedefs = fixtureinfo.name2fixturedefs.copy() self._arg2index: Dict[str, int] = {} - self._fixturemanager: FixtureManager = (pyfuncitem.session._fixturemanager) + self._fixturemanager: FixtureManager = pyfuncitem.session._fixturemanager @property def fixturenames(self) -> List[str]: @@ -700,7 +700,10 @@ class FixtureRequest: ) def _check_scope( - self, argname: str, invoking_scope: "_Scope", requested_scope: "_Scope", + self, + argname: str, + invoking_scope: "_Scope", + requested_scope: "_Scope", ) -> None: if argname == "request": return @@ -907,7 +910,8 @@ class FixtureLookupErrorRepr(TerminalRepr): ) for line in lines[1:]: tw.line( - f"{FormattedExcinfo.flow_marker} {line.strip()}", red=True, + f"{FormattedExcinfo.flow_marker} {line.strip()}", + red=True, ) tw.line() tw.line("%s:%d" % (os.fspath(self.filename), self.firstlineno + 1)) @@ -1167,7 +1171,8 @@ def _params_converter( def wrap_function_to_error_out_if_called_directly( - function: _FixtureFunction, fixture_marker: "FixtureFunctionMarker", + function: _FixtureFunction, + fixture_marker: "FixtureFunctionMarker", ) -> _FixtureFunction: """Wrap the given fixture function so we can raise an error about it being called directly, instead of used as an argument in a test function.""" @@ -1332,7 +1337,11 @@ def fixture( ``@pytest.fixture(name='')``. """ fixture_marker = FixtureFunctionMarker( - scope=scope, params=params, autouse=autouse, ids=ids, name=name, + scope=scope, + params=params, + autouse=autouse, + ids=ids, + name=name, ) # Direct decoration. diff --git a/src/_pytest/freeze_support.py b/src/_pytest/freeze_support.py index 8b93ed5f7..69b7d59ff 100644 --- a/src/_pytest/freeze_support.py +++ b/src/_pytest/freeze_support.py @@ -18,7 +18,8 @@ def freeze_includes() -> List[str]: def _iter_all_modules( - package: Union[str, types.ModuleType], prefix: str = "", + package: Union[str, types.ModuleType], + prefix: str = "", ) -> Iterator[str]: """Iterate over the names of all modules that can be found in the given package, recursively. diff --git a/src/_pytest/hookspec.py b/src/_pytest/hookspec.py index 22bebf5b7..41c12a2cc 100644 --- a/src/_pytest/hookspec.py +++ b/src/_pytest/hookspec.py @@ -540,7 +540,8 @@ def pytest_runtest_logreport(report: "TestReport") -> None: @hookspec(firstresult=True) def pytest_report_to_serializable( - config: "Config", report: Union["CollectReport", "TestReport"], + config: "Config", + report: Union["CollectReport", "TestReport"], ) -> Optional[Dict[str, Any]]: """Serialize the given report object into a data structure suitable for sending over the wire, e.g. converted to JSON.""" @@ -548,7 +549,8 @@ def pytest_report_to_serializable( @hookspec(firstresult=True) def pytest_report_from_serializable( - config: "Config", data: Dict[str, Any], + config: "Config", + data: Dict[str, Any], ) -> Optional[Union["CollectReport", "TestReport"]]: """Restore a report object previously serialized with pytest_report_to_serializable().""" @@ -597,7 +599,8 @@ def pytest_sessionstart(session: "Session") -> None: def pytest_sessionfinish( - session: "Session", exitstatus: Union[int, "ExitCode"], + session: "Session", + exitstatus: Union[int, "ExitCode"], ) -> None: """Called after whole test run finished, right before returning the exit status to the system. @@ -701,7 +704,10 @@ def pytest_report_header( def pytest_report_collectionfinish( - config: "Config", startpath: Path, startdir: py.path.local, items: Sequence["Item"], + config: "Config", + startpath: Path, + startdir: py.path.local, + items: Sequence["Item"], ) -> Union[str, List[str]]: """Return a string or list of strings to be displayed after collection has finished successfully. @@ -731,9 +737,7 @@ def pytest_report_collectionfinish( @hookspec(firstresult=True) def pytest_report_teststatus( report: Union["CollectReport", "TestReport"], config: "Config" -) -> Tuple[ - str, str, Union[str, Mapping[str, bool]], -]: +) -> Tuple[str, str, Union[str, Mapping[str, bool]]]: """Return result-category, shortletter and verbose word for status reporting. @@ -758,7 +762,9 @@ def pytest_report_teststatus( def pytest_terminal_summary( - terminalreporter: "TerminalReporter", exitstatus: "ExitCode", config: "Config", + terminalreporter: "TerminalReporter", + exitstatus: "ExitCode", + config: "Config", ) -> None: """Add a section to terminal summary reporting. @@ -865,7 +871,8 @@ def pytest_markeval_namespace(config: "Config") -> Dict[str, Any]: def pytest_internalerror( - excrepr: "ExceptionRepr", excinfo: "ExceptionInfo[BaseException]", + excrepr: "ExceptionRepr", + excinfo: "ExceptionInfo[BaseException]", ) -> Optional[bool]: """Called for internal errors. diff --git a/src/_pytest/junitxml.py b/src/_pytest/junitxml.py index c4761cd3b..690fd976c 100644 --- a/src/_pytest/junitxml.py +++ b/src/_pytest/junitxml.py @@ -486,7 +486,7 @@ class LogXML: ) self.node_reporters: Dict[ Tuple[Union[str, TestReport], object], _NodeReporter - ] = ({}) + ] = {} self.node_reporters_ordered: List[_NodeReporter] = [] self.global_properties: List[Tuple[str, str]] = [] diff --git a/src/_pytest/logging.py b/src/_pytest/logging.py index 2e4847328..e0d71c7eb 100644 --- a/src/_pytest/logging.py +++ b/src/_pytest/logging.py @@ -685,9 +685,11 @@ class LoggingPlugin: def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None, None, None]: """Implement the internals of the pytest_runtest_xxx() hooks.""" with catching_logs( - self.caplog_handler, level=self.log_level, + self.caplog_handler, + level=self.log_level, ) as caplog_handler, catching_logs( - self.report_handler, level=self.log_level, + self.report_handler, + level=self.log_level, ) as report_handler: caplog_handler.reset() report_handler.reset() diff --git a/src/_pytest/main.py b/src/_pytest/main.py index 79afdde61..5036601f9 100644 --- a/src/_pytest/main.py +++ b/src/_pytest/main.py @@ -116,7 +116,9 @@ def pytest_addoption(parser: Parser) -> None: help="markers not registered in the `markers` section of the configuration file raise errors.", ) group._addoption( - "--strict", action="store_true", help="(deprecated) alias to --strict-markers.", + "--strict", + action="store_true", + help="(deprecated) alias to --strict-markers.", ) group._addoption( "-c", @@ -656,11 +658,11 @@ class Session(nodes.FSCollector): # Keep track of any collected nodes in here, so we don't duplicate fixtures. node_cache1: Dict[Path, Sequence[nodes.Collector]] = {} - node_cache2: Dict[Tuple[Type[nodes.Collector], Path], nodes.Collector] = ({}) + node_cache2: Dict[Tuple[Type[nodes.Collector], Path], nodes.Collector] = {} # Keep track of any collected collectors in matchnodes paths, so they # are not collected more than once. - matchnodes_cache: Dict[Tuple[Type[nodes.Collector], str], CollectReport] = ({}) + matchnodes_cache: Dict[Tuple[Type[nodes.Collector], str], CollectReport] = {} # Dirnames of pkgs with dunder-init files. pkg_roots: Dict[str, Package] = {} diff --git a/src/_pytest/mark/__init__.py b/src/_pytest/mark/__init__.py index 329a11c4a..97fb36ef7 100644 --- a/src/_pytest/mark/__init__.py +++ b/src/_pytest/mark/__init__.py @@ -56,7 +56,10 @@ def param( @pytest.mark.parametrize( "test_input,expected", - [("3+5", 8), pytest.param("6*9", 42, marks=pytest.mark.xfail),], + [ + ("3+5", 8), + pytest.param("6*9", 42, marks=pytest.mark.xfail), + ], ) def test_eval(test_input, expected): assert eval(test_input) == expected diff --git a/src/_pytest/mark/expression.py b/src/_pytest/mark/expression.py index dc3991b10..2e7dcf93c 100644 --- a/src/_pytest/mark/expression.py +++ b/src/_pytest/mark/expression.py @@ -102,7 +102,8 @@ class Scanner: pos += len(value) else: raise ParseError( - pos + 1, 'unexpected character "{}"'.format(input[pos]), + pos + 1, + 'unexpected character "{}"'.format(input[pos]), ) yield Token(TokenType.EOF, "", pos) @@ -120,7 +121,8 @@ class Scanner: raise ParseError( self.current.pos + 1, "expected {}; got {}".format( - " OR ".join(type.value for type in expected), self.current.type.value, + " OR ".join(type.value for type in expected), + self.current.type.value, ), ) @@ -204,7 +206,9 @@ class Expression: """ astexpr = expression(Scanner(input)) code: types.CodeType = compile( - astexpr, filename="", mode="eval", + astexpr, + filename="", + mode="eval", ) return Expression(code) diff --git a/src/_pytest/mark/structures.py b/src/_pytest/mark/structures.py index ae6920735..d2f21e168 100644 --- a/src/_pytest/mark/structures.py +++ b/src/_pytest/mark/structures.py @@ -460,15 +460,11 @@ if TYPE_CHECKING: ... class _UsefixturesMarkDecorator(MarkDecorator): - def __call__( # type: ignore[override] - self, *fixtures: str - ) -> MarkDecorator: + def __call__(self, *fixtures: str) -> MarkDecorator: # type: ignore[override] ... class _FilterwarningsMarkDecorator(MarkDecorator): - def __call__( # type: ignore[override] - self, *filters: str - ) -> MarkDecorator: + def __call__(self, *filters: str) -> MarkDecorator: # type: ignore[override] ... diff --git a/src/_pytest/monkeypatch.py b/src/_pytest/monkeypatch.py index d012b8a53..ffef87173 100644 --- a/src/_pytest/monkeypatch.py +++ b/src/_pytest/monkeypatch.py @@ -124,7 +124,7 @@ class MonkeyPatch: def __init__(self) -> None: self._setattr: List[Tuple[object, str, object]] = [] - self._setitem: List[Tuple[MutableMapping[Any, Any], object, object]] = ([]) + self._setitem: List[Tuple[MutableMapping[Any, Any], object, object]] = [] self._cwd: Optional[str] = None self._savesyspath: Optional[List[str]] = None @@ -157,13 +157,21 @@ class MonkeyPatch: @overload def setattr( - self, target: str, name: object, value: Notset = ..., raising: bool = ..., + self, + target: str, + name: object, + value: Notset = ..., + raising: bool = ..., ) -> None: ... @overload def setattr( - self, target: object, name: str, value: object, raising: bool = ..., + self, + target: object, + name: str, + value: object, + raising: bool = ..., ) -> None: ... diff --git a/src/_pytest/nodes.py b/src/_pytest/nodes.py index c6eb49dec..2a96d55ad 100644 --- a/src/_pytest/nodes.py +++ b/src/_pytest/nodes.py @@ -231,7 +231,10 @@ class Node(metaclass=NodeMeta): path, lineno = get_fslocation_from_item(self) assert lineno is not None warnings.warn_explicit( - warning, category=None, filename=str(path), lineno=lineno + 1, + warning, + category=None, + filename=str(path), + lineno=lineno + 1, ) # Methods for ordering nodes. diff --git a/src/_pytest/pytester.py b/src/_pytest/pytester.py index 0d1f8f278..4544d2c2b 100644 --- a/src/_pytest/pytester.py +++ b/src/_pytest/pytester.py @@ -291,13 +291,15 @@ class HookRecorder: @overload def getreports( - self, names: "Literal['pytest_collectreport']", + self, + names: "Literal['pytest_collectreport']", ) -> Sequence[CollectReport]: ... @overload def getreports( - self, names: "Literal['pytest_runtest_logreport']", + self, + names: "Literal['pytest_runtest_logreport']", ) -> Sequence[TestReport]: ... @@ -354,13 +356,15 @@ class HookRecorder: @overload def getfailures( - self, names: "Literal['pytest_collectreport']", + self, + names: "Literal['pytest_collectreport']", ) -> Sequence[CollectReport]: ... @overload def getfailures( - self, names: "Literal['pytest_runtest_logreport']", + self, + names: "Literal['pytest_runtest_logreport']", ) -> Sequence[TestReport]: ... @@ -419,7 +423,10 @@ class HookRecorder: outcomes = self.listoutcomes() assertoutcome( - outcomes, passed=passed, skipped=skipped, failed=failed, + outcomes, + passed=passed, + skipped=skipped, + failed=failed, ) def clear(self) -> None: @@ -659,7 +666,7 @@ class Pytester: self._request = request self._mod_collections: WeakKeyDictionary[ Collector, List[Union[Item, Collector]] - ] = (WeakKeyDictionary()) + ] = WeakKeyDictionary() if request.function: name: str = request.function.__name__ else: diff --git a/src/_pytest/python.py b/src/_pytest/python.py index 31d91853f..50ea60c2d 100644 --- a/src/_pytest/python.py +++ b/src/_pytest/python.py @@ -1202,7 +1202,9 @@ class Metafunc: return new_ids def _resolve_arg_value_types( - self, argnames: Sequence[str], indirect: Union[bool, Sequence[str]], + self, + argnames: Sequence[str], + indirect: Union[bool, Sequence[str]], ) -> Dict[str, "Literal['params', 'funcargs']"]: """Resolve if each parametrized argument must be considered a parameter to a fixture or a "funcarg" to the function, based on the @@ -1240,7 +1242,9 @@ class Metafunc: return valtypes def _validate_if_using_arg_names( - self, argnames: Sequence[str], indirect: Union[bool, Sequence[str]], + self, + argnames: Sequence[str], + indirect: Union[bool, Sequence[str]], ) -> None: """Check if all argnames are being used, by default values, or directly/indirectly. @@ -1691,7 +1695,8 @@ class Function(PyobjMixin, nodes.Item): # TODO: Type ignored -- breaks Liskov Substitution. def repr_failure( # type: ignore[override] - self, excinfo: ExceptionInfo[BaseException], + self, + excinfo: ExceptionInfo[BaseException], ) -> Union[str, TerminalRepr]: style = self.config.getoption("tbstyle", "auto") if style == "auto": diff --git a/src/_pytest/reports.py b/src/_pytest/reports.py index 58f12517c..bcd40fb36 100644 --- a/src/_pytest/reports.py +++ b/src/_pytest/reports.py @@ -307,7 +307,7 @@ class TestReport(BaseReport): Tuple[str, int, str], str, TerminalRepr, - ] = (None) + ] = None else: if not isinstance(excinfo, ExceptionInfo): outcome = "failed" diff --git a/src/_pytest/terminal.py b/src/_pytest/terminal.py index d3d1a4b66..eea9214e7 100644 --- a/src/_pytest/terminal.py +++ b/src/_pytest/terminal.py @@ -468,7 +468,9 @@ class TerminalReporter: return True def pytest_warning_recorded( - self, warning_message: warnings.WarningMessage, nodeid: str, + self, + warning_message: warnings.WarningMessage, + nodeid: str, ) -> None: from _pytest.warnings import warning_record_to_str @@ -1306,7 +1308,8 @@ def _get_line_with_reprcrash_message( def _folded_skips( - startpath: Path, skipped: Sequence[CollectReport], + startpath: Path, + skipped: Sequence[CollectReport], ) -> List[Tuple[int, str, Optional[int], str]]: d: Dict[Tuple[str, Optional[int], str], List[CollectReport]] = {} for event in skipped: diff --git a/src/_pytest/threadexception.py b/src/_pytest/threadexception.py index 1c1f62fdb..d084dc6e6 100644 --- a/src/_pytest/threadexception.py +++ b/src/_pytest/threadexception.py @@ -69,7 +69,9 @@ def thread_exception_runtest_hook() -> Generator[None, None, None]: msg = f"Exception in thread {thread_name}\n\n" msg += "".join( traceback.format_exception( - cm.args.exc_type, cm.args.exc_value, cm.args.exc_traceback, + cm.args.exc_type, + cm.args.exc_value, + cm.args.exc_traceback, ) ) warnings.warn(pytest.PytestUnhandledThreadExceptionWarning(msg)) diff --git a/src/_pytest/tmpdir.py b/src/_pytest/tmpdir.py index 08c445e2b..29c7e19d7 100644 --- a/src/_pytest/tmpdir.py +++ b/src/_pytest/tmpdir.py @@ -53,7 +53,10 @@ class TempPathFactory: @classmethod def from_config( - cls, config: Config, *, _ispytest: bool = False, + cls, + config: Config, + *, + _ispytest: bool = False, ) -> "TempPathFactory": """Create a factory according to pytest configuration. diff --git a/testing/example_scripts/dataclasses/test_compare_recursive_dataclasses.py b/testing/example_scripts/dataclasses/test_compare_recursive_dataclasses.py index 167140e16..0945790f0 100644 --- a/testing/example_scripts/dataclasses/test_compare_recursive_dataclasses.py +++ b/testing/example_scripts/dataclasses/test_compare_recursive_dataclasses.py @@ -29,10 +29,16 @@ class C3: def test_recursive_dataclasses(): left = C3( - S(10, "ten"), C2(C(S(1, "one"), S(2, "two")), S(2, "three")), "equal", "left", + S(10, "ten"), + C2(C(S(1, "one"), S(2, "two")), S(2, "three")), + "equal", + "left", ) right = C3( - S(20, "xxx"), C2(C(S(1, "one"), S(2, "yyy")), S(3, "three")), "equal", "right", + S(20, "xxx"), + C2(C(S(1, "one"), S(2, "yyy")), S(3, "three")), + "equal", + "right", ) assert left == right diff --git a/testing/io/test_terminalwriter.py b/testing/io/test_terminalwriter.py index fac7593ea..4866c94a5 100644 --- a/testing/io/test_terminalwriter.py +++ b/testing/io/test_terminalwriter.py @@ -258,13 +258,22 @@ class TestTerminalWriterLineWidth: id="with markup and code_highlight", ), pytest.param( - True, False, "assert 0\n", id="with markup but no code_highlight", + True, + False, + "assert 0\n", + id="with markup but no code_highlight", ), pytest.param( - False, True, "assert 0\n", id="without markup but with code_highlight", + False, + True, + "assert 0\n", + id="without markup but with code_highlight", ), pytest.param( - False, False, "assert 0\n", id="neither markup nor code_highlight", + False, + False, + "assert 0\n", + id="neither markup nor code_highlight", ), ], ) diff --git a/testing/python/approx.py b/testing/python/approx.py index e76d6b774..db6124e39 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -514,7 +514,8 @@ class TestApprox: ) def test_expected_value_type_error(self, x, name): with pytest.raises( - TypeError, match=fr"pytest.approx\(\) does not support nested {name}:", + TypeError, + match=fr"pytest.approx\(\) does not support nested {name}:", ): approx(x) diff --git a/testing/python/metafunc.py b/testing/python/metafunc.py index 58a902a3a..6577ff18e 100644 --- a/testing/python/metafunc.py +++ b/testing/python/metafunc.py @@ -514,7 +514,10 @@ class TestMetafunc: ] for config, expected in values: result = idmaker( - ("a",), [pytest.param("string")], idfn=lambda _: "ação", config=config, + ("a",), + [pytest.param("string")], + idfn=lambda _: "ação", + config=config, ) assert result == [expected] @@ -546,7 +549,10 @@ class TestMetafunc: ] for config, expected in values: result = idmaker( - ("a",), [pytest.param("string")], ids=["ação"], config=config, + ("a",), + [pytest.param("string")], + ids=["ação"], + config=config, ) assert result == [expected] diff --git a/testing/test_capture.py b/testing/test_capture.py index 3a5c617fe..4d89f0b9e 100644 --- a/testing/test_capture.py +++ b/testing/test_capture.py @@ -1431,7 +1431,8 @@ def test_error_attribute_issue555(pytester: Pytester) -> None: @pytest.mark.skipif( - not sys.platform.startswith("win"), reason="only on windows", + not sys.platform.startswith("win"), + reason="only on windows", ) def test_py36_windowsconsoleio_workaround_non_standard_streams() -> None: """ diff --git a/testing/test_debugging.py b/testing/test_debugging.py index e1b57299d..9cdd41166 100644 --- a/testing/test_debugging.py +++ b/testing/test_debugging.py @@ -877,7 +877,9 @@ class TestPDB: assert custom_pdb_calls == [] def test_pdb_custom_cls_with_set_trace( - self, pytester: Pytester, monkeypatch: MonkeyPatch, + self, + pytester: Pytester, + monkeypatch: MonkeyPatch, ) -> None: pytester.makepyfile( custom_pdb=""" diff --git a/testing/test_doctest.py b/testing/test_doctest.py index 08d0aacf6..b63665349 100644 --- a/testing/test_doctest.py +++ b/testing/test_doctest.py @@ -69,7 +69,9 @@ class TestDoctests: @pytest.mark.parametrize("filename", ["__init__", "whatever"]) def test_collect_module_two_doctest_no_modulelevel( - self, pytester: Pytester, filename: str, + self, + pytester: Pytester, + filename: str, ) -> None: path = pytester.makepyfile( **{ diff --git a/testing/test_mark.py b/testing/test_mark.py index 5f4b3e063..420faf91e 100644 --- a/testing/test_mark.py +++ b/testing/test_mark.py @@ -356,8 +356,14 @@ def test_parametrize_with_module(pytester: Pytester) -> None: "foo or or", "at column 8: expected not OR left parenthesis OR identifier; got or", ), - ("(foo", "at column 5: expected right parenthesis; got end of input",), - ("foo bar", "at column 5: expected end of input; got identifier",), + ( + "(foo", + "at column 5: expected right parenthesis; got end of input", + ), + ( + "foo bar", + "at column 5: expected end of input; got identifier", + ), ( "or or", "at column 1: expected not OR left parenthesis OR identifier; got or", @@ -863,7 +869,8 @@ class TestKeywordSelection: assert passed + skipped + failed == 0 @pytest.mark.parametrize( - "keyword", ["__", "+", ".."], + "keyword", + ["__", "+", ".."], ) def test_no_magic_values(self, pytester: Pytester, keyword: str) -> None: """Make sure the tests do not match on magic values, diff --git a/testing/test_mark_expression.py b/testing/test_mark_expression.py index faca02d93..d37324f51 100644 --- a/testing/test_mark_expression.py +++ b/testing/test_mark_expression.py @@ -70,7 +70,11 @@ def test_syntax_oddeties(expr: str, expected: bool) -> None: ("expr", "column", "message"), ( ("(", 2, "expected not OR left parenthesis OR identifier; got end of input"), - (" (", 3, "expected not OR left parenthesis OR identifier; got end of input",), + ( + " (", + 3, + "expected not OR left parenthesis OR identifier; got end of input", + ), ( ")", 1, @@ -81,7 +85,11 @@ def test_syntax_oddeties(expr: str, expected: bool) -> None: 1, "expected not OR left parenthesis OR identifier; got right parenthesis", ), - ("not", 4, "expected not OR left parenthesis OR identifier; got end of input",), + ( + "not", + 4, + "expected not OR left parenthesis OR identifier; got end of input", + ), ( "not not", 8, @@ -98,7 +106,11 @@ def test_syntax_oddeties(expr: str, expected: bool) -> None: 10, "expected not OR left parenthesis OR identifier; got end of input", ), - ("ident and or", 11, "expected not OR left parenthesis OR identifier; got or",), + ( + "ident and or", + 11, + "expected not OR left parenthesis OR identifier; got or", + ), ("ident ident", 7, "expected end of input; got identifier"), ), ) diff --git a/testing/test_monkeypatch.py b/testing/test_monkeypatch.py index 0b97a0e5a..955218180 100644 --- a/testing/test_monkeypatch.py +++ b/testing/test_monkeypatch.py @@ -348,7 +348,9 @@ class SampleInherit(Sample): @pytest.mark.parametrize( - "Sample", [Sample, SampleInherit], ids=["new", "new-inherit"], + "Sample", + [Sample, SampleInherit], + ids=["new", "new-inherit"], ) def test_issue156_undo_staticmethod(Sample: Type[Sample]) -> None: monkeypatch = MonkeyPatch() diff --git a/testing/test_pluginmanager.py b/testing/test_pluginmanager.py index a5282a507..9835b24a0 100644 --- a/testing/test_pluginmanager.py +++ b/testing/test_pluginmanager.py @@ -346,7 +346,9 @@ class TestPytestPluginManager: assert mod.x == 3 def test_consider_conftest_deps( - self, pytester: Pytester, pytestpm: PytestPluginManager, + self, + pytester: Pytester, + pytestpm: PytestPluginManager, ) -> None: mod = import_path(pytester.makepyfile("pytest_plugins='xyz'")) with pytest.raises(ImportError): diff --git a/testing/test_runner_xunit.py b/testing/test_runner_xunit.py index e90d761f6..e077ac41e 100644 --- a/testing/test_runner_xunit.py +++ b/testing/test_runner_xunit.py @@ -242,7 +242,9 @@ def test_setup_funcarg_setup_when_outer_scope_fails(pytester: Pytester) -> None: @pytest.mark.parametrize("arg", ["", "arg"]) def test_setup_teardown_function_level_with_optional_argument( - pytester: Pytester, monkeypatch, arg: str, + pytester: Pytester, + monkeypatch, + arg: str, ) -> None: """Parameter to setup/teardown xunit-style functions parameter is now optional (#1728).""" import sys diff --git a/testing/test_stepwise.py b/testing/test_stepwise.py index ff2ec16b7..85489fce8 100644 --- a/testing/test_stepwise.py +++ b/testing/test_stepwise.py @@ -138,7 +138,12 @@ def test_fail_and_continue_with_stepwise(stepwise_pytester: Pytester) -> None: @pytest.mark.parametrize("stepwise_skip", ["--stepwise-skip", "--sw-skip"]) def test_run_with_skip_option(stepwise_pytester: Pytester, stepwise_skip: str) -> None: result = stepwise_pytester.runpytest( - "-v", "--strict-markers", "--stepwise", stepwise_skip, "--fail", "--fail-last", + "-v", + "--strict-markers", + "--stepwise", + stepwise_skip, + "--fail", + "--fail-last", ) assert _strip_resource_warnings(result.stderr.lines) == [] diff --git a/testing/test_warnings.py b/testing/test_warnings.py index 574f3f1ec..8c9c227b2 100644 --- a/testing/test_warnings.py +++ b/testing/test_warnings.py @@ -662,7 +662,7 @@ class TestStackLevel: class CapturedWarnings: captured: List[ Tuple[warnings.WarningMessage, Optional[Tuple[str, int, str]]] - ] = ([]) + ] = [] @classmethod def pytest_warning_recorded(cls, warning_message, when, nodeid, location):