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

View File

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

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."""
def pytest_testnodedown(self, node, error):
"""standard xdist hook function.
"""
"""standard xdist hook function."""
def pytest_configure(config):

View File

@ -36,7 +36,7 @@ which will usually be called once for all the functions:
def teardown_module(module):
""" teardown any state that was previously setup with a setup_module
"""teardown any state that was previously setup with a setup_module
method.
"""
@ -52,14 +52,14 @@ and after all test methods of the class are called:
@classmethod
def setup_class(cls):
""" setup any state specific to the execution of the given class (which
"""setup any state specific to the execution of the given class (which
usually contains tests).
"""
@classmethod
def teardown_class(cls):
""" teardown any state that was previously setup with a call to
"""teardown any state that was previously setup with a call to
setup_class.
"""
@ -71,13 +71,13 @@ Similarly, the following methods are called around each method invocation:
.. code-block:: python
def setup_method(self, method):
""" setup any state tied to the execution of the given method in a
"""setup any state tied to the execution of the given method in a
class. setup_method is invoked for every test method of a class.
"""
def teardown_method(self, method):
""" teardown any state that was previously setup with a setup_method
"""teardown any state that was previously setup with a setup_method
call.
"""
@ -89,13 +89,13 @@ you can also use the following functions to implement fixtures:
.. code-block:: python
def setup_function(function):
""" setup any state tied to the execution of the given function.
"""setup any state tied to the execution of the given function.
Invoked for every test function in the module.
"""
def teardown_function(function):
""" teardown any state that was previously setup with a setup_function
"""teardown any state that was previously setup with a setup_function
call.
"""

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"]
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.")

View File

@ -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"

View File

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

View File

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

View File

@ -219,7 +219,8 @@ class LFPluginCollWrapper:
# Sort any lf-paths to the beginning.
lf_paths = self.lfplugin._last_failed_paths
res.result = sorted(
res.result, key=lambda x: 0 if Path(str(x.fspath)) in lf_paths else 1,
res.result,
key=lambda x: 0 if Path(str(x.fspath)) in lf_paths else 1,
)
return

View File

@ -556,7 +556,11 @@ class MultiCapture(Generic[AnyStr]):
def __repr__(self) -> str:
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:
@ -843,7 +847,9 @@ class CaptureFixture(Generic[AnyStr]):
def _start(self) -> None:
if self._capture is None:
self._capture = MultiCapture(
in_=None, out=self.captureclass(1), err=self.captureclass(2),
in_=None,
out=self.captureclass(1),
err=self.captureclass(2),
)
self._capture.start_capturing()

View File

@ -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(

View File

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

View File

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

View File

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

View File

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

View File

@ -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.

View File

@ -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.

View File

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

View File

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

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.",
)
group._addoption(
"--strict", action="store_true", help="(deprecated) alias to --strict-markers.",
"--strict",
action="store_true",
help="(deprecated) alias to --strict-markers.",
)
group._addoption(
"-c",
@ -656,11 +658,11 @@ class Session(nodes.FSCollector):
# Keep track of any collected nodes in here, so we don't duplicate fixtures.
node_cache1: Dict[Path, Sequence[nodes.Collector]] = {}
node_cache2: Dict[Tuple[Type[nodes.Collector], Path], nodes.Collector] = ({})
node_cache2: Dict[Tuple[Type[nodes.Collector], Path], nodes.Collector] = {}
# Keep track of any collected collectors in matchnodes paths, so they
# are not collected more than once.
matchnodes_cache: Dict[Tuple[Type[nodes.Collector], str], CollectReport] = ({})
matchnodes_cache: Dict[Tuple[Type[nodes.Collector], str], CollectReport] = {}
# Dirnames of pkgs with dunder-init files.
pkg_roots: Dict[str, Package] = {}

View File

@ -56,7 +56,10 @@ def param(
@pytest.mark.parametrize(
"test_input,expected",
[("3+5", 8), pytest.param("6*9", 42, marks=pytest.mark.xfail),],
[
("3+5", 8),
pytest.param("6*9", 42, marks=pytest.mark.xfail),
],
)
def test_eval(test_input, expected):
assert eval(test_input) == expected

View File

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

View File

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

View File

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

View File

@ -231,7 +231,10 @@ class Node(metaclass=NodeMeta):
path, lineno = get_fslocation_from_item(self)
assert lineno is not None
warnings.warn_explicit(
warning, category=None, filename=str(path), lineno=lineno + 1,
warning,
category=None,
filename=str(path),
lineno=lineno + 1,
)
# Methods for ordering nodes.

View File

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

View File

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

View File

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

View File

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

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 += "".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))

View File

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

View File

@ -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

View File

@ -258,13 +258,22 @@ class TestTerminalWriterLineWidth:
id="with markup and code_highlight",
),
pytest.param(
True, False, "assert 0\n", id="with markup but no code_highlight",
True,
False,
"assert 0\n",
id="with markup but no code_highlight",
),
pytest.param(
False, True, "assert 0\n", id="without markup but with code_highlight",
False,
True,
"assert 0\n",
id="without markup but with code_highlight",
),
pytest.param(
False, False, "assert 0\n", id="neither markup nor code_highlight",
False,
False,
"assert 0\n",
id="neither markup nor code_highlight",
),
],
)

View File

@ -514,7 +514,8 @@ class TestApprox:
)
def test_expected_value_type_error(self, x, name):
with pytest.raises(
TypeError, match=fr"pytest.approx\(\) does not support nested {name}:",
TypeError,
match=fr"pytest.approx\(\) does not support nested {name}:",
):
approx(x)

View File

@ -514,7 +514,10 @@ class TestMetafunc:
]
for config, expected in values:
result = idmaker(
("a",), [pytest.param("string")], idfn=lambda _: "ação", config=config,
("a",),
[pytest.param("string")],
idfn=lambda _: "ação",
config=config,
)
assert result == [expected]
@ -546,7 +549,10 @@ class TestMetafunc:
]
for config, expected in values:
result = idmaker(
("a",), [pytest.param("string")], ids=["ação"], config=config,
("a",),
[pytest.param("string")],
ids=["ação"],
config=config,
)
assert result == [expected]

View File

@ -1431,7 +1431,8 @@ def test_error_attribute_issue555(pytester: Pytester) -> None:
@pytest.mark.skipif(
not sys.platform.startswith("win"), reason="only on windows",
not sys.platform.startswith("win"),
reason="only on windows",
)
def test_py36_windowsconsoleio_workaround_non_standard_streams() -> None:
"""

View File

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

View File

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

View File

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

View File

@ -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"),
),
)

View File

@ -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()

View File

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

View File

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

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"])
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) == []

View File

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