Run pre-commit on all files

Running pre-commit on all files after replacing reorder-python-imports by isort.
This commit is contained in:
Bruno Oliveira 2024-01-30 16:34:23 -03:00
parent 899a6cf2ce
commit 8b54596639
63 changed files with 133 additions and 142 deletions

View File

@ -2,9 +2,10 @@ import sys
if __name__ == "__main__": if __name__ == "__main__":
import cProfile import cProfile
import pytest # NOQA
import pstats import pstats
import pytest # NOQA
script = sys.argv[1:] if len(sys.argv) > 1 else ["empty.py"] script = sys.argv[1:] if len(sys.argv) > 1 else ["empty.py"]
cProfile.run("pytest.cmdline.main(%r)" % script, "prof") cProfile.run("pytest.cmdline.main(%r)" % script, "prof")
p = pstats.Stats("prof") p = pstats.Stats("prof")

View File

@ -440,9 +440,10 @@ intersphinx_mapping = {
def configure_logging(app: "sphinx.application.Sphinx") -> None: def configure_logging(app: "sphinx.application.Sphinx") -> None:
"""Configure Sphinx's WarningHandler to handle (expected) missing include.""" """Configure Sphinx's WarningHandler to handle (expected) missing include."""
import sphinx.util.logging
import logging import logging
import sphinx.util.logging
class WarnLogFilter(logging.Filter): class WarnLogFilter(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool: def filter(self, record: logging.LogRecord) -> bool:
"""Ignore warnings about missing include with "only" directive. """Ignore warnings about missing include with "only" directive.

View File

@ -1,12 +1,12 @@
"""Module containing a parametrized tests testing cross-python serialization """Module containing a parametrized tests testing cross-python serialization
via the pickle module.""" via the pickle module."""
import shutil import shutil
import subprocess import subprocess
import textwrap import textwrap
import pytest import pytest
pythonlist = ["python3.9", "python3.10", "python3.11"] pythonlist = ["python3.9", "python3.10", "python3.11"]

View File

@ -19,7 +19,6 @@ from requests_cache import OriginalResponse
from requests_cache import SQLiteCache from requests_cache import SQLiteCache
from tqdm import tqdm from tqdm import tqdm
FILE_HEAD = r""" FILE_HEAD = r"""
.. Note this file is autogenerated by scripts/update-plugin-list.py - usually weekly via github action .. Note this file is autogenerated by scripts/update-plugin-list.py - usually weekly via github action

View File

@ -1,7 +1,8 @@
__all__ = ["__version__", "version_tuple"] __all__ = ["__version__", "version_tuple"]
try: try:
from ._version import version as __version__, version_tuple from ._version import version as __version__
from ._version import version_tuple
except ImportError: # pragma: no cover except ImportError: # pragma: no cover
# broken installation, we don't even try # broken installation, we don't even try
# unknown only works because we do poor mans version compare # unknown only works because we do poor mans version compare

View File

@ -61,6 +61,7 @@ If things do not work right away:
which should throw a KeyError: 'COMPLINE' (which is properly set by the which should throw a KeyError: 'COMPLINE' (which is properly set by the
global argcomplete script). global argcomplete script).
""" """
import argparse import argparse
import os import os
import sys import sys

View File

@ -1,4 +1,5 @@
"""Python inspection/code generation API.""" """Python inspection/code generation API."""
from .code import Code from .code import Code
from .code import ExceptionInfo from .code import ExceptionInfo
from .code import filter_traceback from .code import filter_traceback

View File

@ -278,9 +278,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
@ -377,12 +377,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]
@ -1056,15 +1054,15 @@ 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:
reprtraceback = self.repr_traceback(excinfo_) reprtraceback = self.repr_traceback(excinfo_)
reprcrash = excinfo_._getreprcrash() reprcrash = excinfo_._getreprcrash()

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,7 +1,6 @@
from .terminalwriter import get_terminal_width from .terminalwriter import get_terminal_width
from .terminalwriter import TerminalWriter from .terminalwriter import TerminalWriter
__all__ = [ __all__ = [
"TerminalWriter", "TerminalWriter",
"get_terminal_width", "get_terminal_width",

View File

@ -1,4 +1,5 @@
"""Helper functions for writing to terminals and files.""" """Helper functions for writing to terminals and files."""
import os import os
import shutil import shutil
import sys import sys
@ -10,7 +11,6 @@ from typing import TextIO
from .wcwidth import wcswidth from .wcwidth import wcswidth
# This code was initially copied from py 1.8.1, file _io/terminalwriter.py. # This code was initially copied from py 1.8.1, file _io/terminalwriter.py.
@ -210,8 +210,8 @@ class TerminalWriter:
from pygments.lexers.python import PythonLexer as Lexer from pygments.lexers.python import PythonLexer as Lexer
elif lexer == "diff": elif lexer == "diff":
from pygments.lexers.diff import DiffLexer as Lexer from pygments.lexers.diff import DiffLexer as Lexer
from pygments import highlight
import pygments.util import pygments.util
from pygments import highlight
except ImportError: except ImportError:
return source return source
else: else:

View File

@ -1,4 +1,5 @@
"""create errno-specific classes for IO or os calls.""" """create errno-specific classes for IO or os calls."""
from __future__ import annotations from __future__ import annotations
import errno import errno

View File

@ -204,12 +204,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)
@ -962,12 +960,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."""
@ -1168,7 +1164,8 @@ class LocalPath:
where the 'self' path points to executable. where the 'self' path points to executable.
The process is directly invoked and not through a system shell. The process is directly invoked and not through a system shell.
""" """
from subprocess import Popen, PIPE from subprocess import PIPE
from subprocess import Popen
popen_opts.pop("stdout", None) popen_opts.pop("stdout", None)
popen_opts.pop("stderr", None) popen_opts.pop("stderr", None)

View File

@ -1,4 +1,5 @@
"""Rewrite assertion AST to produce nice error messages.""" """Rewrite assertion AST to produce nice error messages."""
import ast import ast
import errno import errno
import functools import functools
@ -33,15 +34,16 @@ from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE
from _pytest._io.saferepr import saferepr from _pytest._io.saferepr import saferepr
from _pytest._version import version from _pytest._version import version
from _pytest.assertion import util from _pytest.assertion import util
from _pytest.assertion.util import ( # noqa: F401
format_explanation as _format_explanation,
)
from _pytest.config import Config from _pytest.config import Config
from _pytest.main import Session from _pytest.main import Session
from _pytest.pathlib import absolutepath from _pytest.pathlib import absolutepath
from _pytest.pathlib import fnmatch_ex from _pytest.pathlib import fnmatch_ex
from _pytest.stash import StashKey from _pytest.stash import StashKey
# fmt: off
from _pytest.assertion.util import format_explanation as _format_explanation # noqa:F401, isort:skip
# fmt:on
if TYPE_CHECKING: if TYPE_CHECKING:
from _pytest.assertion import AssertionState from _pytest.assertion import AssertionState
@ -669,9 +671,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."""
@ -858,9 +860,10 @@ class AssertionRewriter(ast.NodeVisitor):
the expression is false. the expression is false.
""" """
if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1: if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1:
from _pytest.warning_types import PytestAssertRewriteWarning
import warnings import warnings
from _pytest.warning_types import PytestAssertRewriteWarning
# TODO: This assert should not be needed. # TODO: This assert should not be needed.
assert self.module_path is not None assert self.module_path is not None
warnings.warn_explicit( warnings.warn_explicit(

View File

@ -3,6 +3,7 @@
Current default behaviour is to truncate assertion explanations at Current default behaviour is to truncate assertion explanations at
terminal lines, unless running with an assertions verbosity level of at least 2 or running on CI. terminal lines, unless running with an assertions verbosity level of at least 2 or running on CI.
""" """
from typing import List from typing import List
from typing import Optional from typing import Optional
@ -10,7 +11,6 @@ from _pytest.assertion import util
from _pytest.config import Config from _pytest.config import Config
from _pytest.nodes import Item from _pytest.nodes import Item
DEFAULT_MAX_LINES = 8 DEFAULT_MAX_LINES = 8
DEFAULT_MAX_CHARS = 8 * 80 DEFAULT_MAX_CHARS = 8 * 80
USAGE_MSG = "use '-vv' to show" USAGE_MSG = "use '-vv' to show"

View File

@ -112,6 +112,7 @@ class Cache:
""" """
check_ispytest(_ispytest) check_ispytest(_ispytest)
import warnings import warnings
from _pytest.warning_types import PytestCacheWarning from _pytest.warning_types import PytestCacheWarning
warnings.warn( warnings.warn(

View File

@ -17,7 +17,6 @@ from typing import Final
from typing import NoReturn from typing import NoReturn
from typing import TypeVar from typing import TypeVar
_T = TypeVar("_T") _T = TypeVar("_T")
_S = TypeVar("_S") _S = TypeVar("_S")

View File

@ -66,9 +66,10 @@ from _pytest.warning_types import PytestConfigWarning
from _pytest.warning_types import warn_explicit_for from _pytest.warning_types import warn_explicit_for
if TYPE_CHECKING: if TYPE_CHECKING:
from .argparsing import Argument
from .argparsing import Parser
from _pytest._code.code import _TracebackStyle from _pytest._code.code import _TracebackStyle
from _pytest.terminal import TerminalReporter from _pytest.terminal import TerminalReporter
from .argparsing import Argument, Parser
_PluggyPlugin = object _PluggyPlugin = object
@ -973,7 +974,8 @@ class Config:
*, *,
invocation_params: Optional[InvocationParams] = None, invocation_params: Optional[InvocationParams] = None,
) -> None: ) -> None:
from .argparsing import Parser, FILE_OR_DIR from .argparsing import FILE_OR_DIR
from .argparsing import Parser
if invocation_params is None: if invocation_params is None:
invocation_params = self.InvocationParams( invocation_params = self.InvocationParams(
@ -1390,8 +1392,9 @@ class Config:
return return
# Imported lazily to improve start-up time. # Imported lazily to improve start-up time.
from packaging.requirements import InvalidRequirement
from packaging.requirements import Requirement
from packaging.version import Version from packaging.version import Version
from packaging.requirements import InvalidRequirement, Requirement
plugin_info = self.pluginmanager.list_plugin_distinfo() plugin_info = self.pluginmanager.list_plugin_distinfo()
plugin_dist_info = {dist.project_name: dist.version for _, dist in plugin_info} plugin_dist_info = {dist.project_name: dist.version for _, dist in plugin_info}

View File

@ -8,6 +8,7 @@ All constants defined in this module should be either instances of
:class:`PytestWarning`, or :class:`UnformattedWarning` :class:`PytestWarning`, or :class:`UnformattedWarning`
in case of warnings which need to format their messages. in case of warnings which need to format their messages.
""" """
from warnings import warn from warnings import warn
from _pytest.warning_types import PytestDeprecationWarning from _pytest.warning_types import PytestDeprecationWarning

View File

@ -8,7 +8,6 @@ from _pytest.config.argparsing import Parser
from _pytest.nodes import Item from _pytest.nodes import Item
from _pytest.stash import StashKey from _pytest.stash import StashKey
fault_handler_original_stderr_fd_key = StashKey[int]() fault_handler_original_stderr_fd_key = StashKey[int]()
fault_handler_stderr_fd_key = StashKey[int]() fault_handler_stderr_fd_key = StashKey[int]()

View File

@ -67,7 +67,6 @@ from _pytest.scope import _ScopeName
from _pytest.scope import HIGH_SCOPES from _pytest.scope import HIGH_SCOPES
from _pytest.scope import Scope from _pytest.scope import Scope
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Deque from typing import Deque
@ -1231,8 +1230,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
@ -1246,8 +1244,7 @@ def fixture( # noqa: F811
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( # noqa: F811 def fixture( # noqa: F811

View File

@ -1,5 +1,6 @@
"""Provides a function to report all internal modules for using freezing """Provides a function to report all internal modules for using freezing
tools.""" tools."""
import types import types
from typing import Iterator from typing import Iterator
from typing import List from typing import List

View File

@ -19,12 +19,12 @@ if TYPE_CHECKING:
import warnings import warnings
from typing import Literal from typing import Literal
from _pytest._code.code import ExceptionRepr
from _pytest._code.code import ExceptionInfo from _pytest._code.code import ExceptionInfo
from _pytest._code.code import ExceptionRepr
from _pytest.config import _PluggyPlugin
from _pytest.config import Config from _pytest.config import Config
from _pytest.config import ExitCode from _pytest.config import ExitCode
from _pytest.config import PytestPluginManager from _pytest.config import PytestPluginManager
from _pytest.config import _PluggyPlugin
from _pytest.config.argparsing import Parser from _pytest.config.argparsing import Parser
from _pytest.fixtures import FixtureDef from _pytest.fixtures import FixtureDef
from _pytest.fixtures import SubRequest from _pytest.fixtures import SubRequest

View File

@ -34,7 +34,6 @@ from _pytest.reports import TestReport
from _pytest.stash import StashKey from _pytest.stash import StashKey
from _pytest.terminal import TerminalReporter from _pytest.terminal import TerminalReporter
xml_key = StashKey["LogXML"]() xml_key = StashKey["LogXML"]()

View File

@ -15,6 +15,7 @@ from typing import Union
from iniconfig import SectionWrapper from iniconfig import SectionWrapper
import py import py
from _pytest.cacheprovider import Cache from _pytest.cacheprovider import Cache
from _pytest.config import Config from _pytest.config import Config
from _pytest.config import hookimpl from _pytest.config import hookimpl

View File

@ -1,4 +1,5 @@
"""Core implementation of the testing process: init, session, runtest loop.""" """Core implementation of the testing process: init, session, runtest loop."""
import argparse import argparse
import dataclasses import dataclasses
import fnmatch import fnmatch
@ -721,14 +722,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( # noqa: F811 def perform_collect( # noqa: F811
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( # noqa: F811 def perform_collect( # noqa: F811
self, args: Optional[Sequence[str]] = None, genitems: bool = True self, args: Optional[Sequence[str]] = None, genitems: bool = True

View File

@ -1,4 +1,5 @@
"""Generic mechanism for marking and selecting python functions.""" """Generic mechanism for marking and selecting python functions."""
import dataclasses import dataclasses
from typing import AbstractSet from typing import AbstractSet
from typing import Collection from typing import Collection

View File

@ -14,6 +14,7 @@ The semantics are:
- ident evaluates to True of False according to a provided matcher function. - ident evaluates to True of False according to a provided matcher function.
- or/and/not evaluate according to the usual boolean semantics. - or/and/not evaluate according to the usual boolean semantics.
""" """
import ast import ast
import dataclasses import dataclasses
import enum import enum

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

@ -169,8 +169,7 @@ class MonkeyPatch:
name: object, name: object,
value: Notset = ..., value: Notset = ...,
raising: bool = ..., raising: bool = ...,
) -> None: ) -> None: ...
...
@overload @overload
def setattr( def setattr(
@ -179,8 +178,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

@ -41,8 +41,8 @@ from _pytest.warning_types import PytestWarning
if TYPE_CHECKING: if TYPE_CHECKING:
# Imported here due to circular import. # Imported here due to circular import.
from _pytest.main import Session
from _pytest._code.code import _TracebackStyle from _pytest._code.code import _TracebackStyle
from _pytest.main import Session
SEP = "/" SEP = "/"
@ -104,6 +104,7 @@ class Node(abc.ABC, metaclass=NodeMeta):
``Collector``\'s are the internal nodes of the tree, and ``Item``\'s are the ``Collector``\'s are the internal nodes of the tree, and ``Item``\'s are the
leaf nodes. leaf nodes.
""" """
# Use __slots__ to make attribute access faster. # Use __slots__ to make attribute access faster.
# Note that __dict__ is still available. # Note that __dict__ is still available.
__slots__ = ( __slots__ = (
@ -325,12 +326,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 @@
"""Exception classes and constants handling test outcomes as well as """Exception classes and constants handling test outcomes as well as
functions creating them.""" functions creating them."""
import sys import sys
from typing import Any from typing import Any
from typing import Callable from typing import Callable

View File

@ -12,7 +12,6 @@ from _pytest.config.argparsing import Parser
from _pytest.stash import StashKey from _pytest.stash import StashKey
from _pytest.terminal import TerminalReporter from _pytest.terminal import TerminalReporter
pastebinfile_key = StashKey[IO[bytes]]() pastebinfile_key = StashKey[IO[bytes]]()
@ -74,8 +73,8 @@ def create_new_paste(contents: Union[str, bytes]) -> str:
:returns: URL to the pasted contents, or an error message. :returns: URL to the pasted contents, or an error message.
""" """
import re import re
from urllib.request import urlopen
from urllib.parse import urlencode from urllib.parse import urlencode
from urllib.request import urlopen
params = {"code": contents, "lexer": "text", "expiry": "1week"} params = {"code": contents, "lexer": "text", "expiry": "1week"}
url = "https://bpa.st" url = "https://bpa.st"

View File

@ -244,8 +244,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
@ -326,15 +325,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(
@ -343,8 +340,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,
@ -391,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(
@ -408,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,4 +1,5 @@
"""Helper plugin for pytester; should not be loaded on its own.""" """Helper plugin for pytester; should not be loaded on its own."""
# This plugin contains assertions used by pytester. pytester cannot # This plugin contains assertions used by pytester. pytester cannot
# contain them itself, since it is imported by the `pytest` module, # contain them itself, since it is imported by the `pytest` module,
# hence cannot be subject to assertion rewriting, which requires a # hence cannot be subject to assertion rewriting, which requires a

View File

@ -81,7 +81,6 @@ from _pytest.warning_types import PytestCollectionWarning
from _pytest.warning_types import PytestReturnNotNoneWarning from _pytest.warning_types import PytestReturnNotNoneWarning
from _pytest.warning_types import PytestUnhandledCoroutineWarning from _pytest.warning_types import PytestUnhandledCoroutineWarning
_PYTEST_DIR = Path(_pytest.__file__).parent _PYTEST_DIR = Path(_pytest.__file__).parent
@ -1793,9 +1792,11 @@ class Function(PyobjMixin, nodes.Item):
if self.config.getoption("tbstyle", "auto") == "auto": if self.config.getoption("tbstyle", "auto") == "auto":
if len(ntraceback) > 2: if len(ntraceback) > 2:
ntraceback = Traceback( ntraceback = Traceback(
(
entry entry
if i == 0 or i == len(ntraceback) - 1 if i == 0 or i == len(ntraceback) - 1
else entry.with_repr_style("short") else entry.with_repr_style("short")
)
for i, entry in enumerate(ntraceback) for i, entry in enumerate(ntraceback)
) )

View File

@ -779,8 +779,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
@ -789,8 +788,7 @@ def raises( # noqa: F811
func: Callable[..., Any], func: Callable[..., Any],
*args: Any, *args: Any,
**kwargs: Any, **kwargs: Any,
) -> _pytest._code.ExceptionInfo[E]: ) -> _pytest._code.ExceptionInfo[E]: ...
...
def raises( # noqa: F811 def raises( # noqa: F811

View File

@ -22,7 +22,6 @@ from _pytest.deprecated import check_ispytest
from _pytest.fixtures import fixture from _pytest.fixtures import fixture
from _pytest.outcomes import fail from _pytest.outcomes import fail
T = TypeVar("T") T = TypeVar("T")
@ -42,15 +41,13 @@ 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( # noqa: F811 def deprecated_call( # noqa: F811
func: Callable[..., T], *args: Any, **kwargs: Any func: Callable[..., T], *args: Any, **kwargs: Any
) -> T: ) -> T: ...
...
def deprecated_call( # noqa: F811 def deprecated_call( # noqa: F811
@ -92,8 +89,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
@ -102,8 +98,7 @@ def warns( # noqa: F811
func: Callable[..., T], func: Callable[..., T],
*args: Any, *args: Any,
**kwargs: Any, **kwargs: Any,
) -> T: ) -> T: ...
...
def warns( # noqa: F811 def warns( # noqa: F811

View File

@ -71,8 +71,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"):
@ -609,9 +608,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

@ -7,12 +7,12 @@ would cause circular references.
Also this makes the module light to import, as it should. Also this makes the module light to import, as it should.
""" """
from enum import Enum from enum import Enum
from functools import total_ordering from functools import total_ordering
from typing import Literal from typing import Literal
from typing import Optional from typing import Optional
_ScopeName = Literal["session", "package", "module", "class", "function"] _ScopeName = Literal["session", "package", "module", "class", "function"]

View File

@ -5,7 +5,6 @@ from typing import Generic
from typing import TypeVar from typing import TypeVar
from typing import Union from typing import Union
__all__ = ["Stash", "StashKey"] __all__ = ["Stash", "StashKey"]

View File

@ -5,6 +5,7 @@ pytest runtime information (issue #185).
Fixture "mock_timing" also interacts with this module for pytest's own tests. Fixture "mock_timing" also interacts with this module for pytest's own tests.
""" """
from time import perf_counter from time import perf_counter
from time import sleep from time import sleep
from time import time from time import time

View File

@ -33,6 +33,7 @@ from _pytest.runner import CallInfo
if TYPE_CHECKING: if TYPE_CHECKING:
import unittest import unittest
import twisted.trial.unittest import twisted.trial.unittest
_SysExcInfoType = Union[ _SysExcInfoType = Union[
@ -397,8 +398,8 @@ def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:
def check_testcase_implements_trial_reporter(done: List[int] = []) -> None: def check_testcase_implements_trial_reporter(done: List[int] = []) -> None:
if done: if done:
return return
from zope.interface import classImplements
from twisted.trial.itrial import IReporter from twisted.trial.itrial import IReporter
from zope.interface import classImplements
classImplements(TestCaseFunction, IReporter) classImplements(TestCaseFunction, IReporter)
done.append(1) done.append(1)

View File

@ -1,4 +1,5 @@
"""The pytest entry point.""" """The pytest entry point."""
import pytest import pytest
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -7,10 +7,11 @@ import time
import warnings import warnings
from unittest import mock from unittest import mock
import pytest
from py import error from py import error
from py.path import local from py.path import local
import pytest
@contextlib.contextmanager @contextlib.contextmanager
def ignore_encoding_warning(): def ignore_encoding_warning():
@ -1367,8 +1368,8 @@ class TestPOSIXLocalPath:
assert realpath.basename == "file" assert realpath.basename == "file"
def test_owner(self, path1, tmpdir): def test_owner(self, path1, tmpdir):
from pwd import getpwuid # type:ignore[attr-defined]
from grp import getgrgid # type:ignore[attr-defined] from grp import getgrgid # type:ignore[attr-defined]
from pwd import getpwuid # type:ignore[attr-defined]
stat = path1.stat() stat = path1.stat()
assert stat.path == path1 assert stat.path == path1

View File

@ -24,7 +24,6 @@ from _pytest.pathlib import import_path
from _pytest.pytester import LineMatcher from _pytest.pytester import LineMatcher
from _pytest.pytester import Pytester from _pytest.pytester import Pytester
if TYPE_CHECKING: if TYPE_CHECKING:
from _pytest._code.code import _TracebackStyle from _pytest._code.code import _TracebackStyle

View File

@ -2,7 +2,6 @@
from typing import List from typing import List
from unittest import IsolatedAsyncioTestCase from unittest import IsolatedAsyncioTestCase
teardowns: List[None] = [] teardowns: List[None] = []

View File

@ -5,7 +5,6 @@ from typing import List
import asynctest import asynctest
teardowns: List[None] = [] teardowns: List[None] = []

View File

@ -1,8 +1,10 @@
"""Generate an executable with pytest runner embedded using PyInstaller.""" """Generate an executable with pytest runner embedded using PyInstaller."""
if __name__ == "__main__": if __name__ == "__main__":
import pytest
import subprocess import subprocess
import pytest
hidden = [] hidden = []
for x in pytest.freeze_includes(): for x in pytest.freeze_includes():
hidden.extend(["--hidden-import", x]) hidden.extend(["--hidden-import", x])

View File

@ -5,6 +5,7 @@ pytest main().
if __name__ == "__main__": if __name__ == "__main__":
import sys import sys
import pytest import pytest
sys.exit(pytest.main()) sys.exit(pytest.main())

View File

@ -2,6 +2,7 @@
Called by tox.ini: uses the generated executable to run the tests in ./tests/ Called by tox.ini: uses the generated executable to run the tests in ./tests/
directory. directory.
""" """
if __name__ == "__main__": if __name__ == "__main__":
import os import os
import sys import sys

View File

@ -13,7 +13,6 @@ import pytest
from _pytest._io import terminalwriter from _pytest._io import terminalwriter
from _pytest.monkeypatch import MonkeyPatch from _pytest.monkeypatch import MonkeyPatch
# These tests were initially copied from py 1.8.1. # These tests were initially copied from py 1.8.1.

View File

@ -831,9 +831,10 @@ def test_live_logging_suspends_capture(
We parametrize the test to also make sure _LiveLoggingStreamHandler works correctly if no capture manager plugin We parametrize the test to also make sure _LiveLoggingStreamHandler works correctly if no capture manager plugin
is installed. is installed.
""" """
import logging
import contextlib import contextlib
import logging
from functools import partial from functools import partial
from _pytest.logging import _LiveLoggingStreamHandler from _pytest.logging import _LiveLoggingStreamHandler
class MockCaptureManager: class MockCaptureManager:

View File

@ -43,9 +43,10 @@ class TestMockDecoration:
assert values == ("x",) assert values == ("x",)
def test_getfuncargnames_patching(self): def test_getfuncargnames_patching(self):
from _pytest.compat import getfuncargnames
from unittest.mock import patch from unittest.mock import patch
from _pytest.compat import getfuncargnames
class T: class T:
def original(self, x, y, z): def original(self, x, y, z):
pass pass

View File

@ -1037,8 +1037,8 @@ class TestAssertionRewriteHookDetails:
assert pytester.runpytest().ret == 0 assert pytester.runpytest().ret == 0
def test_write_pyc(self, pytester: Pytester, tmp_path) -> None: def test_write_pyc(self, pytester: Pytester, tmp_path) -> None:
from _pytest.assertion.rewrite import _write_pyc
from _pytest.assertion import AssertionState from _pytest.assertion import AssertionState
from _pytest.assertion.rewrite import _write_pyc
config = pytester.parseconfig() config = pytester.parseconfig()
state = AssertionState(config, "rewrite") state = AssertionState(config, "rewrite")
@ -1088,6 +1088,7 @@ class TestAssertionRewriteHookDetails:
an exception that is propagated to the caller. an exception that is propagated to the caller.
""" """
import py_compile import py_compile
from _pytest.assertion.rewrite import _read_pyc from _pytest.assertion.rewrite import _read_pyc
source = tmp_path / "source.py" source = tmp_path / "source.py"

View File

@ -2109,9 +2109,9 @@ class TestPytestPluginsVariable:
args = ("--pyargs", "pkg") if use_pyargs else () args = ("--pyargs", "pkg") if use_pyargs else ()
res = pytester.runpytest(*args) res = pytester.runpytest(*args)
assert res.ret == (0 if use_pyargs else 2) assert res.ret == (0 if use_pyargs else 2)
msg = ( msg = msg = (
msg "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported"
) = "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported" )
if use_pyargs: if use_pyargs:
assert msg not in res.stdout.str() assert msg not in res.stdout.str()
else: else:

View File

@ -9,7 +9,6 @@ from _pytest.debugging import _validate_usepdb_cls
from _pytest.monkeypatch import MonkeyPatch from _pytest.monkeypatch import MonkeyPatch
from _pytest.pytester import Pytester from _pytest.pytester import Pytester
_ENVIRON_PYTHONBREAKPOINT = os.environ.get("PYTHONBREAKPOINT", "") _ENVIRON_PYTHONBREAKPOINT = os.environ.get("PYTHONBREAKPOINT", "")

View File

@ -4,10 +4,10 @@ Tests and examples for correct "+/-" usage in error diffs.
See https://github.com/pytest-dev/pytest/issues/3333 for details. See https://github.com/pytest-dev/pytest/issues/3333 for details.
""" """
import pytest import pytest
from _pytest.pytester import Pytester from _pytest.pytester import Pytester
TESTCASES = [ TESTCASES = [
pytest.param( pytest.param(
""" """

View File

@ -114,6 +114,7 @@ def test_cancel_timeout_on_hook(monkeypatch, hook_name) -> None:
to timeout before entering pdb (pytest-dev/pytest-faulthandler#12) or any to timeout before entering pdb (pytest-dev/pytest-faulthandler#12) or any
other interactive exception (pytest-dev/pytest-faulthandler#14).""" other interactive exception (pytest-dev/pytest-faulthandler#14)."""
import faulthandler import faulthandler
from _pytest import faulthandler as faulthandler_plugin from _pytest import faulthandler as faulthandler_plugin
called = [] called = []

View File

@ -943,7 +943,8 @@ def test_parameterset_for_parametrize_marks(
) )
config = pytester.parseconfig() config = pytester.parseconfig()
from _pytest.mark import pytest_configure, get_empty_parameterset_mark from _pytest.mark import get_empty_parameterset_mark
from _pytest.mark import pytest_configure
pytest_configure(config) pytest_configure(config)
result_mark = get_empty_parameterset_mark(config, ["a"], all) result_mark = get_empty_parameterset_mark(config, ["a"], all)
@ -967,7 +968,8 @@ def test_parameterset_for_fail_at_collect(pytester: Pytester) -> None:
) )
config = pytester.parseconfig() config = pytester.parseconfig()
from _pytest.mark import pytest_configure, get_empty_parameterset_mark from _pytest.mark import get_empty_parameterset_mark
from _pytest.mark import pytest_configure
pytest_configure(config) pytest_configure(config)

View File

@ -3,6 +3,7 @@
This ensures all internal packages can be imported without needing the pytest This ensures all internal packages can be imported without needing the pytest
namespace being set, which is critical for the initialization of xdist. namespace being set, which is critical for the initialization of xdist.
""" """
import pkgutil import pkgutil
import subprocess import subprocess
import sys import sys

View File

@ -296,9 +296,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

@ -200,6 +200,8 @@ extend-ignore =
D302 D302
; Docstring Content Issues ; Docstring Content Issues
D400,D401,D401,D402,D405,D406,D407,D408,D409,D410,D411,D412,D413,D414,D415,D416,D417 D400,D401,D401,D402,D405,D406,D407,D408,D409,D410,D411,D412,D413,D414,D415,D416,D417
; Unused imports
F401
[isort] [isort]