Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace reorder-python-imports by isort due to black incompatibility #11896

Merged
merged 3 commits into from
Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitblameignore → .git-blame-ignore-revs
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,6 @@ afc607cfd81458d4e4f3b1f3cf8cc931b933907e

# move argument parser to own file
c9df77cbd6a365dcb73c39618e4842711817e871

# Replace reorder-python-imports by isort due to black incompatibility (#11896)
8b54596639f41dfac070030ef20394b9001fe63c
11 changes: 6 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -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]
Expand Down Expand Up @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion bench/bench.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

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")
Expand Down
3 changes: 2 additions & 1 deletion doc/en/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,9 +440,10 @@

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.
Expand Down
2 changes: 1 addition & 1 deletion doc/en/example/multipython.py
Original file line number Diff line number Diff line change
@@ -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"]


Expand Down
1 change: 0 additions & 1 deletion scripts/update-plugin-list.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
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

Expand Down
3 changes: 2 additions & 1 deletion src/_pytest/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
1 change: 1 addition & 0 deletions src/_pytest/_argcomplete.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
which should throw a KeyError: 'COMPLINE' (which is properly set by the
global argcomplete script).
"""

import argparse
import os
import sys
Expand Down
1 change: 1 addition & 0 deletions src/_pytest/_code/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Python inspection/code generation API."""

from .code import Code
from .code import ExceptionInfo
from .code import filter_traceback
Expand Down
26 changes: 12 additions & 14 deletions src/_pytest/_code/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,9 +278,9 @@ def ishidden(self, excinfo: Optional["ExceptionInfo[BaseException]"]) -> bool:

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
Expand Down Expand Up @@ -377,12 +377,10 @@ def cut(
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]
Expand Down Expand Up @@ -1056,13 +1054,13 @@ def repr_excinfo(
# 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:
Expand Down
6 changes: 2 additions & 4 deletions src/_pytest/_code/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,10 @@ def __eq__(self, other: object) -> bool:
__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):
Expand Down
1 change: 0 additions & 1 deletion src/_pytest/_io/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from .terminalwriter import get_terminal_width
from .terminalwriter import TerminalWriter


__all__ = [
"TerminalWriter",
"get_terminal_width",
Expand Down
4 changes: 2 additions & 2 deletions src/_pytest/_io/terminalwriter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Helper functions for writing to terminals and files."""

import os
import shutil
import sys
Expand All @@ -10,7 +11,6 @@

from .wcwidth import wcswidth


# This code was initially copied from py 1.8.1, file _io/terminalwriter.py.


Expand Down Expand Up @@ -210,8 +210,8 @@ def _highlight(
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:
Expand Down
1 change: 1 addition & 0 deletions src/_pytest/_py/error.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""create errno-specific classes for IO or os calls."""

from __future__ import annotations

import errno
Expand Down
15 changes: 6 additions & 9 deletions src/_pytest/_py/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,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)
Expand Down Expand Up @@ -962,12 +960,10 @@ def ensure(self, *args, **kwargs):
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."""
Expand Down Expand Up @@ -1168,7 +1164,8 @@ def sysexec(self, *argv: os.PathLike[str], **popen_opts: Any) -> str:
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)
Expand Down
17 changes: 10 additions & 7 deletions src/_pytest/assertion/rewrite.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Rewrite assertion AST to produce nice error messages."""

import ast
import errno
import functools
Expand Down Expand Up @@ -33,15 +34,16 @@
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

Expand Down Expand Up @@ -669,9 +671,9 @@ def __init__(
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."""
Expand Down Expand Up @@ -858,9 +860,10 @@ def visit_Assert(self, assert_: ast.Assert) -> List[ast.stmt]:
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(
Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/assertion/truncate.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
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

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"
Expand Down
1 change: 1 addition & 0 deletions src/_pytest/cacheprovider.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ def warn(self, fmt: str, *, _ispytest: bool = False, **args: object) -> None:
"""
check_ispytest(_ispytest)
import warnings

from _pytest.warning_types import PytestCacheWarning

warnings.warn(
Expand Down
1 change: 0 additions & 1 deletion src/_pytest/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from typing import NoReturn
from typing import TypeVar


_T = TypeVar("_T")
_S = TypeVar("_S")

Expand Down
9 changes: 6 additions & 3 deletions src/_pytest/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,10 @@
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
Expand Down Expand Up @@ -973,7 +974,8 @@ def __init__(
*,
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(
Expand Down Expand Up @@ -1390,8 +1392,9 @@ def _validate_plugins(self) -> None:
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}
Expand Down
1 change: 1 addition & 0 deletions src/_pytest/deprecated.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
: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
Expand Down
1 change: 0 additions & 1 deletion src/_pytest/faulthandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
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]()

Expand Down