[8.0.x] Replace reorder-python-imports by isort due to black incompatibility (#11898)

Backport of #11896
This commit is contained in:
Bruno Oliveira 2024-01-31 09:08:36 -03:00 committed by GitHub
parent a76aa6ff80
commit 06e592370e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
84 changed files with 175 additions and 149 deletions

View File

@ -26,3 +26,6 @@ afc607cfd81458d4e4f3b1f3cf8cc931b933907e
# move argument parser to own file
c9df77cbd6a365dcb73c39618e4842711817e871
# Replace reorder-python-imports by isort due to black incompatibility (#11896)
8b54596639f41dfac070030ef20394b9001fe63c

View File

@ -1,6 +1,6 @@
repos:
- repo: https://github.com/psf/black
rev: 23.12.1
rev: 24.1.1
hooks:
- id: black
args: [--safe, --quiet]
@ -36,11 +36,12 @@ repos:
additional_dependencies:
- flake8-typing-imports==1.12.0
- flake8-docstrings==1.5.0
- repo: https://github.com/asottile/reorder-python-imports
rev: v3.12.0
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: reorder-python-imports
args: ['--application-directories=.:src', --py38-plus]
- id: isort
name: isort
args: [--force-single-line, --profile=black]
- repo: https://github.com/asottile/pyupgrade
rev: v3.15.0
hooks:

View File

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

View File

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

View File

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

View File

@ -19,7 +19,6 @@ from requests_cache import OriginalResponse
from requests_cache import SQLiteCache
from tqdm import tqdm
FILE_HEAD = r"""
.. 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"]
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
# broken installation, we don't even try
# 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
global argcomplete script).
"""
import argparse
import os
import sys

View File

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

View File

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

View File

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

View File

@ -1,7 +1,6 @@
from .terminalwriter import get_terminal_width
from .terminalwriter import TerminalWriter
__all__ = [
"TerminalWriter",
"get_terminal_width",

View File

@ -1,4 +1,5 @@
"""Helper functions for writing to terminals and files."""
import os
import shutil
import sys
@ -10,7 +11,6 @@ from typing import TextIO
from .wcwidth import wcswidth
# 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
elif lexer == "diff":
from pygments.lexers.diff import DiffLexer as Lexer
from pygments import highlight
import pygments.util
from pygments import highlight
except ImportError:
return source
else:

View File

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

View File

@ -1,4 +1,5 @@
"""local path implementation."""
from __future__ import annotations
import atexit
@ -203,12 +204,10 @@ class Stat:
if TYPE_CHECKING:
@property
def size(self) -> int:
...
def size(self) -> int: ...
@property
def mtime(self) -> float:
...
def mtime(self) -> float: ...
def __getattr__(self, name: str) -> Any:
return getattr(self._osstatresult, "st_" + name)
@ -961,12 +960,10 @@ class LocalPath:
return p
@overload
def stat(self, raising: Literal[True] = ...) -> Stat:
...
def stat(self, raising: Literal[True] = ...) -> Stat: ...
@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:
"""Return an os.stat() tuple."""
@ -1167,7 +1164,8 @@ class LocalPath:
where the 'self' path points to executable.
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("stderr", None)

View File

@ -1,4 +1,5 @@
"""Support for presenting detailed information in failing assertions."""
import sys
from typing import Any
from typing import Generator

View File

@ -1,4 +1,5 @@
"""Rewrite assertion AST to produce nice error messages."""
import ast
import errno
import functools
@ -33,15 +34,16 @@ from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE
from _pytest._io.saferepr import saferepr
from _pytest._version import version
from _pytest.assertion import util
from _pytest.assertion.util import ( # noqa: F401
format_explanation as _format_explanation,
)
from _pytest.config import Config
from _pytest.main import Session
from _pytest.pathlib import absolutepath
from _pytest.pathlib import fnmatch_ex
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:
from _pytest.assertion import AssertionState
@ -669,9 +671,9 @@ class AssertionRewriter(ast.NodeVisitor):
self.enable_assertion_pass_hook = False
self.source = source
self.scope: tuple[ast.AST, ...] = ()
self.variables_overwrite: defaultdict[
tuple[ast.AST, ...], Dict[str, str]
] = defaultdict(dict)
self.variables_overwrite: defaultdict[tuple[ast.AST, ...], Dict[str, str]] = (
defaultdict(dict)
)
def run(self, mod: ast.Module) -> None:
"""Find all assert statements in *mod* and rewrite them."""
@ -858,9 +860,10 @@ class AssertionRewriter(ast.NodeVisitor):
the expression is false.
"""
if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1:
from _pytest.warning_types import PytestAssertRewriteWarning
import warnings
from _pytest.warning_types import PytestAssertRewriteWarning
# TODO: This assert should not be needed.
assert self.module_path is not None
warnings.warn_explicit(

View File

@ -3,6 +3,7 @@
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.
"""
from typing import List
from typing import Optional
@ -10,7 +11,6 @@ from _pytest.assertion import util
from _pytest.config import Config
from _pytest.nodes import Item
DEFAULT_MAX_LINES = 8
DEFAULT_MAX_CHARS = 8 * 80
USAGE_MSG = "use '-vv' to show"

View File

@ -1,4 +1,5 @@
"""Utilities for assertion debugging."""
import collections.abc
import os
import pprint

View File

@ -1,4 +1,5 @@
"""Implementation of the cache provider."""
# This plugin was not named "cache" to avoid conflicts with the external
# pytest-cache version.
import dataclasses
@ -111,6 +112,7 @@ class Cache:
"""
check_ispytest(_ispytest)
import warnings
from _pytest.warning_types import PytestCacheWarning
warnings.warn(

View File

@ -1,4 +1,5 @@
"""Per-test stdout/stderr capturing mechanism."""
import abc
import collections
import contextlib

View File

@ -1,4 +1,5 @@
"""Python version compatibility code."""
from __future__ import annotations
import dataclasses
@ -18,7 +19,6 @@ from typing import TypeVar
import py
_T = TypeVar("_T")
_S = TypeVar("_S")

View File

@ -1,4 +1,5 @@
"""Command line options, ini-file and conftest.py processing."""
import argparse
import collections.abc
import copy
@ -68,9 +69,10 @@ from _pytest.warning_types import PytestConfigWarning
from _pytest.warning_types import warn_explicit_for
if TYPE_CHECKING:
from .argparsing import Argument
from .argparsing import Parser
from _pytest._code.code import _TracebackStyle
from _pytest.terminal import TerminalReporter
from .argparsing import Argument, Parser
_PluggyPlugin = object
@ -980,7 +982,8 @@ class Config:
*,
invocation_params: Optional[InvocationParams] = None,
) -> None:
from .argparsing import Parser, FILE_OR_DIR
from .argparsing import FILE_OR_DIR
from .argparsing import Parser
if invocation_params is None:
invocation_params = self.InvocationParams(
@ -1399,8 +1402,9 @@ class Config:
return
# Imported lazily to improve start-up time.
from packaging.requirements import InvalidRequirement
from packaging.requirements import Requirement
from packaging.version import Version
from packaging.requirements import InvalidRequirement, Requirement
plugin_info = self.pluginmanager.list_plugin_distinfo()
plugin_dist_info = {dist.project_name: dist.version for _, dist in plugin_info}

View File

@ -1,4 +1,5 @@
"""Interactive debugging with PDB, the Python Debugger."""
import argparse
import functools
import sys

View File

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

View File

@ -1,4 +1,5 @@
"""Discover and run doctests in modules and test files."""
import bdb
import functools
import inspect

View File

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

View File

@ -66,7 +66,6 @@ from _pytest.scope import _ScopeName
from _pytest.scope import HIGH_SCOPES
from _pytest.scope import Scope
if TYPE_CHECKING:
from typing import Deque
@ -1239,8 +1238,7 @@ def fixture(
Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]
] = ...,
name: Optional[str] = ...,
) -> FixtureFunction:
...
) -> FixtureFunction: ...
@overload
@ -1254,8 +1252,7 @@ def fixture( # noqa: F811
Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]
] = ...,
name: Optional[str] = None,
) -> FixtureFunctionMarker:
...
) -> FixtureFunctionMarker: ...
def fixture( # noqa: F811

View File

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

View File

@ -1,4 +1,5 @@
"""Version info, help messages, tracing configuration."""
import os
import sys
from argparse import Action

View File

@ -1,5 +1,6 @@
"""Hook specifications for pytest plugins which are invoked by pytest itself
and by builtin plugins."""
from pathlib import Path
from typing import Any
from typing import Dict
@ -20,12 +21,13 @@ if TYPE_CHECKING:
import warnings
from typing import Literal
from _pytest._code.code import ExceptionRepr
from _pytest._code.code import ExceptionInfo
from _pytest._code.code import ExceptionRepr
from _pytest.compat import LEGACY_PATH
from _pytest.config import _PluggyPlugin
from _pytest.config import Config
from _pytest.config import ExitCode
from _pytest.config import PytestPluginManager
from _pytest.config import _PluggyPlugin
from _pytest.config.argparsing import Parser
from _pytest.fixtures import FixtureDef
from _pytest.fixtures import SubRequest
@ -42,7 +44,6 @@ if TYPE_CHECKING:
from _pytest.runner import CallInfo
from _pytest.terminal import TerminalReporter
from _pytest.terminal import TestShortLogReport
from _pytest.compat import LEGACY_PATH
hookspec = HookspecMarker("pytest")

View File

@ -6,6 +6,7 @@ Based on initial code from Ross Lawley.
Output conforms to
https://github.com/jenkinsci/xunit-plugin/blob/master/src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd
"""
import functools
import os
import platform
@ -33,7 +34,6 @@ from _pytest.reports import TestReport
from _pytest.stash import StashKey
from _pytest.terminal import TerminalReporter
xml_key = StashKey["LogXML"]()

View File

@ -1,4 +1,5 @@
"""Add backward compatibility support for the legacy py path type."""
import dataclasses
import shlex
import subprocess

View File

@ -1,4 +1,5 @@
"""Access and control log capturing."""
import io
import logging
import os

View File

@ -1,4 +1,5 @@
"""Core implementation of the testing process: init, session, runtest loop."""
import argparse
import dataclasses
import fnmatch
@ -722,14 +723,12 @@ class Session(nodes.Collector):
@overload
def perform_collect(
self, args: Optional[Sequence[str]] = ..., genitems: "Literal[True]" = ...
) -> Sequence[nodes.Item]:
...
) -> Sequence[nodes.Item]: ...
@overload
def perform_collect( # noqa: F811
self, args: Optional[Sequence[str]] = ..., genitems: bool = ...
) -> Sequence[Union[nodes.Item, nodes.Collector]]:
...
) -> Sequence[Union[nodes.Item, nodes.Collector]]: ...
def perform_collect( # noqa: F811
self, args: Optional[Sequence[str]] = None, genitems: bool = True

View File

@ -1,4 +1,5 @@
"""Generic mechanism for marking and selecting python functions."""
import dataclasses
from typing import AbstractSet
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.
- or/and/not evaluate according to the usual boolean semantics.
"""
import ast
import dataclasses
import enum

View File

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

View File

@ -1,4 +1,5 @@
"""Monkeypatching and mocking functionality."""
import os
import re
import sys
@ -168,8 +169,7 @@ class MonkeyPatch:
name: object,
value: Notset = ...,
raising: bool = ...,
) -> None:
...
) -> None: ...
@overload
def setattr(
@ -178,8 +178,7 @@ class MonkeyPatch:
name: str,
value: object,
raising: bool = ...,
) -> None:
...
) -> None: ...
def setattr(
self,

View File

@ -45,8 +45,8 @@ from _pytest.warning_types import PytestWarning
if TYPE_CHECKING:
# Imported here due to circular import.
from _pytest.main import Session
from _pytest._code.code import _TracebackStyle
from _pytest.main import Session
SEP = "/"
@ -179,8 +179,8 @@ class Node(abc.ABC, metaclass=NodeMeta):
#: A ``LEGACY_PATH`` copy of the :attr:`path` attribute. Intended for usage
#: for methods not migrated to ``pathlib.Path`` yet, such as
#: :meth:`Item.reportinfo <pytest.Item.reportinfo>`. Will be deprecated in
#: a future release, prefer using :attr:`path` instead.
fspath: LEGACY_PATH
#: a future release, prefer using :attr:`path` instead.
# Use __slots__ to make attribute access faster.
# Note that __dict__ is still available.
@ -395,12 +395,10 @@ class Node(abc.ABC, metaclass=NodeMeta):
yield node, mark
@overload
def get_closest_marker(self, name: str) -> Optional[Mark]:
...
def get_closest_marker(self, name: str) -> Optional[Mark]: ...
@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(
self, name: str, default: Optional[Mark] = None

View File

@ -1,4 +1,5 @@
"""Run testsuites written for nose."""
import warnings
from _pytest.config import hookimpl

View File

@ -1,5 +1,6 @@
"""Exception classes and constants handling test outcomes as well as
functions creating them."""
import sys
import warnings
from typing import Any

View File

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

View File

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

View File

@ -1,4 +1,5 @@
"""Helper plugin for pytester; should not be loaded on its own."""
# This plugin contains assertions used by pytester. pytester cannot
# contain them itself, since it is imported by the `pytest` module,
# hence cannot be subject to assertion rewriting, which requires a

View File

@ -1,4 +1,5 @@
"""Python test discovery, setup and run of test functions."""
import abc
import dataclasses
import enum
@ -84,7 +85,6 @@ from _pytest.warning_types import PytestCollectionWarning
from _pytest.warning_types import PytestReturnNotNoneWarning
from _pytest.warning_types import PytestUnhandledCoroutineWarning
_PYTEST_DIR = Path(_pytest.__file__).parent
@ -1857,9 +1857,11 @@ class Function(PyobjMixin, nodes.Item):
if self.config.getoption("tbstyle", "auto") == "auto":
if len(ntraceback) > 2:
ntraceback = Traceback(
entry
if i == 0 or i == len(ntraceback) - 1
else entry.with_repr_style("short")
(
entry
if i == 0 or i == len(ntraceback) - 1
else entry.with_repr_style("short")
)
for i, entry in enumerate(ntraceback)
)

View File

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

View File

@ -1,4 +1,5 @@
"""Record warnings during test function execution."""
import re
import warnings
from pprint import pformat
@ -22,7 +23,6 @@ from _pytest.deprecated import WARNS_NONE_ARG
from _pytest.fixtures import fixture
from _pytest.outcomes import fail
T = TypeVar("T")
@ -42,15 +42,13 @@ def recwarn() -> Generator["WarningsRecorder", None, None]:
@overload
def deprecated_call(
*, match: Optional[Union[str, Pattern[str]]] = ...
) -> "WarningsRecorder":
...
) -> "WarningsRecorder": ...
@overload
def deprecated_call( # noqa: F811
func: Callable[..., T], *args: Any, **kwargs: Any
) -> T:
...
) -> T: ...
def deprecated_call( # noqa: F811
@ -92,8 +90,7 @@ def warns(
expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = ...,
*,
match: Optional[Union[str, Pattern[str]]] = ...,
) -> "WarningsChecker":
...
) -> "WarningsChecker": ...
@overload
@ -102,8 +99,7 @@ def warns( # noqa: F811
func: Callable[..., T],
*args: Any,
**kwargs: Any,
) -> T:
...
) -> T: ...
def warns( # noqa: F811

View File

@ -70,8 +70,7 @@ class BaseReport:
if TYPE_CHECKING:
# 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:
if hasattr(self, "node"):
@ -608,9 +607,9 @@ def _report_kwargs_from_json(reportdict: Dict[str, Any]) -> Dict[str, Any]:
description,
)
)
exception_info: Union[
ExceptionChainRepr, ReprExceptionInfo
] = ExceptionChainRepr(chain)
exception_info: Union[ExceptionChainRepr, ReprExceptionInfo] = (
ExceptionChainRepr(chain)
)
else:
exception_info = ReprExceptionInfo(
reprtraceback=reprtraceback,

View File

@ -1,4 +1,5 @@
"""Basic collect and runtest protocol implementations."""
import bdb
import dataclasses
import os

View File

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

View File

@ -1,4 +1,5 @@
"""Support for skip/xfail functions and markers."""
import dataclasses
import os
import platform

View File

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

View File

@ -2,6 +2,7 @@
This is a good source for looking at the various reporting hooks.
"""
import argparse
import dataclasses
import datetime

View File

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

View File

@ -1,4 +1,5 @@
"""Support for providing temporary directories to test functions."""
import dataclasses
import os
import re

View File

@ -1,4 +1,5 @@
"""Discover and run std-library "unittest" style tests."""
import sys
import traceback
import types
@ -33,6 +34,7 @@ from _pytest.scope import Scope
if TYPE_CHECKING:
import unittest
import twisted.trial.unittest
_SysExcInfoType = Union[
@ -412,8 +414,8 @@ def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:
def check_testcase_implements_trial_reporter(done: List[int] = []) -> None:
if done:
return
from zope.interface import classImplements
from twisted.trial.itrial import IReporter
from zope.interface import classImplements
classImplements(TestCaseFunction, IReporter)
done.append(1)

View File

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

View File

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

View File

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

View File

@ -1,4 +1,5 @@
"""Reproduces issue #3774"""
from unittest import mock
import pytest

View File

@ -1,4 +1,5 @@
"""Skipping an entire subclass with unittest.skip() should *not* call setUp from a base class."""
import unittest

View File

@ -1,4 +1,5 @@
"""Skipping an entire subclass with unittest.skip() should *not* call setUpClass from a base class."""
import unittest

View File

@ -1,4 +1,5 @@
"""setUpModule is always called, even if all tests in the module are skipped"""
import unittest

View File

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

View File

@ -1,10 +1,10 @@
"""Issue #7110"""
import asyncio
from typing import List
import asynctest
teardowns: List[None] = []

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1036,8 +1036,8 @@ class TestAssertionRewriteHookDetails:
assert pytester.runpytest().ret == 0
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.rewrite import _write_pyc
config = pytester.parseconfig()
state = AssertionState(config, "rewrite")
@ -1087,6 +1087,7 @@ class TestAssertionRewriteHookDetails:
an exception that is propagated to the caller.
"""
import py_compile
from _pytest.assertion.rewrite import _read_pyc
source = tmp_path / "source.py"

View File

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

View File

@ -8,7 +8,6 @@ from _pytest.debugging import _validate_usepdb_cls
from _pytest.monkeypatch import MonkeyPatch
from _pytest.pytester import Pytester
_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.
"""
import pytest
from _pytest.pytester import Pytester
TESTCASES = [
pytest.param(
"""

View File

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

View File

@ -942,7 +942,8 @@ def test_parameterset_for_parametrize_marks(
)
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)
result_mark = get_empty_parameterset_mark(config, ["a"], all)
@ -966,7 +967,8 @@ def test_parameterset_for_fail_at_collect(pytester: Pytester) -> None:
)
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)

View File

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

View File

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

View File

@ -1,4 +1,5 @@
"""Test correct setup/teardowns at module, class, and instance level."""
from typing import List
import pytest

View File

@ -1,4 +1,5 @@
"""Terminal reporting of the full testing process."""
import collections
import os
import sys

View File

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

View File

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