From 152e68434b220979c48058590b5cd121ffd46ead Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 21 Mar 2022 23:16:23 +0000 Subject: [PATCH 1/2] [pre-commit.ci] pre-commit autoupdate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/psf/black: 19.10b0 → 22.1.0](https://github.com/psf/black/compare/19.10b0...22.1.0) - [github.com/asottile/blacken-docs: v1.8.0 → v1.12.1](https://github.com/asottile/blacken-docs/compare/v1.8.0...v1.12.1) - [github.com/pre-commit/pre-commit-hooks: v3.2.0 → v4.1.0](https://github.com/pre-commit/pre-commit-hooks/compare/v3.2.0...v4.1.0) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.8.3 → 4.0.1](https://github.com/PyCQA/flake8/compare/3.8.3...4.0.1) - [github.com/asottile/reorder_python_imports: v2.3.5 → v3.0.1](https://github.com/asottile/reorder_python_imports/compare/v2.3.5...v3.0.1) - [github.com/asottile/pyupgrade: v2.7.2 → v2.31.1](https://github.com/asottile/pyupgrade/compare/v2.7.2...v2.31.1) - [github.com/asottile/setup-cfg-fmt: v1.11.0 → v1.20.0](https://github.com/asottile/setup-cfg-fmt/compare/v1.11.0...v1.20.0) - [github.com/pre-commit/pygrep-hooks: v1.6.0 → v1.9.0](https://github.com/pre-commit/pygrep-hooks/compare/v1.6.0...v1.9.0) - [github.com/pre-commit/mirrors-mypy: v0.790 → v0.941](https://github.com/pre-commit/mirrors-mypy/compare/v0.790...v0.941) --- .pre-commit-config.yaml | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 68cc3273bba..696b54631ff 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: 22.1.0 hooks: - id: black args: [--safe, --quiet] - repo: https://github.com/asottile/blacken-docs - rev: v1.8.0 + rev: v1.12.1 hooks: - id: blacken-docs additional_dependencies: [black==19.10b0] - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v3.2.0 + rev: v4.1.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer @@ -20,8 +20,8 @@ repos: - id: debug-statements exclude: _pytest/(debugging|hookspec).py language_version: python3 -- repo: https://gitlab.com/pycqa/flake8 - rev: 3.8.3 +- repo: https://github.com/PyCQA/flake8 + rev: 4.0.1 hooks: - id: flake8 language_version: python3 @@ -29,27 +29,27 @@ 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: v3.0.1 hooks: - id: reorder-python-imports args: ['--application-directories=.:src', --py36-plus] - repo: https://github.com/asottile/pyupgrade - rev: v2.7.2 + rev: v2.31.1 hooks: - id: pyupgrade args: [--py36-plus] - repo: https://github.com/asottile/setup-cfg-fmt - rev: v1.11.0 + rev: v1.20.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.9.0 hooks: - id: python-use-type-annotations - repo: https://github.com/pre-commit/mirrors-mypy - rev: v0.790 + rev: v0.941 hooks: - id: mypy files: ^(src/|testing/) From de187550d3ff9abc812e73f042e6f94a575ff8bb Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 21 Mar 2022 23:17:47 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- extra/setup-py.test/setup.py | 1 + scripts/prepare-release-pr.py | 10 ++++- scripts/release-on-comment.py | 5 ++- src/_pytest/_argcomplete.py | 1 - src/_pytest/_code/code.py | 8 ++-- src/_pytest/_io/saferepr.py | 11 +++-- src/_pytest/assertion/rewrite.py | 1 - src/_pytest/cacheprovider.py | 3 +- src/_pytest/capture.py | 10 ++++- src/_pytest/compat.py | 6 +-- src/_pytest/config/__init__.py | 43 ++++++++++++++----- src/_pytest/config/findpaths.py | 4 +- src/_pytest/doctest.py | 20 ++++++--- src/_pytest/fixtures.py | 27 ++++++++---- 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 | 14 +++--- src/_pytest/mark/expression.py | 10 +++-- src/_pytest/mark/structures.py | 10 ++--- src/_pytest/monkeypatch.py | 14 ++++-- src/_pytest/nodes.py | 5 ++- src/_pytest/pastebin.py | 2 +- src/_pytest/pathlib.py | 3 +- src/_pytest/pytester.py | 21 ++++++--- src/_pytest/python.py | 15 ++++--- src/_pytest/python_api.py | 2 +- src/_pytest/recwarn.py | 2 +- src/_pytest/reports.py | 2 +- src/_pytest/setuponly.py | 2 +- src/_pytest/terminal.py | 15 ++++--- src/_pytest/threadexception.py | 4 +- src/_pytest/tmpdir.py | 5 ++- testing/acceptance_test.py | 2 +- .../test_compare_recursive_dataclasses.py | 10 ++++- testing/io/test_terminalwriter.py | 17 ++++++-- testing/python/approx.py | 3 +- testing/python/metafunc.py | 10 ++++- testing/python/raises.py | 4 +- testing/test_assertrewrite.py | 4 +- testing/test_capture.py | 3 +- testing/test_debugging.py | 4 +- testing/test_doctest.py | 9 ++-- testing/test_junitxml.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 | 4 +- 52 files changed, 295 insertions(+), 141 deletions(-) diff --git a/extra/setup-py.test/setup.py b/extra/setup-py.test/setup.py index d0560ce1f5f..97883852e2e 100644 --- a/extra/setup-py.test/setup.py +++ b/extra/setup-py.test/setup.py @@ -1,4 +1,5 @@ import sys + from distutils.core import setup if __name__ == "__main__": diff --git a/scripts/prepare-release-pr.py b/scripts/prepare-release-pr.py index 538a5af5a41..296de46ea0c 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 44431a4fc3f..f8af9c0fc83 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/_argcomplete.py b/src/_pytest/_argcomplete.py index 41d9d9407c7..120f09ff68f 100644 --- a/src/_pytest/_argcomplete.py +++ b/src/_pytest/_argcomplete.py @@ -108,7 +108,6 @@ def __call__(self, prefix: str, **kwargs: Any) -> List[str]: def try_argcomplete(parser: argparse.ArgumentParser) -> None: argcomplete.autocomplete(parser, always_complete_options=False) - else: def try_argcomplete(parser: argparse.ArgumentParser) -> None: diff --git a/src/_pytest/_code/code.py b/src/_pytest/_code/code.py index 423069330a5..4782e6a1973 100644 --- a/src/_pytest/_code/code.py +++ b/src/_pytest/_code/code.py @@ -270,9 +270,9 @@ def ishidden(self) -> bool: 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 @@ -950,7 +950,7 @@ def __str__(self) -> str: return io.getvalue().strip() def __repr__(self) -> str: - return "<{} instance at {:0x}>".format(self.__class__, id(self)) + return f"<{self.__class__} instance at {id(self):0x}>" def toterminal(self, tw: TerminalWriter) -> None: raise NotImplementedError() diff --git a/src/_pytest/_io/saferepr.py b/src/_pytest/_io/saferepr.py index 5eb1e088905..72f4dc4e928 100644 --- a/src/_pytest/_io/saferepr.py +++ b/src/_pytest/_io/saferepr.py @@ -12,7 +12,7 @@ def _try_repr_or_str(obj: object) -> str: except (KeyboardInterrupt, SystemExit): raise except BaseException: - return '{}("{}")'.format(type(obj).__name__, obj) + return f'{type(obj).__name__}("{obj}")' def _format_repr_exception(exc: BaseException, obj: object) -> str: @@ -21,7 +21,7 @@ def _format_repr_exception(exc: BaseException, obj: object) -> str: except (KeyboardInterrupt, SystemExit): raise except BaseException as exc: - exc_info = "unpresentable exception ({})".format(_try_repr_or_str(exc)) + exc_info = f"unpresentable exception ({_try_repr_or_str(exc)})" return "<[{} raised in repr()] {} object at 0x{:x}>".format( exc_info, type(obj).__name__, id(obj) ) @@ -107,7 +107,12 @@ def _format( 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/assertion/rewrite.py b/src/_pytest/assertion/rewrite.py index a01be76b4d3..4717ca1c52a 100644 --- a/src/_pytest/assertion/rewrite.py +++ b/src/_pytest/assertion/rewrite.py @@ -314,7 +314,6 @@ def _write_pyc( return False return True - else: def _write_pyc( diff --git a/src/_pytest/cacheprovider.py b/src/_pytest/cacheprovider.py index 03acd03109e..480319c03b4 100755 --- a/src/_pytest/cacheprovider.py +++ b/src/_pytest/cacheprovider.py @@ -219,7 +219,8 @@ def pytest_make_collect_report(self, collector: nodes.Collector): # 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 086302658cb..355f42591a7 100644 --- a/src/_pytest/capture.py +++ b/src/_pytest/capture.py @@ -556,7 +556,11 @@ def __init__(self, in_, out, err) -> None: 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 @@ def __init__( 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 c7f86ea9c0a..feb0b8ec11f 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( @@ -177,7 +178,6 @@ def getfuncargnames( def nullcontext(): yield - else: from contextlib import nullcontext as nullcontext # noqa: F401 @@ -397,4 +397,4 @@ def __get__(self, instance, owner=None): # # This also work for Enums (if you use `is` to compare) and Literals. def assert_never(value: "NoReturn") -> "NoReturn": - assert False, "Unhandled value: {} ({})".format(value, type(value).__name__) + assert False, f"Unhandled value: {value} ({type(value).__name__})" diff --git a/src/_pytest/config/__init__.py b/src/_pytest/config/__init__.py index 0df4ffa01c1..8a0500250f7 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(), ), ) @@ -362,7 +366,10 @@ def __init__(self) -> None: 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 @@ -514,7 +521,9 @@ def _try_load_conftest( @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 [] @@ -539,7 +548,10 @@ def _getconftestmodules( 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): @@ -550,7 +562,9 @@ def _rget_with_confmod( 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 @@ -588,7 +602,9 @@ def _importconftest( 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") @@ -703,7 +719,7 @@ def import_plugin(self, modname: str, consider_entry_points: bool = False) -> No __import__(importspec) except ImportError as e: raise ImportError( - 'Error importing plugin "{}": {}'.format(modname, str(e.args[0])) + f'Error importing plugin "{modname}": {str(e.args[0])}' ).with_traceback(e.__traceback__) from e except Skipped as e: @@ -1225,7 +1241,11 @@ def _checkversion(self) -> None: 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: @@ -1500,7 +1520,8 @@ def _warn_about_missing_assertion(self, mode: str) -> None: "(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: @@ -1576,7 +1597,7 @@ def parse_warning_filter( raise warnings._OptionError(f"too many fields (max 5): {arg!r}") while len(parts) < 5: parts.append("") - action_, message, category_, module, lineno_ = [s.strip() for s in parts] + action_, message, category_, module, lineno_ = (s.strip() for s in parts) action: str = warnings._getaction(action_) # type: ignore[attr-defined] category: Type[Warning] = warnings._getcategory(category_) # type: ignore[attr-defined] if message and escape: diff --git a/src/_pytest/config/findpaths.py b/src/_pytest/config/findpaths.py index 2edf54536ba..e256f086b48 100644 --- a/src/_pytest/config/findpaths.py +++ b/src/_pytest/config/findpaths.py @@ -83,9 +83,7 @@ def make_scalar(v: object) -> Union[str, List[str]]: 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 d0b6b4c4185..452487d4ee0 100644 --- a/src/_pytest/doctest.py +++ b/src/_pytest/doctest.py @@ -120,7 +120,8 @@ def pytest_unconfigure() -> None: def pytest_collect_file( - path: py.path.local, parent: Collector, + path: py.path.local, + parent: Collector, ) -> Optional[Union["DoctestModule", "DoctestTextfile"]]: config = parent.config if path.ext == ".py": @@ -192,7 +193,11 @@ def __init__( 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: @@ -302,13 +307,14 @@ def _disable_output_capturing_for_darwin(self) -> None: # 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) ): @@ -509,7 +515,9 @@ def _find_lineno(self, obj, source_lines): 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( @@ -647,7 +655,7 @@ def _remove_unwanted_precision(self, want: str, got: str) -> str: precision = len(fraction) if exponent is not None: precision -= int(exponent) - if float(w.group()) == approx(float(g.group()), abs=10 ** -precision): + if float(w.group()) == approx(float(g.group()), abs=10**-precision): # They're close enough. Replace the text we actually # got with the text we want, so that it will match when we # check the string literally. diff --git a/src/_pytest/fixtures.py b/src/_pytest/fixtures.py index c24ab7069cb..eda3c12d772 100644 --- a/src/_pytest/fixtures.py +++ b/src/_pytest/fixtures.py @@ -236,7 +236,7 @@ def getfixturemarker(obj: object) -> Optional["FixtureFunctionMarker"]: 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] @@ -441,7 +441,7 @@ def __init__(self, pyfuncitem, *, _ispytest: bool = False) -> None: 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]: @@ -698,7 +698,10 @@ def _schedule_finalizers( ) 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 @@ -847,7 +850,7 @@ def formatrepr(self) -> "FixtureLookupErrorRepr": error_msg = "file %s, line %s: source code not available" addline(error_msg % (fspath, lineno + 1)) else: - addline("file {}, line {}".format(fspath, lineno + 1)) + addline(f"file {fspath}, line {lineno + 1}") for i, line in enumerate(lines): line = line.rstrip() addline(" " + line) @@ -896,12 +899,13 @@ def toterminal(self, tw: TerminalWriter) -> None: lines = self.errorstring.split("\n") if lines: tw.line( - "{} {}".format(FormattedExcinfo.fail_marker, lines[0].strip()), + f"{FormattedExcinfo.fail_marker} {lines[0].strip()}", red=True, ) 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)) @@ -909,7 +913,7 @@ def toterminal(self, tw: TerminalWriter) -> None: def fail_fixturefunc(fixturefunc, msg: str) -> "NoReturn": fs, lineno = getfslineno(fixturefunc) - location = "{}:{}".format(fs, lineno + 1) + location = f"{fs}:{lineno + 1}" source = _pytest._code.Source(fixturefunc) fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, pytrace=False) @@ -1161,7 +1165,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.""" @@ -1326,7 +1331,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 8b93ed5f7f8..69b7d59ff69 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 22bebf5b783..76ef3fb3d2e 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 c4761cd3b87..690fd976ca9 100644 --- a/src/_pytest/junitxml.py +++ b/src/_pytest/junitxml.py @@ -486,7 +486,7 @@ def __init__( ) 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 2e4847328ab..e0d71c7eb54 100644 --- a/src/_pytest/logging.py +++ b/src/_pytest/logging.py @@ -685,9 +685,11 @@ def pytest_runtest_logreport(self) -> None: 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 e7c31ecc1d5..9b1f04d5749 100644 --- a/src/_pytest/main.py +++ b/src/_pytest/main.py @@ -115,7 +115,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", @@ -290,7 +292,7 @@ def wrap_session( except exit.Exception as exc: if exc.returncode is not None: session.exitstatus = exc.returncode - sys.stderr.write("{}: {}\n".format(type(exc).__name__, exc)) + sys.stderr.write(f"{type(exc).__name__}: {exc}\n") else: if isinstance(excinfo.value, SystemExit): sys.stderr.write("mainloop: caught unexpected SystemExit!\n") @@ -307,7 +309,7 @@ def wrap_session( except exit.Exception as exc: if exc.returncode is not None: session.exitstatus = exc.returncode - sys.stderr.write("{}: {}\n".format(type(exc).__name__, exc)) + sys.stderr.write(f"{type(exc).__name__}: {exc}\n") config._ensure_unconfigure() return session.exitstatus @@ -655,11 +657,11 @@ def collect(self) -> Iterator[Union[nodes.Item, nodes.Collector]]: node_cache1: Dict[py.path.local, Sequence[nodes.Collector]] = {} node_cache2: Dict[ Tuple[Type[nodes.Collector], py.path.local], 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] = {} @@ -690,7 +692,7 @@ def collect(self) -> Iterator[Union[nodes.Item, nodes.Collector]]: # If it's a directory argument, recurse and look for any Subpackages. # Let the Package collector deal with subnodes, don't collect here. if argpath.is_dir(): - assert not names, "invalid arg {!r}".format((argpath, names)) + assert not names, f"invalid arg {(argpath, names)!r}" seen_dirs: Set[py.path.local] = set() for direntry in visit(str(argpath), self._recurse): diff --git a/src/_pytest/mark/expression.py b/src/_pytest/mark/expression.py index dc3991b10c4..72e2ed4bdb7 100644 --- a/src/_pytest/mark/expression.py +++ b/src/_pytest/mark/expression.py @@ -102,7 +102,8 @@ def lex(self, input: str) -> Iterator[Token]: pos += len(value) else: raise ParseError( - pos + 1, 'unexpected character "{}"'.format(input[pos]), + pos + 1, + f'unexpected character "{input[pos]}"', ) yield Token(TokenType.EOF, "", pos) @@ -120,7 +121,8 @@ def reject(self, expected: Sequence[TokenType]) -> "NoReturn": 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 @@ def compile(self, input: str) -> "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 6c126cf4a29..0343bea0c79 100644 --- a/src/_pytest/mark/structures.py +++ b/src/_pytest/mark/structures.py @@ -99,7 +99,7 @@ def param( if id is not None: if not isinstance(id, str): raise TypeError( - "Expected id to be a string, got {}: {!r}".format(type(id), id) + f"Expected id to be a string, got {type(id)}: {id!r}" ) id = ascii_escaped(id) return cls(values, marks, id) @@ -437,15 +437,11 @@ def __call__( # type: ignore[override] ... 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 d012b8a535a..ffef87173a8 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 @@ def test_partial(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 1b3ec5571b1..2d425bc0604 100644 --- a/src/_pytest/nodes.py +++ b/src/_pytest/nodes.py @@ -228,7 +228,10 @@ def warn(self, warning: Warning) -> None: 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/pastebin.py b/src/_pytest/pastebin.py index 131873c174a..189ed3c5e10 100644 --- a/src/_pytest/pastebin.py +++ b/src/_pytest/pastebin.py @@ -86,7 +86,7 @@ def create_new_paste(contents: Union[str, bytes]) -> str: return "bad response: %s" % exc_info m = re.search(r'href="/raw/(\w+)"', response) if m: - return "{}/show/{}".format(url, m.group(1)) + return f"{url}/show/{m.group(1)}" else: return "bad response: invalid format ('" + response + "')" diff --git a/src/_pytest/pathlib.py b/src/_pytest/pathlib.py index 2e452eb1cc9..a38e0cbde8c 100644 --- a/src/_pytest/pathlib.py +++ b/src/_pytest/pathlib.py @@ -497,7 +497,7 @@ def import_path( if spec is None: raise ImportError( - "Can't find module {} at location {}".format(module_name, str(path)) + f"Can't find module {module_name} at location {str(path)}" ) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) # type: ignore[union-attr] @@ -558,7 +558,6 @@ def import_path( def _is_same(f1: str, f2: str) -> bool: return Path(f1) == Path(f2) or os.path.samefile(f1, f2) - else: def _is_same(f1: str, f2: str) -> bool: diff --git a/src/_pytest/pytester.py b/src/_pytest/pytester.py index 0d1f8f278f9..0268f79a788 100644 --- a/src/_pytest/pytester.py +++ b/src/_pytest/pytester.py @@ -291,13 +291,15 @@ def getcall(self, name: str) -> ParsedCall: @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 @@ def matchreport( @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 @@ def assertoutcome(self, passed: int = 0, skipped: int = 0, failed: int = 0) -> N 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 @@ def __init__( self._request = request self._mod_collections: WeakKeyDictionary[ Collector, List[Union[Item, Collector]] - ] = (WeakKeyDictionary()) + ] = WeakKeyDictionary() if request.function: name: str = request.function.__name__ else: @@ -1835,7 +1842,7 @@ def _match_lines( Match lines consecutively? """ if not isinstance(lines2, collections.abc.Sequence): - raise TypeError("invalid type for lines2: {}".format(type(lines2).__name__)) + raise TypeError(f"invalid type for lines2: {type(lines2).__name__}") lines2 = self._getlines(lines2) lines1 = self.lines[:] extralines = [] diff --git a/src/_pytest/python.py b/src/_pytest/python.py index 3ff04455fbf..9f27d301607 100644 --- a/src/_pytest/python.py +++ b/src/_pytest/python.py @@ -1187,7 +1187,9 @@ def _validate_ids( 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 @@ -1225,7 +1227,9 @@ def _resolve_arg_value_types( 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. @@ -1396,7 +1400,7 @@ def idmaker( # Suffix non-unique IDs to make them unique. for index, test_id in enumerate(resolved_ids): if test_id_counts[test_id] > 1: - resolved_ids[index] = "{}{}".format(test_id, test_id_suffixes[test_id]) + resolved_ids[index] = f"{test_id}{test_id_suffixes[test_id]}" test_id_suffixes[test_id] += 1 return resolved_ids @@ -1445,7 +1449,7 @@ def write_item(item: nodes.Item) -> None: tw.line() tw.sep("-", f"fixtures used by {item.name}") # TODO: Fix this type ignore. - tw.sep("-", "({})".format(get_best_relpath(item.function))) # type: ignore[attr-defined] + tw.sep("-", f"({get_best_relpath(item.function)})") # type: ignore[attr-defined] # dict key not used in loop but needed for sorting. for _, fixturedefs in sorted(info.name2fixturedefs.items()): assert fixturedefs is not None @@ -1676,7 +1680,8 @@ def _prunetraceback(self, excinfo: ExceptionInfo[BaseException]) -> None: # 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/python_api.py b/src/_pytest/python_api.py index 81ce4f89539..ad8ad7be409 100644 --- a/src/_pytest/python_api.py +++ b/src/_pytest/python_api.py @@ -732,7 +732,7 @@ def raises( func = args[0] if not callable(func): raise TypeError( - "{!r} object (type: {}) must be callable".format(func, type(func)) + f"{func!r} object (type: {type(func)}) must be callable" ) try: func(*args[1:], **kwargs) diff --git a/src/_pytest/recwarn.py b/src/_pytest/recwarn.py index d872d9da401..e3d8fbe3df9 100644 --- a/src/_pytest/recwarn.py +++ b/src/_pytest/recwarn.py @@ -150,7 +150,7 @@ def warns( func = args[0] if not callable(func): raise TypeError( - "{!r} object (type: {}) must be callable".format(func, type(func)) + f"{func!r} object (type: {type(func)}) must be callable" ) with WarningsChecker(expected_warning, _ispytest=True): return func(*args[1:], **kwargs) diff --git a/src/_pytest/reports.py b/src/_pytest/reports.py index 58f12517c5b..bcd40fb362e 100644 --- a/src/_pytest/reports.py +++ b/src/_pytest/reports.py @@ -307,7 +307,7 @@ def from_item_and_call(cls, item: Item, call: "CallInfo[None]") -> "TestReport": Tuple[str, int, str], str, TerminalRepr, - ] = (None) + ] = None else: if not isinstance(excinfo, ExceptionInfo): outcome = "failed" diff --git a/src/_pytest/setuponly.py b/src/_pytest/setuponly.py index 44a1094c0d2..9a1dd751716 100644 --- a/src/_pytest/setuponly.py +++ b/src/_pytest/setuponly.py @@ -79,7 +79,7 @@ def _show_fixture_action(fixturedef: FixtureDef[object], msg: str) -> None: tw.write(" (fixtures used: {})".format(", ".join(deps))) if hasattr(fixturedef, "cached_param"): - tw.write("[{}]".format(saferepr(fixturedef.cached_param, maxsize=42))) # type: ignore[attr-defined] + tw.write(f"[{saferepr(fixturedef.cached_param, maxsize=42)}]") # type: ignore[attr-defined] tw.flush() diff --git a/src/_pytest/terminal.py b/src/_pytest/terminal.py index f5d4e1f8ddc..1ccd753b39a 100644 --- a/src/_pytest/terminal.py +++ b/src/_pytest/terminal.py @@ -475,7 +475,9 @@ def pytest_internalerror(self, excrepr: ExceptionRepr) -> bool: 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 @@ -582,7 +584,7 @@ def pytest_runtest_logfinish(self, nodeid: str) -> None: if self.verbosity <= 0 and self._show_progress_info: if self._show_progress_info == "count": num_tests = self._session.testscollected - progress_length = len(" [{}/{}]".format(str(num_tests), str(num_tests))) + progress_length = len(f" [{str(num_tests)}/{str(num_tests)}]") else: progress_length = len(" [100%]") @@ -604,7 +606,7 @@ def _get_progress_information_message(self) -> str: if self._show_progress_info == "count": if collected: progress = self._progress_nodeids_reported - counter_format = "{{:{}d}}".format(len(str(collected))) + counter_format = f"{{:{len(str(collected))}d}}" format_string = f" [{counter_format}/{{}}]" return format_string.format(len(progress), collected) return f" [ {collected} / {collected} ]" @@ -698,7 +700,7 @@ def pytest_sessionstart(self, session: "Session") -> None: pypy_version_info = getattr(sys, "pypy_version_info", None) if pypy_version_info: verinfo = ".".join(map(str, pypy_version_info[:3])) - msg += "[pypy-{}-{}]".format(verinfo, pypy_version_info[3]) + msg += f"[pypy-{verinfo}-{pypy_version_info[3]}]" msg += ", pytest-{}, py-{}, pluggy-{}".format( _pytest._version.version, py.__version__, pluggy.__version__ ) @@ -1061,7 +1063,7 @@ def summary_stats(self) -> None: msg = ", ".join(line_parts) main_markup = {main_color: True} - duration = " in {}".format(format_session_duration(session_duration)) + duration = f" in {format_session_duration(session_duration)}" duration_with_markup = self._tw.markup(duration, **main_markup) if display_sep: fullwidth += len(duration_with_markup) - len(duration) @@ -1313,7 +1315,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 1c1f62fdb73..d084dc6e6a2 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 08c445e2bf8..29c7e19d7b4 100644 --- a/src/_pytest/tmpdir.py +++ b/src/_pytest/tmpdir.py @@ -53,7 +53,10 @@ def __init__( @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/acceptance_test.py b/testing/acceptance_test.py index b7ec18a9cb6..f9e35e45ce9 100644 --- a/testing/acceptance_test.py +++ b/testing/acceptance_test.py @@ -188,7 +188,7 @@ def test_not_collectable_arguments(self, pytester: Pytester) -> None: result.stderr.fnmatch_lines( [ f"ERROR: not found: {p2}", - "(no name {!r} in any of [[][]])".format(str(p2)), + f"(no name {str(p2)!r} in any of [[][]])", "", ] ) diff --git a/testing/example_scripts/dataclasses/test_compare_recursive_dataclasses.py b/testing/example_scripts/dataclasses/test_compare_recursive_dataclasses.py index 167140e16a6..0945790f004 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 fac7593eadd..6fe718b5341 100644 --- a/testing/io/test_terminalwriter.py +++ b/testing/io/test_terminalwriter.py @@ -56,7 +56,7 @@ def test_terminalwriter_not_unicode() -> None: file = io.TextIOWrapper(buffer, encoding="cp1252") tw = terminalwriter.TerminalWriter(file) tw.write("hello 🌀 wôrld אבג", flush=True) - assert buffer.getvalue() == br"hello \U0001f300 w\xf4rld \u05d0\u05d1\u05d2" + assert buffer.getvalue() == rb"hello \U0001f300 w\xf4rld \u05d0\u05d1\u05d2" win32 = int(sys.platform == "win32") @@ -258,13 +258,22 @@ def test_combining(self) -> None: 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 e76d6b774d6..d5a14a301ff 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -514,7 +514,8 @@ def test_foo(): ) def test_expected_value_type_error(self, x, name): with pytest.raises( - TypeError, match=fr"pytest.approx\(\) does not support nested {name}:", + TypeError, + match=rf"pytest.approx\(\) does not support nested {name}:", ): approx(x) diff --git a/testing/python/metafunc.py b/testing/python/metafunc.py index c50ea53d255..a7c991d18dd 100644 --- a/testing/python/metafunc.py +++ b/testing/python/metafunc.py @@ -514,7 +514,10 @@ def getini(self, name): ] 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 @@ def getini(self, name): ] 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/python/raises.py b/testing/python/raises.py index a3991adaef1..2d62e91091b 100644 --- a/testing/python/raises.py +++ b/testing/python/raises.py @@ -144,7 +144,7 @@ def test_no_raise_message(self) -> None: try: pytest.raises(ValueError, int, "0") except pytest.fail.Exception as e: - assert e.msg == "DID NOT RAISE {}".format(repr(ValueError)) + assert e.msg == f"DID NOT RAISE {repr(ValueError)}" else: assert False, "Expected pytest.raises.Exception" @@ -152,7 +152,7 @@ def test_no_raise_message(self) -> None: with pytest.raises(ValueError): pass except pytest.fail.Exception as e: - assert e.msg == "DID NOT RAISE {}".format(repr(ValueError)) + assert e.msg == f"DID NOT RAISE {repr(ValueError)}" else: assert False, "Expected pytest.raises.Exception" diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index ffe18260f90..efb019ee7c6 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -1239,7 +1239,7 @@ def test_simple_failure(): @pytest.mark.skipif( - sys.maxsize <= (2 ** 31 - 1), reason="Causes OverflowError on 32bit systems" + sys.maxsize <= (2**31 - 1), reason="Causes OverflowError on 32bit systems" ) @pytest.mark.parametrize("offset", [-1, +1]) def test_source_mtime_long_long(pytester: Pytester, offset) -> None: @@ -1258,7 +1258,7 @@ def test(): pass # use unsigned long timestamp which overflows signed long, # which was the cause of the bug # +1 offset also tests masking of 0xFFFFFFFF - timestamp = 2 ** 32 + offset + timestamp = 2**32 + offset os.utime(str(p), (timestamp, timestamp)) result = pytester.runpytest() assert result.ret == 0 diff --git a/testing/test_capture.py b/testing/test_capture.py index 3a5c617fe5a..4d89f0b9e40 100644 --- a/testing/test_capture.py +++ b/testing/test_capture.py @@ -1431,7 +1431,8 @@ def test_capattr(): @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 e1b57299d25..9cdd411667d 100644 --- a/testing/test_debugging.py +++ b/testing/test_debugging.py @@ -877,7 +877,9 @@ def test_pdb_custom_cls_without_pdb( 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 6e3880330a9..dcdbd340f74 100644 --- a/testing/test_doctest.py +++ b/testing/test_doctest.py @@ -70,7 +70,9 @@ def my_func(): @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( **{ @@ -729,12 +731,11 @@ def test_unicode_doctest(self, pytester: Pytester): test_unicode_doctest=""" .. doctest:: - >>> print( - ... "Hi\\n\\nByé") + >>> print("Hi\\n\\nByé") Hi ... Byé - >>> 1/0 # Byé + >>> 1 / 0 # Byé 1 """ ) diff --git a/testing/test_junitxml.py b/testing/test_junitxml.py index 1c76351eafc..2b2ca76f741 100644 --- a/testing/test_junitxml.py +++ b/testing/test_junitxml.py @@ -1388,7 +1388,7 @@ def test_pass(): result, dom = run_and_parse(f, f) result.stdout.no_fnmatch_line("*INTERNALERROR*") - first, second = [x["classname"] for x in dom.find_by_tag("testcase")] + first, second = (x["classname"] for x in dom.find_by_tag("testcase")) assert first == second @@ -1406,7 +1406,7 @@ def test_pass(): result, dom = run_and_parse(f, "--dist", "each", "--tx", "2*popen") result.stdout.no_fnmatch_line("*INTERNALERROR*") - first, second = [x["classname"] for x in dom.find_by_tag("testcase")] + first, second = (x["classname"] for x in dom.find_by_tag("testcase")) assert first == second diff --git a/testing/test_mark.py b/testing/test_mark.py index e0b91f0cef4..0f3cbf4df20 100644 --- a/testing/test_mark.py +++ b/testing/test_mark.py @@ -356,8 +356,14 @@ def test_func(arg): "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 @@ def test_one(): 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 faca02d9330..d37324f51cd 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 0b97a0e5adb..95521818021 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 a5282a50795..9835b24a046 100644 --- a/testing/test_pluginmanager.py +++ b/testing/test_pluginmanager.py @@ -346,7 +346,9 @@ def test_import_plugin_dotted_name( 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 e90d761f633..e077ac41e2c 100644 --- a/testing/test_runner_xunit.py +++ b/testing/test_runner_xunit.py @@ -242,7 +242,9 @@ def test_function2(hello): @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 ff2ec16b707..85489fce803 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 574f3f1ec02..e9ca6089d57 100644 --- a/testing/test_warnings.py +++ b/testing/test_warnings.py @@ -662,7 +662,7 @@ def capwarn(self, pytester: Pytester): class CapturedWarnings: captured: List[ Tuple[warnings.WarningMessage, Optional[Tuple[str, int, str]]] - ] = ([]) + ] = [] @classmethod def pytest_warning_recorded(cls, warning_message, when, nodeid, location): @@ -772,7 +772,7 @@ def test_it(): # with stacklevel=2 the warning should originate from the above created test file result.stdout.fnmatch_lines_random( [ - "*{testfile}:3*".format(testfile=str(testfile)), + f"*{str(testfile)}:3*", "*Unknown pytest.mark.unknown*", ] )