[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 <asottile@umich.edu>
This commit is contained in:
pre-commit-ci[bot] 2020-12-30 11:56:09 +02:00 committed by GitHub
parent 7751904875
commit ee03e31831
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
45 changed files with 280 additions and 121 deletions

View File

@ -1,16 +1,16 @@
repos: repos:
- repo: https://github.com/psf/black - repo: https://github.com/psf/black
rev: 19.10b0 rev: 20.8b1
hooks: hooks:
- id: black - id: black
args: [--safe, --quiet] args: [--safe, --quiet]
- repo: https://github.com/asottile/blacken-docs - repo: https://github.com/asottile/blacken-docs
rev: v1.8.0 rev: v1.9.1
hooks: hooks:
- id: blacken-docs - id: blacken-docs
additional_dependencies: [black==19.10b0] additional_dependencies: [black==20.8b1]
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0 rev: v3.4.0
hooks: hooks:
- id: trailing-whitespace - id: trailing-whitespace
- id: end-of-file-fixer - id: end-of-file-fixer
@ -21,7 +21,7 @@ repos:
exclude: _pytest/(debugging|hookspec).py exclude: _pytest/(debugging|hookspec).py
language_version: python3 language_version: python3
- repo: https://gitlab.com/pycqa/flake8 - repo: https://gitlab.com/pycqa/flake8
rev: 3.8.3 rev: 3.8.4
hooks: hooks:
- id: flake8 - id: flake8
language_version: python3 language_version: python3
@ -29,23 +29,21 @@ repos:
- flake8-typing-imports==1.9.0 - flake8-typing-imports==1.9.0
- flake8-docstrings==1.5.0 - flake8-docstrings==1.5.0
- repo: https://github.com/asottile/reorder_python_imports - repo: https://github.com/asottile/reorder_python_imports
rev: v2.3.5 rev: v2.3.6
hooks: hooks:
- id: reorder-python-imports - id: reorder-python-imports
args: ['--application-directories=.:src', --py36-plus] args: ['--application-directories=.:src', --py36-plus]
- repo: https://github.com/asottile/pyupgrade - repo: https://github.com/asottile/pyupgrade
rev: v2.7.2 rev: v2.7.4
hooks: hooks:
- id: pyupgrade - id: pyupgrade
args: [--py36-plus] args: [--py36-plus]
- repo: https://github.com/asottile/setup-cfg-fmt - repo: https://github.com/asottile/setup-cfg-fmt
rev: v1.11.0 rev: v1.16.0
hooks: hooks:
- id: setup-cfg-fmt - 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 - repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.6.0 rev: v1.7.0
hooks: hooks:
- id: python-use-type-annotations - id: python-use-type-annotations
- repo: https://github.com/pre-commit/mirrors-mypy - repo: https://github.com/pre-commit/mirrors-mypy

View File

@ -48,7 +48,7 @@ and functions, including from test modules:
# content of mymodule.py # content of mymodule.py
def something(): def something():
""" a doctest in a docstring """a doctest in a docstring
>>> something() >>> something()
42 42
""" """

View File

@ -762,8 +762,7 @@ declaring the hook functions directly in your plugin module, for example:
"""Simple plugin to defer pytest-xdist hook functions.""" """Simple plugin to defer pytest-xdist hook functions."""
def pytest_testnodedown(self, node, error): def pytest_testnodedown(self, node, error):
"""standard xdist hook function. """standard xdist hook function."""
"""
def pytest_configure(config): def pytest_configure(config):

View File

@ -36,7 +36,7 @@ which will usually be called once for all the functions:
def teardown_module(module): 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. method.
""" """
@ -52,14 +52,14 @@ and after all test methods of the class are called:
@classmethod @classmethod
def setup_class(cls): 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). usually contains tests).
""" """
@classmethod @classmethod
def teardown_class(cls): 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. setup_class.
""" """
@ -71,13 +71,13 @@ Similarly, the following methods are called around each method invocation:
.. code-block:: python .. code-block:: python
def setup_method(self, method): 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. class. setup_method is invoked for every test method of a class.
""" """
def teardown_method(self, method): 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. call.
""" """
@ -89,13 +89,13 @@ you can also use the following functions to implement fixtures:
.. code-block:: python .. code-block:: python
def setup_function(function): 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. Invoked for every test function in the module.
""" """
def teardown_function(function): 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. call.
""" """

View File

@ -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"] cmdline = ["tox", "-e", "release", "--", version, "--skip-check-links"]
print("Running", " ".join(cmdline)) print("Running", " ".join(cmdline))
run( 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" 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) body = PR_BODY.format(version=version)
repo = login(token) repo = login(token)
pr = repo.create_pull( 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.") print(f"Pull request {Fore.CYAN}{pr.url}{Fore.RESET} created.")

View File

@ -153,7 +153,10 @@ def trigger_release(payload_path: Path, token: str) -> None:
cmdline = ["tox", "-e", "release", "--", version, "--skip-check-links"] cmdline = ["tox", "-e", "release", "--", version, "--skip-check-links"]
print("Running", " ".join(cmdline)) print("Running", " ".join(cmdline))
run( 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" oauth_url = f"https://{token}:x-oauth-basic@github.com/{SLUG}.git"

View File

@ -272,9 +272,9 @@ class TracebackEntry:
Mostly for internal use. Mostly for internal use.
""" """
tbh: Union[bool, Callable[[Optional[ExceptionInfo[BaseException]]], bool]] = ( tbh: Union[
False bool, Callable[[Optional[ExceptionInfo[BaseException]]], bool]
) ] = False
for maybe_ns_dct in (self.frame.f_locals, self.frame.f_globals): for maybe_ns_dct in (self.frame.f_locals, self.frame.f_globals):
# in normal cases, f_locals and f_globals are dictionaries # in normal cases, f_locals and f_globals are dictionaries
# however via `exec(...)` / `eval(...)` they can be other types # however via `exec(...)` / `eval(...)` they can be other types

View File

@ -107,7 +107,12 @@ class AlwaysDispatchingPrettyPrinter(pprint.PrettyPrinter):
if objid in context or p is None: if objid in context or p is None:
# Type ignored because _format is private. # Type ignored because _format is private.
super()._format( # type: ignore[misc] super()._format( # type: ignore[misc]
object, stream, indent, allowance, context, level, object,
stream,
indent,
allowance,
context,
level,
) )
return return

View File

@ -219,7 +219,8 @@ class LFPluginCollWrapper:
# Sort any lf-paths to the beginning. # Sort any lf-paths to the beginning.
lf_paths = self.lfplugin._last_failed_paths lf_paths = self.lfplugin._last_failed_paths
res.result = sorted( 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 return

View File

@ -556,7 +556,11 @@ class MultiCapture(Generic[AnyStr]):
def __repr__(self) -> str: def __repr__(self) -> str:
return "<MultiCapture out={!r} err={!r} in_={!r} _state={!r} _in_suspended={!r}>".format( return "<MultiCapture out={!r} err={!r} in_={!r} _state={!r} _in_suspended={!r}>".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: def start_capturing(self) -> None:
@ -843,7 +847,9 @@ class CaptureFixture(Generic[AnyStr]):
def _start(self) -> None: def _start(self) -> None:
if self._capture is None: if self._capture is None:
self._capture = MultiCapture( 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() self._capture.start_capturing()

View File

@ -143,7 +143,8 @@ def getfuncargnames(
parameters = signature(function).parameters parameters = signature(function).parameters
except (ValueError, TypeError) as e: except (ValueError, TypeError) as e:
fail( 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( arg_names = tuple(

View File

@ -104,7 +104,9 @@ class ExitCode(enum.IntEnum):
class ConftestImportFailure(Exception): class ConftestImportFailure(Exception):
def __init__( def __init__(
self, path: Path, excinfo: Tuple[Type[Exception], Exception, TracebackType], self,
path: Path,
excinfo: Tuple[Type[Exception], Exception, TracebackType],
) -> None: ) -> None:
super().__init__(path, excinfo) super().__init__(path, excinfo)
self.path = path self.path = path
@ -269,7 +271,9 @@ def get_config(
config = Config( config = Config(
pluginmanager, pluginmanager,
invocation_params=Config.InvocationParams( 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") encoding: str = getattr(err, "encoding", "utf8")
try: try:
err = open( 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: except Exception:
pass pass
@ -516,7 +523,9 @@ class PytestPluginManager(PluginManager):
@lru_cache(maxsize=128) @lru_cache(maxsize=128)
def _getconftestmodules( def _getconftestmodules(
self, path: Path, importmode: Union[str, ImportMode], self,
path: Path,
importmode: Union[str, ImportMode],
) -> List[types.ModuleType]: ) -> List[types.ModuleType]:
if self._noconftest: if self._noconftest:
return [] return []
@ -541,7 +550,10 @@ class PytestPluginManager(PluginManager):
return clist return clist
def _rget_with_confmod( 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]: ) -> Tuple[types.ModuleType, Any]:
modules = self._getconftestmodules(path, importmode) modules = self._getconftestmodules(path, importmode)
for mod in reversed(modules): for mod in reversed(modules):
@ -552,7 +564,9 @@ class PytestPluginManager(PluginManager):
raise KeyError(name) raise KeyError(name)
def _importconftest( def _importconftest(
self, conftestpath: Path, importmode: Union[str, ImportMode], self,
conftestpath: Path,
importmode: Union[str, ImportMode],
) -> types.ModuleType: ) -> types.ModuleType:
# Use a resolved Path object as key to avoid loading the same conftest # Use a resolved Path object as key to avoid loading the same conftest
# twice with build systems that create build directories containing # twice with build systems that create build directories containing
@ -590,7 +604,9 @@ class PytestPluginManager(PluginManager):
return mod return mod
def _check_non_top_pytest_plugins( def _check_non_top_pytest_plugins(
self, mod: types.ModuleType, conftestpath: Path, self,
mod: types.ModuleType,
conftestpath: Path,
) -> None: ) -> None:
if ( if (
hasattr(mod, "pytest_plugins") hasattr(mod, "pytest_plugins")
@ -1227,7 +1243,11 @@ class Config:
if Version(minver) > Version(pytest.__version__): if Version(minver) > Version(pytest.__version__):
raise pytest.UsageError( raise pytest.UsageError(
"%s: 'minversion' requires pytest-%s, actual pytest-%s'" "%s: 'minversion' requires pytest-%s, actual pytest-%s'"
% (self.inipath, minver, pytest.__version__,) % (
self.inipath,
minver,
pytest.__version__,
)
) )
def _validate_config_options(self) -> None: def _validate_config_options(self) -> None:
@ -1502,7 +1522,8 @@ class Config:
"(are you using python -O?)\n" "(are you using python -O?)\n"
) )
self.issue_config_time_warning( self.issue_config_time_warning(
PytestConfigWarning(warning_text), stacklevel=3, PytestConfigWarning(warning_text),
stacklevel=3,
) )
def _warn_about_skipped_plugins(self) -> None: def _warn_about_skipped_plugins(self) -> None:

View File

@ -83,9 +83,7 @@ def load_config_dict_from_file(
def locate_config( def locate_config(
args: Iterable[Path], args: Iterable[Path],
) -> Tuple[ ) -> Tuple[Optional[Path], Optional[Path], Dict[str, Union[str, List[str]]]]:
Optional[Path], Optional[Path], Dict[str, Union[str, List[str]]],
]:
"""Search in the list of arguments for a valid ini-file for pytest, """Search in the list of arguments for a valid ini-file for pytest,
and return a tuple of (rootdir, inifile, cfg-dict).""" and return a tuple of (rootdir, inifile, cfg-dict)."""
config_names = [ config_names = [

View File

@ -121,7 +121,9 @@ def pytest_unconfigure() -> None:
def pytest_collect_file( def pytest_collect_file(
fspath: Path, path: py.path.local, parent: Collector, fspath: Path,
path: py.path.local,
parent: Collector,
) -> Optional[Union["DoctestModule", "DoctestTextfile"]]: ) -> Optional[Union["DoctestModule", "DoctestTextfile"]]:
config = parent.config config = parent.config
if fspath.suffix == ".py": if fspath.suffix == ".py":
@ -193,7 +195,11 @@ def _init_runner_class() -> Type["doctest.DocTestRunner"]:
self.continue_on_failure = continue_on_failure self.continue_on_failure = continue_on_failure
def report_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: ) -> None:
failure = doctest.DocTestFailure(test, example, got) failure = doctest.DocTestFailure(test, example, got)
if self.continue_on_failure: if self.continue_on_failure:
@ -303,13 +309,14 @@ class DoctestItem(pytest.Item):
# TODO: Type ignored -- breaks Liskov Substitution. # TODO: Type ignored -- breaks Liskov Substitution.
def repr_failure( # type: ignore[override] def repr_failure( # type: ignore[override]
self, excinfo: ExceptionInfo[BaseException], self,
excinfo: ExceptionInfo[BaseException],
) -> Union[str, TerminalRepr]: ) -> Union[str, TerminalRepr]:
import doctest import doctest
failures: Optional[ failures: Optional[
Sequence[Union[doctest.DocTestFailure, doctest.UnexpectedException]] Sequence[Union[doctest.DocTestFailure, doctest.UnexpectedException]]
] = (None) ] = None
if isinstance( if isinstance(
excinfo.value, (doctest.DocTestFailure, doctest.UnexpectedException) excinfo.value, (doctest.DocTestFailure, doctest.UnexpectedException)
): ):
@ -510,7 +517,9 @@ class DoctestModule(pytest.Module):
obj = getattr(obj, "fget", obj) obj = getattr(obj, "fget", obj)
# Type ignored because this is a private function. # Type ignored because this is a private function.
return doctest.DocTestFinder._find_lineno( # type: ignore return doctest.DocTestFinder._find_lineno( # type: ignore
self, obj, source_lines, self,
obj,
source_lines,
) )
def _find( def _find(

View File

@ -238,7 +238,7 @@ _Key = Tuple[object, ...]
def get_parametrized_fixture_keys(item: nodes.Item, scopenum: int) -> Iterator[_Key]: def get_parametrized_fixture_keys(item: nodes.Item, scopenum: int) -> Iterator[_Key]:
"""Return list of keys for all parametrized arguments which match """Return list of keys for all parametrized arguments which match
the specified scope. """ the specified scope."""
assert scopenum < scopenum_function # function assert scopenum < scopenum_function # function
try: try:
callspec = item.callspec # type: ignore[attr-defined] callspec = item.callspec # type: ignore[attr-defined]
@ -443,7 +443,7 @@ class FixtureRequest:
fixtureinfo: FuncFixtureInfo = pyfuncitem._fixtureinfo fixtureinfo: FuncFixtureInfo = pyfuncitem._fixtureinfo
self._arg2fixturedefs = fixtureinfo.name2fixturedefs.copy() self._arg2fixturedefs = fixtureinfo.name2fixturedefs.copy()
self._arg2index: Dict[str, int] = {} self._arg2index: Dict[str, int] = {}
self._fixturemanager: FixtureManager = (pyfuncitem.session._fixturemanager) self._fixturemanager: FixtureManager = pyfuncitem.session._fixturemanager
@property @property
def fixturenames(self) -> List[str]: def fixturenames(self) -> List[str]:
@ -700,7 +700,10 @@ class FixtureRequest:
) )
def _check_scope( def _check_scope(
self, argname: str, invoking_scope: "_Scope", requested_scope: "_Scope", self,
argname: str,
invoking_scope: "_Scope",
requested_scope: "_Scope",
) -> None: ) -> None:
if argname == "request": if argname == "request":
return return
@ -907,7 +910,8 @@ class FixtureLookupErrorRepr(TerminalRepr):
) )
for line in lines[1:]: for line in lines[1:]:
tw.line( tw.line(
f"{FormattedExcinfo.flow_marker} {line.strip()}", red=True, f"{FormattedExcinfo.flow_marker} {line.strip()}",
red=True,
) )
tw.line() tw.line()
tw.line("%s:%d" % (os.fspath(self.filename), self.firstlineno + 1)) 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( def wrap_function_to_error_out_if_called_directly(
function: _FixtureFunction, fixture_marker: "FixtureFunctionMarker", function: _FixtureFunction,
fixture_marker: "FixtureFunctionMarker",
) -> _FixtureFunction: ) -> _FixtureFunction:
"""Wrap the given fixture function so we can raise an error about it being called directly, """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.""" instead of used as an argument in a test function."""
@ -1332,7 +1337,11 @@ def fixture(
``@pytest.fixture(name='<fixturename>')``. ``@pytest.fixture(name='<fixturename>')``.
""" """
fixture_marker = FixtureFunctionMarker( 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. # Direct decoration.

View File

@ -18,7 +18,8 @@ def freeze_includes() -> List[str]:
def _iter_all_modules( def _iter_all_modules(
package: Union[str, types.ModuleType], prefix: str = "", package: Union[str, types.ModuleType],
prefix: str = "",
) -> Iterator[str]: ) -> Iterator[str]:
"""Iterate over the names of all modules that can be found in the given """Iterate over the names of all modules that can be found in the given
package, recursively. package, recursively.

View File

@ -540,7 +540,8 @@ def pytest_runtest_logreport(report: "TestReport") -> None:
@hookspec(firstresult=True) @hookspec(firstresult=True)
def pytest_report_to_serializable( def pytest_report_to_serializable(
config: "Config", report: Union["CollectReport", "TestReport"], config: "Config",
report: Union["CollectReport", "TestReport"],
) -> Optional[Dict[str, Any]]: ) -> Optional[Dict[str, Any]]:
"""Serialize the given report object into a data structure suitable for """Serialize the given report object into a data structure suitable for
sending over the wire, e.g. converted to JSON.""" sending over the wire, e.g. converted to JSON."""
@ -548,7 +549,8 @@ def pytest_report_to_serializable(
@hookspec(firstresult=True) @hookspec(firstresult=True)
def pytest_report_from_serializable( def pytest_report_from_serializable(
config: "Config", data: Dict[str, Any], config: "Config",
data: Dict[str, Any],
) -> Optional[Union["CollectReport", "TestReport"]]: ) -> Optional[Union["CollectReport", "TestReport"]]:
"""Restore a report object previously serialized with pytest_report_to_serializable().""" """Restore a report object previously serialized with pytest_report_to_serializable()."""
@ -597,7 +599,8 @@ def pytest_sessionstart(session: "Session") -> None:
def pytest_sessionfinish( def pytest_sessionfinish(
session: "Session", exitstatus: Union[int, "ExitCode"], session: "Session",
exitstatus: Union[int, "ExitCode"],
) -> None: ) -> None:
"""Called after whole test run finished, right before returning the exit status to the system. """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( 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]]: ) -> Union[str, List[str]]:
"""Return a string or list of strings to be displayed after collection """Return a string or list of strings to be displayed after collection
has finished successfully. has finished successfully.
@ -731,9 +737,7 @@ def pytest_report_collectionfinish(
@hookspec(firstresult=True) @hookspec(firstresult=True)
def pytest_report_teststatus( def pytest_report_teststatus(
report: Union["CollectReport", "TestReport"], config: "Config" report: Union["CollectReport", "TestReport"], config: "Config"
) -> Tuple[ ) -> Tuple[str, str, Union[str, Mapping[str, bool]]]:
str, str, Union[str, Mapping[str, bool]],
]:
"""Return result-category, shortletter and verbose word for status """Return result-category, shortletter and verbose word for status
reporting. reporting.
@ -758,7 +762,9 @@ def pytest_report_teststatus(
def pytest_terminal_summary( def pytest_terminal_summary(
terminalreporter: "TerminalReporter", exitstatus: "ExitCode", config: "Config", terminalreporter: "TerminalReporter",
exitstatus: "ExitCode",
config: "Config",
) -> None: ) -> None:
"""Add a section to terminal summary reporting. """Add a section to terminal summary reporting.
@ -865,7 +871,8 @@ def pytest_markeval_namespace(config: "Config") -> Dict[str, Any]:
def pytest_internalerror( def pytest_internalerror(
excrepr: "ExceptionRepr", excinfo: "ExceptionInfo[BaseException]", excrepr: "ExceptionRepr",
excinfo: "ExceptionInfo[BaseException]",
) -> Optional[bool]: ) -> Optional[bool]:
"""Called for internal errors. """Called for internal errors.

View File

@ -486,7 +486,7 @@ class LogXML:
) )
self.node_reporters: Dict[ self.node_reporters: Dict[
Tuple[Union[str, TestReport], object], _NodeReporter Tuple[Union[str, TestReport], object], _NodeReporter
] = ({}) ] = {}
self.node_reporters_ordered: List[_NodeReporter] = [] self.node_reporters_ordered: List[_NodeReporter] = []
self.global_properties: List[Tuple[str, str]] = [] self.global_properties: List[Tuple[str, str]] = []

View File

@ -685,9 +685,11 @@ class LoggingPlugin:
def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None, None, None]: def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None, None, None]:
"""Implement the internals of the pytest_runtest_xxx() hooks.""" """Implement the internals of the pytest_runtest_xxx() hooks."""
with catching_logs( with catching_logs(
self.caplog_handler, level=self.log_level, self.caplog_handler,
level=self.log_level,
) as caplog_handler, catching_logs( ) as caplog_handler, catching_logs(
self.report_handler, level=self.log_level, self.report_handler,
level=self.log_level,
) as report_handler: ) as report_handler:
caplog_handler.reset() caplog_handler.reset()
report_handler.reset() report_handler.reset()

View File

@ -116,7 +116,9 @@ def pytest_addoption(parser: Parser) -> None:
help="markers not registered in the `markers` section of the configuration file raise errors.", help="markers not registered in the `markers` section of the configuration file raise errors.",
) )
group._addoption( group._addoption(
"--strict", action="store_true", help="(deprecated) alias to --strict-markers.", "--strict",
action="store_true",
help="(deprecated) alias to --strict-markers.",
) )
group._addoption( group._addoption(
"-c", "-c",
@ -656,11 +658,11 @@ class Session(nodes.FSCollector):
# Keep track of any collected nodes in here, so we don't duplicate fixtures. # Keep track of any collected nodes in here, so we don't duplicate fixtures.
node_cache1: Dict[Path, Sequence[nodes.Collector]] = {} 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 # Keep track of any collected collectors in matchnodes paths, so they
# are not collected more than once. # 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. # Dirnames of pkgs with dunder-init files.
pkg_roots: Dict[str, Package] = {} pkg_roots: Dict[str, Package] = {}

View File

@ -56,7 +56,10 @@ def param(
@pytest.mark.parametrize( @pytest.mark.parametrize(
"test_input,expected", "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): def test_eval(test_input, expected):
assert eval(test_input) == expected assert eval(test_input) == expected

View File

@ -102,7 +102,8 @@ class Scanner:
pos += len(value) pos += len(value)
else: else:
raise ParseError( raise ParseError(
pos + 1, 'unexpected character "{}"'.format(input[pos]), pos + 1,
'unexpected character "{}"'.format(input[pos]),
) )
yield Token(TokenType.EOF, "", pos) yield Token(TokenType.EOF, "", pos)
@ -120,7 +121,8 @@ class Scanner:
raise ParseError( raise ParseError(
self.current.pos + 1, self.current.pos + 1,
"expected {}; got {}".format( "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)) astexpr = expression(Scanner(input))
code: types.CodeType = compile( code: types.CodeType = compile(
astexpr, filename="<pytest match expression>", mode="eval", astexpr,
filename="<pytest match expression>",
mode="eval",
) )
return Expression(code) return Expression(code)

View File

@ -460,15 +460,11 @@ if TYPE_CHECKING:
... ...
class _UsefixturesMarkDecorator(MarkDecorator): class _UsefixturesMarkDecorator(MarkDecorator):
def __call__( # type: ignore[override] def __call__(self, *fixtures: str) -> MarkDecorator: # type: ignore[override]
self, *fixtures: str
) -> MarkDecorator:
... ...
class _FilterwarningsMarkDecorator(MarkDecorator): class _FilterwarningsMarkDecorator(MarkDecorator):
def __call__( # type: ignore[override] def __call__(self, *filters: str) -> MarkDecorator: # type: ignore[override]
self, *filters: str
) -> MarkDecorator:
... ...

View File

@ -124,7 +124,7 @@ class MonkeyPatch:
def __init__(self) -> None: def __init__(self) -> None:
self._setattr: List[Tuple[object, str, object]] = [] 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._cwd: Optional[str] = None
self._savesyspath: Optional[List[str]] = None self._savesyspath: Optional[List[str]] = None
@ -157,13 +157,21 @@ class MonkeyPatch:
@overload @overload
def setattr( def setattr(
self, target: str, name: object, value: Notset = ..., raising: bool = ..., self,
target: str,
name: object,
value: Notset = ...,
raising: bool = ...,
) -> None: ) -> None:
... ...
@overload @overload
def setattr( def setattr(
self, target: object, name: str, value: object, raising: bool = ..., self,
target: object,
name: str,
value: object,
raising: bool = ...,
) -> None: ) -> None:
... ...

View File

@ -231,7 +231,10 @@ class Node(metaclass=NodeMeta):
path, lineno = get_fslocation_from_item(self) path, lineno = get_fslocation_from_item(self)
assert lineno is not None assert lineno is not None
warnings.warn_explicit( 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. # Methods for ordering nodes.

View File

@ -291,13 +291,15 @@ class HookRecorder:
@overload @overload
def getreports( def getreports(
self, names: "Literal['pytest_collectreport']", self,
names: "Literal['pytest_collectreport']",
) -> Sequence[CollectReport]: ) -> Sequence[CollectReport]:
... ...
@overload @overload
def getreports( def getreports(
self, names: "Literal['pytest_runtest_logreport']", self,
names: "Literal['pytest_runtest_logreport']",
) -> Sequence[TestReport]: ) -> Sequence[TestReport]:
... ...
@ -354,13 +356,15 @@ class HookRecorder:
@overload @overload
def getfailures( def getfailures(
self, names: "Literal['pytest_collectreport']", self,
names: "Literal['pytest_collectreport']",
) -> Sequence[CollectReport]: ) -> Sequence[CollectReport]:
... ...
@overload @overload
def getfailures( def getfailures(
self, names: "Literal['pytest_runtest_logreport']", self,
names: "Literal['pytest_runtest_logreport']",
) -> Sequence[TestReport]: ) -> Sequence[TestReport]:
... ...
@ -419,7 +423,10 @@ class HookRecorder:
outcomes = self.listoutcomes() outcomes = self.listoutcomes()
assertoutcome( assertoutcome(
outcomes, passed=passed, skipped=skipped, failed=failed, outcomes,
passed=passed,
skipped=skipped,
failed=failed,
) )
def clear(self) -> None: def clear(self) -> None:
@ -659,7 +666,7 @@ class Pytester:
self._request = request self._request = request
self._mod_collections: WeakKeyDictionary[ self._mod_collections: WeakKeyDictionary[
Collector, List[Union[Item, Collector]] Collector, List[Union[Item, Collector]]
] = (WeakKeyDictionary()) ] = WeakKeyDictionary()
if request.function: if request.function:
name: str = request.function.__name__ name: str = request.function.__name__
else: else:

View File

@ -1202,7 +1202,9 @@ class Metafunc:
return new_ids return new_ids
def _resolve_arg_value_types( 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']"]: ) -> Dict[str, "Literal['params', 'funcargs']"]:
"""Resolve if each parametrized argument must be considered a """Resolve if each parametrized argument must be considered a
parameter to a fixture or a "funcarg" to the function, based on the parameter to a fixture or a "funcarg" to the function, based on the
@ -1240,7 +1242,9 @@ class Metafunc:
return valtypes return valtypes
def _validate_if_using_arg_names( 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: ) -> None:
"""Check if all argnames are being used, by default values, or directly/indirectly. """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. # TODO: Type ignored -- breaks Liskov Substitution.
def repr_failure( # type: ignore[override] def repr_failure( # type: ignore[override]
self, excinfo: ExceptionInfo[BaseException], self,
excinfo: ExceptionInfo[BaseException],
) -> Union[str, TerminalRepr]: ) -> Union[str, TerminalRepr]:
style = self.config.getoption("tbstyle", "auto") style = self.config.getoption("tbstyle", "auto")
if style == "auto": if style == "auto":

View File

@ -307,7 +307,7 @@ class TestReport(BaseReport):
Tuple[str, int, str], Tuple[str, int, str],
str, str,
TerminalRepr, TerminalRepr,
] = (None) ] = None
else: else:
if not isinstance(excinfo, ExceptionInfo): if not isinstance(excinfo, ExceptionInfo):
outcome = "failed" outcome = "failed"

View File

@ -468,7 +468,9 @@ class TerminalReporter:
return True return True
def pytest_warning_recorded( def pytest_warning_recorded(
self, warning_message: warnings.WarningMessage, nodeid: str, self,
warning_message: warnings.WarningMessage,
nodeid: str,
) -> None: ) -> None:
from _pytest.warnings import warning_record_to_str from _pytest.warnings import warning_record_to_str
@ -1306,7 +1308,8 @@ def _get_line_with_reprcrash_message(
def _folded_skips( def _folded_skips(
startpath: Path, skipped: Sequence[CollectReport], startpath: Path,
skipped: Sequence[CollectReport],
) -> List[Tuple[int, str, Optional[int], str]]: ) -> List[Tuple[int, str, Optional[int], str]]:
d: Dict[Tuple[str, Optional[int], str], List[CollectReport]] = {} d: Dict[Tuple[str, Optional[int], str], List[CollectReport]] = {}
for event in skipped: for event in skipped:

View File

@ -69,7 +69,9 @@ def thread_exception_runtest_hook() -> Generator[None, None, None]:
msg = f"Exception in thread {thread_name}\n\n" msg = f"Exception in thread {thread_name}\n\n"
msg += "".join( msg += "".join(
traceback.format_exception( 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)) warnings.warn(pytest.PytestUnhandledThreadExceptionWarning(msg))

View File

@ -53,7 +53,10 @@ class TempPathFactory:
@classmethod @classmethod
def from_config( def from_config(
cls, config: Config, *, _ispytest: bool = False, cls,
config: Config,
*,
_ispytest: bool = False,
) -> "TempPathFactory": ) -> "TempPathFactory":
"""Create a factory according to pytest configuration. """Create a factory according to pytest configuration.

View File

@ -29,10 +29,16 @@ class C3:
def test_recursive_dataclasses(): def test_recursive_dataclasses():
left = C3( 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( 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 assert left == right

View File

@ -258,13 +258,22 @@ class TestTerminalWriterLineWidth:
id="with markup and code_highlight", id="with markup and code_highlight",
), ),
pytest.param( 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( 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( pytest.param(
False, False, "assert 0\n", id="neither markup nor code_highlight", False,
False,
"assert 0\n",
id="neither markup nor code_highlight",
), ),
], ],
) )

View File

@ -514,7 +514,8 @@ class TestApprox:
) )
def test_expected_value_type_error(self, x, name): def test_expected_value_type_error(self, x, name):
with pytest.raises( 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) approx(x)

View File

@ -514,7 +514,10 @@ class TestMetafunc:
] ]
for config, expected in values: for config, expected in values:
result = idmaker( 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] assert result == [expected]
@ -546,7 +549,10 @@ class TestMetafunc:
] ]
for config, expected in values: for config, expected in values:
result = idmaker( result = idmaker(
("a",), [pytest.param("string")], ids=["ação"], config=config, ("a",),
[pytest.param("string")],
ids=["ação"],
config=config,
) )
assert result == [expected] assert result == [expected]

View File

@ -1431,7 +1431,8 @@ def test_error_attribute_issue555(pytester: Pytester) -> None:
@pytest.mark.skipif( @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: def test_py36_windowsconsoleio_workaround_non_standard_streams() -> None:
""" """

View File

@ -877,7 +877,9 @@ class TestPDB:
assert custom_pdb_calls == [] assert custom_pdb_calls == []
def test_pdb_custom_cls_with_set_trace( def test_pdb_custom_cls_with_set_trace(
self, pytester: Pytester, monkeypatch: MonkeyPatch, self,
pytester: Pytester,
monkeypatch: MonkeyPatch,
) -> None: ) -> None:
pytester.makepyfile( pytester.makepyfile(
custom_pdb=""" custom_pdb="""

View File

@ -69,7 +69,9 @@ class TestDoctests:
@pytest.mark.parametrize("filename", ["__init__", "whatever"]) @pytest.mark.parametrize("filename", ["__init__", "whatever"])
def test_collect_module_two_doctest_no_modulelevel( def test_collect_module_two_doctest_no_modulelevel(
self, pytester: Pytester, filename: str, self,
pytester: Pytester,
filename: str,
) -> None: ) -> None:
path = pytester.makepyfile( path = pytester.makepyfile(
**{ **{

View File

@ -356,8 +356,14 @@ def test_parametrize_with_module(pytester: Pytester) -> None:
"foo or or", "foo or or",
"at column 8: expected not OR left parenthesis OR identifier; got 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", "or or",
"at column 1: expected not OR left parenthesis OR identifier; got or", "at column 1: expected not OR left parenthesis OR identifier; got or",
@ -863,7 +869,8 @@ class TestKeywordSelection:
assert passed + skipped + failed == 0 assert passed + skipped + failed == 0
@pytest.mark.parametrize( @pytest.mark.parametrize(
"keyword", ["__", "+", ".."], "keyword",
["__", "+", ".."],
) )
def test_no_magic_values(self, pytester: Pytester, keyword: str) -> None: def test_no_magic_values(self, pytester: Pytester, keyword: str) -> None:
"""Make sure the tests do not match on magic values, """Make sure the tests do not match on magic values,

View File

@ -70,7 +70,11 @@ def test_syntax_oddeties(expr: str, expected: bool) -> None:
("expr", "column", "message"), ("expr", "column", "message"),
( (
("(", 2, "expected not OR left parenthesis OR identifier; got end of input"), ("(", 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, 1,
@ -81,7 +85,11 @@ def test_syntax_oddeties(expr: str, expected: bool) -> None:
1, 1,
"expected not OR left parenthesis OR identifier; got right parenthesis", "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", "not not",
8, 8,
@ -98,7 +106,11 @@ def test_syntax_oddeties(expr: str, expected: bool) -> None:
10, 10,
"expected not OR left parenthesis OR identifier; got end of input", "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"), ("ident ident", 7, "expected end of input; got identifier"),
), ),
) )

View File

@ -348,7 +348,9 @@ class SampleInherit(Sample):
@pytest.mark.parametrize( @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: def test_issue156_undo_staticmethod(Sample: Type[Sample]) -> None:
monkeypatch = MonkeyPatch() monkeypatch = MonkeyPatch()

View File

@ -346,7 +346,9 @@ class TestPytestPluginManager:
assert mod.x == 3 assert mod.x == 3
def test_consider_conftest_deps( def test_consider_conftest_deps(
self, pytester: Pytester, pytestpm: PytestPluginManager, self,
pytester: Pytester,
pytestpm: PytestPluginManager,
) -> None: ) -> None:
mod = import_path(pytester.makepyfile("pytest_plugins='xyz'")) mod = import_path(pytester.makepyfile("pytest_plugins='xyz'"))
with pytest.raises(ImportError): with pytest.raises(ImportError):

View File

@ -242,7 +242,9 @@ def test_setup_funcarg_setup_when_outer_scope_fails(pytester: Pytester) -> None:
@pytest.mark.parametrize("arg", ["", "arg"]) @pytest.mark.parametrize("arg", ["", "arg"])
def test_setup_teardown_function_level_with_optional_argument( def test_setup_teardown_function_level_with_optional_argument(
pytester: Pytester, monkeypatch, arg: str, pytester: Pytester,
monkeypatch,
arg: str,
) -> None: ) -> None:
"""Parameter to setup/teardown xunit-style functions parameter is now optional (#1728).""" """Parameter to setup/teardown xunit-style functions parameter is now optional (#1728)."""
import sys import sys

View File

@ -138,7 +138,12 @@ def test_fail_and_continue_with_stepwise(stepwise_pytester: Pytester) -> None:
@pytest.mark.parametrize("stepwise_skip", ["--stepwise-skip", "--sw-skip"]) @pytest.mark.parametrize("stepwise_skip", ["--stepwise-skip", "--sw-skip"])
def test_run_with_skip_option(stepwise_pytester: Pytester, stepwise_skip: str) -> None: def test_run_with_skip_option(stepwise_pytester: Pytester, stepwise_skip: str) -> None:
result = stepwise_pytester.runpytest( 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) == [] assert _strip_resource_warnings(result.stderr.lines) == []

View File

@ -662,7 +662,7 @@ class TestStackLevel:
class CapturedWarnings: class CapturedWarnings:
captured: List[ captured: List[
Tuple[warnings.WarningMessage, Optional[Tuple[str, int, str]]] Tuple[warnings.WarningMessage, Optional[Tuple[str, int, str]]]
] = ([]) ] = []
@classmethod @classmethod
def pytest_warning_recorded(cls, warning_message, when, nodeid, location): def pytest_warning_recorded(cls, warning_message, when, nodeid, location):