[pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci
This commit is contained in:
pre-commit-ci[bot] 2024-03-13 00:40:31 +00:00
parent f3e6dda15c
commit b41bdc50be
46 changed files with 102 additions and 126 deletions

View File

@ -8,6 +8,7 @@ our CHANGELOG) into Markdown (which is required by GitHub Releases).
Requires Python3.6+. Requires Python3.6+.
""" """
from pathlib import Path from pathlib import Path
import re import re
import sys import sys

View File

@ -13,6 +13,7 @@ After that, it will create a release using the `release` tox environment, and pu
**Token**: currently the token from the GitHub Actions is used, pushed with **Token**: currently the token from the GitHub Actions is used, pushed with
`pytest bot <pytestbot@gmail.com>` commit author. `pytest bot <pytestbot@gmail.com>` commit author.
""" """
import argparse import argparse
from pathlib import Path from pathlib import Path
import re import re

View File

@ -1,5 +1,6 @@
# mypy: disallow-untyped-defs # mypy: disallow-untyped-defs
"""Invoke development tasks.""" """Invoke development tasks."""
import argparse import argparse
import os import os
from pathlib import Path from pathlib import Path

View File

@ -279,9 +279,9 @@ class TracebackEntry:
Mostly for internal use. Mostly for internal use.
""" """
tbh: Union[ tbh: Union[bool, Callable[[Optional[ExceptionInfo[BaseException]]], bool]] = (
bool, Callable[[Optional[ExceptionInfo[BaseException]]], bool] False
] = 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
@ -378,12 +378,10 @@ class Traceback(List[TracebackEntry]):
return self return self
@overload @overload
def __getitem__(self, key: "SupportsIndex") -> TracebackEntry: def __getitem__(self, key: "SupportsIndex") -> TracebackEntry: ...
...
@overload @overload
def __getitem__(self, key: slice) -> "Traceback": def __getitem__(self, key: slice) -> "Traceback": ...
...
def __getitem__( def __getitem__(
self, key: Union["SupportsIndex", slice] self, key: Union["SupportsIndex", slice]
@ -1051,13 +1049,13 @@ class FormattedExcinfo:
# full support for exception groups added to ExceptionInfo. # full support for exception groups added to ExceptionInfo.
# See https://github.com/pytest-dev/pytest/issues/9159 # See https://github.com/pytest-dev/pytest/issues/9159
if isinstance(e, BaseExceptionGroup): if isinstance(e, BaseExceptionGroup):
reprtraceback: Union[ reprtraceback: Union[ReprTracebackNative, ReprTraceback] = (
ReprTracebackNative, ReprTraceback ReprTracebackNative(
] = ReprTracebackNative( traceback.format_exception(
traceback.format_exception( type(excinfo_.value),
type(excinfo_.value), excinfo_.value,
excinfo_.value, excinfo_.traceback[0]._rawentry,
excinfo_.traceback[0]._rawentry, )
) )
) )
else: else:

View File

@ -47,12 +47,10 @@ class Source:
__hash__ = None # type: ignore __hash__ = None # type: ignore
@overload @overload
def __getitem__(self, key: int) -> str: def __getitem__(self, key: int) -> str: ...
...
@overload @overload
def __getitem__(self, key: slice) -> "Source": def __getitem__(self, key: slice) -> "Source": ...
...
def __getitem__(self, key: Union[int, slice]) -> Union[str, "Source"]: def __getitem__(self, key: Union[int, slice]) -> Union[str, "Source"]:
if isinstance(key, int): if isinstance(key, int):

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""local path implementation.""" """local path implementation."""
from __future__ import annotations from __future__ import annotations
import atexit import atexit
@ -205,12 +206,10 @@ class Stat:
if TYPE_CHECKING: if TYPE_CHECKING:
@property @property
def size(self) -> int: def size(self) -> int: ...
...
@property @property
def mtime(self) -> float: def mtime(self) -> float: ...
...
def __getattr__(self, name: str) -> Any: def __getattr__(self, name: str) -> Any:
return getattr(self._osstatresult, "st_" + name) return getattr(self._osstatresult, "st_" + name)
@ -966,12 +965,10 @@ class LocalPath:
return p return p
@overload @overload
def stat(self, raising: Literal[True] = ...) -> Stat: def stat(self, raising: Literal[True] = ...) -> Stat: ...
...
@overload @overload
def stat(self, raising: Literal[False]) -> Stat | None: def stat(self, raising: Literal[False]) -> Stat | None: ...
...
def stat(self, raising: bool = True) -> Stat | None: def stat(self, raising: bool = True) -> Stat | None:
"""Return an os.stat() tuple.""" """Return an os.stat() tuple."""

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Support for presenting detailed information in failing assertions.""" """Support for presenting detailed information in failing assertions."""
import sys import sys
from typing import Any from typing import Any
from typing import Generator from typing import Generator

View File

@ -672,9 +672,9 @@ class AssertionRewriter(ast.NodeVisitor):
self.enable_assertion_pass_hook = False self.enable_assertion_pass_hook = False
self.source = source self.source = source
self.scope: tuple[ast.AST, ...] = () self.scope: tuple[ast.AST, ...] = ()
self.variables_overwrite: defaultdict[ self.variables_overwrite: defaultdict[tuple[ast.AST, ...], Dict[str, str]] = (
tuple[ast.AST, ...], Dict[str, str] defaultdict(dict)
] = defaultdict(dict) )
def run(self, mod: ast.Module) -> None: def run(self, mod: ast.Module) -> None:
"""Find all assert statements in *mod* and rewrite them.""" """Find all assert statements in *mod* and rewrite them."""

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Utilities for assertion debugging.""" """Utilities for assertion debugging."""
import collections.abc import collections.abc
import os import os
import pprint import pprint
@ -223,9 +224,7 @@ def assertrepr_compare(
raise raise
except Exception: except Exception:
explanation = [ explanation = [
"(pytest_assertion plugin: representation of details failed: {}.".format( f"(pytest_assertion plugin: representation of details failed: {_pytest._code.ExceptionInfo.from_current()._getreprcrash()}.",
_pytest._code.ExceptionInfo.from_current()._getreprcrash()
),
" Probably an object has a faulty __repr__.)", " Probably an object has a faulty __repr__.)",
] ]

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Implementation of the cache provider.""" """Implementation of the cache provider."""
# This plugin was not named "cache" to avoid conflicts with the external # This plugin was not named "cache" to avoid conflicts with the external
# pytest-cache version. # pytest-cache version.
import dataclasses import dataclasses

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Per-test stdout/stderr capturing mechanism.""" """Per-test stdout/stderr capturing mechanism."""
import abc import abc
import collections import collections
import contextlib import contextlib
@ -482,13 +483,7 @@ class FDCaptureBase(CaptureBase[AnyStr]):
self._state = "initialized" self._state = "initialized"
def __repr__(self) -> str: def __repr__(self) -> str:
return "<{} {} oldfd={} _state={!r} tmpfile={!r}>".format( return f"<{self.__class__.__name__} {self.targetfd} oldfd={self.targetfd_save} _state={self._state!r} tmpfile={self.tmpfile!r}>"
self.__class__.__name__,
self.targetfd,
self.targetfd_save,
self._state,
self.tmpfile,
)
def _assert_state(self, op: str, states: Tuple[str, ...]) -> None: def _assert_state(self, op: str, states: Tuple[str, ...]) -> None:
assert ( assert (
@ -621,13 +616,7 @@ class MultiCapture(Generic[AnyStr]):
self.err: Optional[CaptureBase[AnyStr]] = err self.err: Optional[CaptureBase[AnyStr]] = err
def __repr__(self) -> str: def __repr__(self) -> str:
return "<MultiCapture out={!r} err={!r} in_={!r} _state={!r} _in_suspended={!r}>".format( return f"<MultiCapture out={self.out!r} err={self.err!r} in_={self.in_!r} _state={self._state!r} _in_suspended={self._in_suspended!r}>"
self.out,
self.err,
self.in_,
self._state,
self._in_suspended,
)
def start_capturing(self) -> None: def start_capturing(self) -> None:
self._state = "started" self._state = "started"
@ -735,9 +724,7 @@ class CaptureManager:
self._capture_fixture: Optional[CaptureFixture[Any]] = None self._capture_fixture: Optional[CaptureFixture[Any]] = None
def __repr__(self) -> str: def __repr__(self) -> str:
return "<CaptureManager _method={!r} _global_capturing={!r} _capture_fixture={!r}>".format( return f"<CaptureManager _method={self._method!r} _global_capturing={self._global_capturing!r} _capture_fixture={self._capture_fixture!r}>"
self._method, self._global_capturing, self._capture_fixture
)
def is_capturing(self) -> Union[str, bool]: def is_capturing(self) -> Union[str, bool]:
if self.is_globally_capturing(): if self.is_globally_capturing():

View File

@ -304,7 +304,7 @@ def get_user_id() -> int | None:
# mypy follows the version and platform checking expectation of PEP 484: # mypy follows the version and platform checking expectation of PEP 484:
# https://mypy.readthedocs.io/en/stable/common_issues.html?highlight=platform#python-version-and-system-platform-checks # https://mypy.readthedocs.io/en/stable/common_issues.html?highlight=platform#python-version-and-system-platform-checks
# Containment checks are too complex for mypy v1.5.0 and cause failure. # Containment checks are too complex for mypy v1.5.0 and cause failure.
if sys.platform == "win32" or sys.platform == "emscripten": # noqa: PLR1714 if sys.platform == "win32" or sys.platform == "emscripten":
# win32 does not have a getuid() function. # win32 does not have a getuid() function.
# Emscripten has a return 0 stub. # Emscripten has a return 0 stub.
return None return None

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Command line options, ini-file and conftest.py processing.""" """Command line options, ini-file and conftest.py processing."""
import argparse import argparse
import collections.abc import collections.abc
import copy import copy

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Interactive debugging with PDB, the Python Debugger.""" """Interactive debugging with PDB, the Python Debugger."""
import argparse import argparse
import functools import functools
import sys import sys

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Discover and run doctests in modules and test files.""" """Discover and run doctests in modules and test files."""
import bdb import bdb
from contextlib import contextmanager from contextlib import contextmanager
import functools import functools

View File

@ -631,15 +631,9 @@ class FixtureRequest(abc.ABC):
source_path_str = str(source_path) source_path_str = str(source_path)
msg = ( msg = (
"The requested fixture has no parameter defined for test:\n" "The requested fixture has no parameter defined for test:\n"
" {}\n\n" f" {funcitem.nodeid}\n\n"
"Requested fixture '{}' defined in:\n{}" f"Requested fixture '{fixturedef.argname}' defined in:\n{getlocation(fixturedef.func, funcitem.config.rootpath)}"
"\n\nRequested here:\n{}:{}".format( f"\n\nRequested here:\n{source_path_str}:{source_lineno}"
funcitem.nodeid,
fixturedef.argname,
getlocation(fixturedef.func, funcitem.config.rootpath),
source_path_str,
source_lineno,
)
) )
fail(msg, pytrace=False) fail(msg, pytrace=False)
@ -1148,11 +1142,11 @@ def wrap_function_to_error_out_if_called_directly(
"""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."""
message = ( message = (
'Fixture "{name}" called directly. Fixtures are not meant to be called directly,\n' f'Fixture "{fixture_marker.name or function.__name__}" called directly. Fixtures are not meant to be called directly,\n'
"but are created automatically when test functions request them as parameters.\n" "but are created automatically when test functions request them as parameters.\n"
"See https://docs.pytest.org/en/stable/explanation/fixtures.html for more information about fixtures, and\n" "See https://docs.pytest.org/en/stable/explanation/fixtures.html for more information about fixtures, and\n"
"https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly about how to update your code." "https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly about how to update your code."
).format(name=fixture_marker.name or function.__name__) )
@functools.wraps(function) @functools.wraps(function)
def result(*args, **kwargs): def result(*args, **kwargs):
@ -1219,8 +1213,7 @@ def fixture(
Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]] Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]
] = ..., ] = ...,
name: Optional[str] = ..., name: Optional[str] = ...,
) -> FixtureFunction: ) -> FixtureFunction: ...
...
@overload @overload
@ -1234,8 +1227,7 @@ def fixture(
Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]] Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]
] = ..., ] = ...,
name: Optional[str] = None, name: Optional[str] = None,
) -> FixtureFunctionMarker: ) -> FixtureFunctionMarker: ...
...
def fixture( def fixture(

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Version info, help messages, tracing configuration.""" """Version info, help messages, tracing configuration."""
from argparse import Action from argparse import Action
import os import os
import sys import sys

View File

@ -1,6 +1,7 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Hook specifications for pytest plugins which are invoked by pytest itself """Hook specifications for pytest plugins which are invoked by pytest itself
and by builtin plugins.""" and by builtin plugins."""
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
from typing import Dict from typing import Dict

View File

@ -7,6 +7,7 @@ Based on initial code from Ross Lawley.
Output conforms to Output conforms to
https://github.com/jenkinsci/xunit-plugin/blob/master/src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd https://github.com/jenkinsci/xunit-plugin/blob/master/src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd
""" """
from datetime import datetime from datetime import datetime
import functools import functools
import os import os
@ -60,7 +61,7 @@ def bin_xml_escape(arg: object) -> str:
# Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] # Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
# For an unknown(?) reason, we disallow #x7F (DEL) as well. # For an unknown(?) reason, we disallow #x7F (DEL) as well.
illegal_xml_re = ( illegal_xml_re = (
"[^\u0009\u000A\u000D\u0020-\u007E\u0080-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]" "[^\u0009\u000a\u000d\u0020-\u007e\u0080-\ud7ff\ue000-\ufffd\u10000-\u10ffFF]"
) )
return re.sub(illegal_xml_re, repl, str(arg)) return re.sub(illegal_xml_re, repl, str(arg))

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Access and control log capturing.""" """Access and control log capturing."""
from contextlib import contextmanager from contextlib import contextmanager
from contextlib import nullcontext from contextlib import nullcontext
from datetime import datetime from datetime import datetime

View File

@ -736,14 +736,12 @@ class Session(nodes.Collector):
@overload @overload
def perform_collect( def perform_collect(
self, args: Optional[Sequence[str]] = ..., genitems: "Literal[True]" = ... self, args: Optional[Sequence[str]] = ..., genitems: "Literal[True]" = ...
) -> Sequence[nodes.Item]: ) -> Sequence[nodes.Item]: ...
...
@overload @overload
def perform_collect( def perform_collect(
self, args: Optional[Sequence[str]] = ..., genitems: bool = ... self, args: Optional[Sequence[str]] = ..., genitems: bool = ...
) -> Sequence[Union[nodes.Item, nodes.Collector]]: ) -> Sequence[Union[nodes.Item, nodes.Collector]]: ...
...
def perform_collect( def perform_collect(
self, args: Optional[Sequence[str]] = None, genitems: bool = True self, args: Optional[Sequence[str]] = None, genitems: bool = True

View File

@ -434,12 +434,10 @@ if TYPE_CHECKING:
class _SkipMarkDecorator(MarkDecorator): class _SkipMarkDecorator(MarkDecorator):
@overload # type: ignore[override,misc,no-overload-impl] @overload # type: ignore[override,misc,no-overload-impl]
def __call__(self, arg: Markable) -> Markable: def __call__(self, arg: Markable) -> Markable: ...
...
@overload @overload
def __call__(self, reason: str = ...) -> "MarkDecorator": def __call__(self, reason: str = ...) -> "MarkDecorator": ...
...
class _SkipifMarkDecorator(MarkDecorator): class _SkipifMarkDecorator(MarkDecorator):
def __call__( # type: ignore[override] def __call__( # type: ignore[override]
@ -447,13 +445,11 @@ if TYPE_CHECKING:
condition: Union[str, bool] = ..., condition: Union[str, bool] = ...,
*conditions: Union[str, bool], *conditions: Union[str, bool],
reason: str = ..., reason: str = ...,
) -> MarkDecorator: ) -> MarkDecorator: ...
...
class _XfailMarkDecorator(MarkDecorator): class _XfailMarkDecorator(MarkDecorator):
@overload # type: ignore[override,misc,no-overload-impl] @overload # type: ignore[override,misc,no-overload-impl]
def __call__(self, arg: Markable) -> Markable: def __call__(self, arg: Markable) -> Markable: ...
...
@overload @overload
def __call__( def __call__(
@ -466,8 +462,7 @@ if TYPE_CHECKING:
None, Type[BaseException], Tuple[Type[BaseException], ...] None, Type[BaseException], Tuple[Type[BaseException], ...]
] = ..., ] = ...,
strict: bool = ..., strict: bool = ...,
) -> MarkDecorator: ) -> MarkDecorator: ...
...
class _ParametrizeMarkDecorator(MarkDecorator): class _ParametrizeMarkDecorator(MarkDecorator):
def __call__( # type: ignore[override] def __call__( # type: ignore[override]
@ -483,8 +478,7 @@ if TYPE_CHECKING:
] ]
] = ..., ] = ...,
scope: Optional[_ScopeName] = ..., scope: Optional[_ScopeName] = ...,
) -> MarkDecorator: ) -> MarkDecorator: ...
...
class _UsefixturesMarkDecorator(MarkDecorator): class _UsefixturesMarkDecorator(MarkDecorator):
def __call__(self, *fixtures: str) -> MarkDecorator: # type: ignore[override] def __call__(self, *fixtures: str) -> MarkDecorator: # type: ignore[override]

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Monkeypatching and mocking functionality.""" """Monkeypatching and mocking functionality."""
from contextlib import contextmanager from contextlib import contextmanager
import os import os
import re import re
@ -167,8 +168,7 @@ class MonkeyPatch:
name: object, name: object,
value: Notset = ..., value: Notset = ...,
raising: bool = ..., raising: bool = ...,
) -> None: ) -> None: ...
...
@overload @overload
def setattr( def setattr(
@ -177,8 +177,7 @@ class MonkeyPatch:
name: str, name: str,
value: object, value: object,
raising: bool = ..., raising: bool = ...,
) -> None: ) -> None: ...
...
def setattr( def setattr(
self, self,

View File

@ -363,12 +363,10 @@ class Node(abc.ABC, metaclass=NodeMeta):
yield node, mark yield node, mark
@overload @overload
def get_closest_marker(self, name: str) -> Optional[Mark]: def get_closest_marker(self, name: str) -> Optional[Mark]: ...
...
@overload @overload
def get_closest_marker(self, name: str, default: Mark) -> Mark: def get_closest_marker(self, name: str, default: Mark) -> Mark: ...
...
def get_closest_marker( def get_closest_marker(
self, name: str, default: Optional[Mark] = None self, name: str, default: Optional[Mark] = None

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Submit failure or test session information to a pastebin service.""" """Submit failure or test session information to a pastebin service."""
from io import StringIO from io import StringIO
import tempfile import tempfile
from typing import IO from typing import IO

View File

@ -3,6 +3,7 @@
PYTEST_DONT_REWRITE PYTEST_DONT_REWRITE
""" """
import collections.abc import collections.abc
import contextlib import contextlib
from fnmatch import fnmatch from fnmatch import fnmatch
@ -245,8 +246,7 @@ class RecordedHookCall:
if TYPE_CHECKING: if TYPE_CHECKING:
# The class has undetermined attributes, this tells mypy about it. # The class has undetermined attributes, this tells mypy about it.
def __getattr__(self, key: str): def __getattr__(self, key: str): ...
...
@final @final
@ -327,15 +327,13 @@ class HookRecorder:
def getreports( def getreports(
self, self,
names: "Literal['pytest_collectreport']", names: "Literal['pytest_collectreport']",
) -> Sequence[CollectReport]: ) -> Sequence[CollectReport]: ...
...
@overload @overload
def getreports( def getreports(
self, self,
names: "Literal['pytest_runtest_logreport']", names: "Literal['pytest_runtest_logreport']",
) -> Sequence[TestReport]: ) -> Sequence[TestReport]: ...
...
@overload @overload
def getreports( def getreports(
@ -344,8 +342,7 @@ class HookRecorder:
"pytest_collectreport", "pytest_collectreport",
"pytest_runtest_logreport", "pytest_runtest_logreport",
), ),
) -> Sequence[Union[CollectReport, TestReport]]: ) -> Sequence[Union[CollectReport, TestReport]]: ...
...
def getreports( def getreports(
self, self,
@ -390,15 +387,13 @@ class HookRecorder:
def getfailures( def getfailures(
self, self,
names: "Literal['pytest_collectreport']", names: "Literal['pytest_collectreport']",
) -> Sequence[CollectReport]: ) -> Sequence[CollectReport]: ...
...
@overload @overload
def getfailures( def getfailures(
self, self,
names: "Literal['pytest_runtest_logreport']", names: "Literal['pytest_runtest_logreport']",
) -> Sequence[TestReport]: ) -> Sequence[TestReport]: ...
...
@overload @overload
def getfailures( def getfailures(
@ -407,8 +402,7 @@ class HookRecorder:
"pytest_collectreport", "pytest_collectreport",
"pytest_runtest_logreport", "pytest_runtest_logreport",
), ),
) -> Sequence[Union[CollectReport, TestReport]]: ) -> Sequence[Union[CollectReport, TestReport]]: ...
...
def getfailures( def getfailures(
self, self,

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Python test discovery, setup and run of test functions.""" """Python test discovery, setup and run of test functions."""
import abc import abc
from collections import Counter from collections import Counter
from collections import defaultdict from collections import defaultdict

View File

@ -769,8 +769,7 @@ def raises(
expected_exception: Union[Type[E], Tuple[Type[E], ...]], expected_exception: Union[Type[E], Tuple[Type[E], ...]],
*, *,
match: Optional[Union[str, Pattern[str]]] = ..., match: Optional[Union[str, Pattern[str]]] = ...,
) -> "RaisesContext[E]": ) -> "RaisesContext[E]": ...
...
@overload @overload
@ -779,8 +778,7 @@ def raises(
func: Callable[..., Any], func: Callable[..., Any],
*args: Any, *args: Any,
**kwargs: Any, **kwargs: Any,
) -> _pytest._code.ExceptionInfo[E]: ) -> _pytest._code.ExceptionInfo[E]: ...
...
def raises( def raises(

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Record warnings during test function execution.""" """Record warnings during test function execution."""
from pprint import pformat from pprint import pformat
import re import re
from types import TracebackType from types import TracebackType
@ -43,13 +44,11 @@ def recwarn() -> Generator["WarningsRecorder", None, None]:
@overload @overload
def deprecated_call( def deprecated_call(
*, match: Optional[Union[str, Pattern[str]]] = ... *, match: Optional[Union[str, Pattern[str]]] = ...
) -> "WarningsRecorder": ) -> "WarningsRecorder": ...
...
@overload @overload
def deprecated_call(func: Callable[..., T], *args: Any, **kwargs: Any) -> T: def deprecated_call(func: Callable[..., T], *args: Any, **kwargs: Any) -> T: ...
...
def deprecated_call( def deprecated_call(
@ -91,8 +90,7 @@ def warns(
expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = ..., expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = ...,
*, *,
match: Optional[Union[str, Pattern[str]]] = ..., match: Optional[Union[str, Pattern[str]]] = ...,
) -> "WarningsChecker": ) -> "WarningsChecker": ...
...
@overload @overload
@ -101,8 +99,7 @@ def warns(
func: Callable[..., T], func: Callable[..., T],
*args: Any, *args: Any,
**kwargs: Any, **kwargs: Any,
) -> T: ) -> T: ...
...
def warns( def warns(

View File

@ -72,8 +72,7 @@ class BaseReport:
if TYPE_CHECKING: if TYPE_CHECKING:
# Can have arbitrary fields given to __init__(). # Can have arbitrary fields given to __init__().
def __getattr__(self, key: str) -> Any: def __getattr__(self, key: str) -> Any: ...
...
def toterminal(self, out: TerminalWriter) -> None: def toterminal(self, out: TerminalWriter) -> None:
if hasattr(self, "node"): if hasattr(self, "node"):
@ -606,9 +605,9 @@ def _report_kwargs_from_json(reportdict: Dict[str, Any]) -> Dict[str, Any]:
description, description,
) )
) )
exception_info: Union[ exception_info: Union[ExceptionChainRepr, ReprExceptionInfo] = (
ExceptionChainRepr, ReprExceptionInfo ExceptionChainRepr(chain)
] = ExceptionChainRepr(chain) )
else: else:
exception_info = ReprExceptionInfo( exception_info = ReprExceptionInfo(
reprtraceback=reprtraceback, reprtraceback=reprtraceback,

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Basic collect and runtest protocol implementations.""" """Basic collect and runtest protocol implementations."""
import bdb import bdb
import dataclasses import dataclasses
import os import os

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Support for skip/xfail functions and markers.""" """Support for skip/xfail functions and markers."""
from collections.abc import Mapping from collections.abc import Mapping
import dataclasses import dataclasses
import os import os

View File

@ -3,6 +3,7 @@
This is a good source for looking at the various reporting hooks. This is a good source for looking at the various reporting hooks.
""" """
import argparse import argparse
from collections import Counter from collections import Counter
import dataclasses import dataclasses

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Support for providing temporary directories to test functions.""" """Support for providing temporary directories to test functions."""
import dataclasses import dataclasses
import os import os
from pathlib import Path from pathlib import Path

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Discover and run std-library "unittest" style tests.""" """Discover and run std-library "unittest" style tests."""
import sys import sys
import traceback import traceback
import types import types

View File

@ -1,5 +1,6 @@
# PYTHON_ARGCOMPLETE_OK # PYTHON_ARGCOMPLETE_OK
"""pytest: unit and functional testing with Python.""" """pytest: unit and functional testing with Python."""
from _pytest import __version__ from _pytest import __version__
from _pytest import version_tuple from _pytest import version_tuple
from _pytest._code import ExceptionInfo from _pytest._code import ExceptionInfo

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Reproduces issue #3774""" """Reproduces issue #3774"""
from unittest import mock from unittest import mock
import pytest import pytest

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Skipping an entire subclass with unittest.skip() should *not* call setUp from a base class.""" """Skipping an entire subclass with unittest.skip() should *not* call setUp from a base class."""
import unittest import unittest

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Skipping an entire subclass with unittest.skip() should *not* call setUpClass from a base class.""" """Skipping an entire subclass with unittest.skip() should *not* call setUpClass from a base class."""
import unittest import unittest

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""setUpModule is always called, even if all tests in the module are skipped""" """setUpModule is always called, even if all tests in the module are skipped"""
import unittest import unittest

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Issue #7110""" """Issue #7110"""
import asyncio import asyncio
from typing import List from typing import List

View File

@ -11,8 +11,8 @@ import pytest
("a", 1), ("a", 1),
("1", 1), ("1", 1),
("א", 1), ("א", 1),
("\u200B", 0), ("\u200b", 0),
("\u1ABE", 0), ("\u1abe", 0),
("\u0591", 0), ("\u0591", 0),
("🉐", 2), ("🉐", 2),
("", 2), # noqa: RUF001 ("", 2), # noqa: RUF001

View File

@ -294,9 +294,9 @@ class TestReportSerialization:
reprec = pytester.inline_run() reprec = pytester.inline_run()
if report_class is TestReport: if report_class is TestReport:
reports: Union[ reports: Union[Sequence[TestReport], Sequence[CollectReport]] = (
Sequence[TestReport], Sequence[CollectReport] reprec.getreports("pytest_runtest_logreport")
] = reprec.getreports("pytest_runtest_logreport") )
# we have 3 reports: setup/call/teardown # we have 3 reports: setup/call/teardown
assert len(reports) == 3 assert len(reports) == 3
# get the call report # get the call report

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Test correct setup/teardowns at module, class, and instance level.""" """Test correct setup/teardowns at module, class, and instance level."""
from typing import List from typing import List
from _pytest.pytester import Pytester from _pytest.pytester import Pytester

View File

@ -1,5 +1,6 @@
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
"""Terminal reporting of the full testing process.""" """Terminal reporting of the full testing process."""
from io import StringIO from io import StringIO
import os import os
from pathlib import Path from pathlib import Path

View File

@ -4,6 +4,7 @@
This file is not executed, it is only checked by mypy to ensure that This file is not executed, it is only checked by mypy to ensure that
none of the code triggers any mypy errors. none of the code triggers any mypy errors.
""" """
import contextlib import contextlib
from typing import Optional from typing import Optional