[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
45 changed files with 280 additions and 121 deletions

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.