Skip to content

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

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

Merged
merged 1 commit 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
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 @@ -441,9 +441,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 @@ -277,9 +277,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 @@ -376,12 +376,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 @@ -1055,13 +1053,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 @@ -46,12 +46,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
16 changes: 7 additions & 9 deletions src/_pytest/_py/path.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""local path implementation."""

from __future__ import annotations

import atexit
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -961,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 @@ -1167,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
1 change: 1 addition & 0 deletions src/_pytest/assertion/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Support for presenting detailed information in failing assertions."""

import sys
from typing import Any
from typing import Generator
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/assertion/util.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Utilities for assertion debugging."""

import collections.abc
import os
import pprint
Expand Down
2 changes: 2 additions & 0 deletions src/_pytest/cacheprovider.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -111,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: 1 addition & 0 deletions src/_pytest/capture.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Per-test stdout/stderr capturing mechanism."""

import abc
import collections
import contextlib
Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/compat.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Python version compatibility code."""

from __future__ import annotations

import dataclasses
Expand All @@ -18,7 +19,6 @@

import py


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

Expand Down
Loading