Skip to content

Commit

Permalink
[pre-commit.ci] pre-commit autoupdate (pytest-dev#12115)
Browse files Browse the repository at this point in the history
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
Co-authored-by: Ran Benita <ran@unusedvar.com>
  • Loading branch information
3 people committed Mar 13, 2024
1 parent 1443778 commit c0532dd
Show file tree
Hide file tree
Showing 61 changed files with 185 additions and 212 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: "v0.2.2"
rev: "v0.3.2"
hooks:
- id: ruff
args: ["--fix"]
Expand All @@ -26,7 +26,7 @@ repos:
hooks:
- id: python-use-type-annotations
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.8.0
rev: v1.9.0
hooks:
- id: mypy
files: ^(src/|testing/|scripts/)
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Expand Up @@ -281,6 +281,7 @@ template = "changelog/_template.rst"
showcontent = true

[tool.mypy]
files = ["src", "testing", "scripts"]
mypy_path = ["src"]
check_untyped_defs = true
disallow_any_generics = true
Expand All @@ -293,3 +294,4 @@ warn_return_any = true
warn_unreachable = true
warn_unused_configs = true
no_implicit_reexport = true
warn_unused_ignores = true
1 change: 1 addition & 0 deletions scripts/generate-gh-release-notes.py
Expand Up @@ -8,6 +8,7 @@
Requires Python3.6+.
"""

from pathlib import Path
import re
import sys
Expand Down
1 change: 1 addition & 0 deletions scripts/prepare-release-pr.py
Expand Up @@ -13,6 +13,7 @@
**Token**: currently the token from the GitHub Actions is used, pushed with
`pytest bot <pytestbot@gmail.com>` commit author.
"""

import argparse
from pathlib import Path
import re
Expand Down
1 change: 1 addition & 0 deletions scripts/release.py
@@ -1,5 +1,6 @@
# mypy: disallow-untyped-defs
"""Invoke development tasks."""

import argparse
import os
from pathlib import Path
Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/__init__.py
Expand Up @@ -7,4 +7,4 @@
# broken installation, we don't even try
# unknown only works because we do poor mans version compare
__version__ = "unknown"
version_tuple = (0, 0, "unknown") # type:ignore[assignment]
version_tuple = (0, 0, "unknown")
28 changes: 13 additions & 15 deletions src/_pytest/_code/code.py
Expand Up @@ -279,9 +279,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 @@ -378,12 +378,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 @@ -1051,13 +1049,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 Expand Up @@ -1348,7 +1346,7 @@ def getfslineno(obj: object) -> Tuple[Union[str, Path], int]:
# in 6ec13a2b9. It ("place_as") appears to be something very custom.
obj = get_real_func(obj)
if hasattr(obj, "place_as"):
obj = obj.place_as # type: ignore[attr-defined]
obj = obj.place_as

try:
code = Code.from_function(obj)
Expand Down
6 changes: 2 additions & 4 deletions src/_pytest/_code/source.py
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
3 changes: 3 additions & 0 deletions src/_pytest/_io/terminalwriter.py
Expand Up @@ -9,6 +9,7 @@
from typing import Sequence
from typing import TextIO

from ..compat import assert_never
from .wcwidth import wcswidth


Expand Down Expand Up @@ -209,6 +210,8 @@ def _highlight(
from pygments.lexers.python import PythonLexer as Lexer
elif lexer == "diff":
from pygments.lexers.diff import DiffLexer as Lexer
else:
assert_never(lexer)
from pygments import highlight
import pygments.util
except ImportError:
Expand Down
37 changes: 12 additions & 25 deletions src/_pytest/_py/path.py
@@ -1,5 +1,6 @@
# mypy: allow-untyped-defs
"""local path implementation."""

from __future__ import annotations

import atexit
Expand Down Expand Up @@ -205,12 +206,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 All @@ -225,7 +224,7 @@ def owner(self):
raise NotImplementedError("XXX win32")
import pwd

entry = error.checked_call(pwd.getpwuid, self.uid) # type:ignore[attr-defined]
entry = error.checked_call(pwd.getpwuid, self.uid) # type:ignore[attr-defined,unused-ignore]
return entry[0]

@property
Expand All @@ -235,7 +234,7 @@ def group(self):
raise NotImplementedError("XXX win32")
import grp

entry = error.checked_call(grp.getgrgid, self.gid) # type:ignore[attr-defined]
entry = error.checked_call(grp.getgrgid, self.gid) # type:ignore[attr-defined,unused-ignore]
return entry[0]

def isdir(self):
Expand All @@ -253,15 +252,15 @@ def getuserid(user):
import pwd

if not isinstance(user, int):
user = pwd.getpwnam(user)[2] # type:ignore[attr-defined]
user = pwd.getpwnam(user)[2] # type:ignore[attr-defined,unused-ignore]
return user


def getgroupid(group):
import grp

if not isinstance(group, int):
group = grp.getgrnam(group)[2] # type:ignore[attr-defined]
group = grp.getgrnam(group)[2] # type:ignore[attr-defined,unused-ignore]
return group


Expand Down Expand Up @@ -318,7 +317,7 @@ def chown(self, user, group, rec=0):
def readlink(self) -> str:
"""Return value of a symbolic link."""
# https://github.com/python/mypy/issues/12278
return error.checked_call(os.readlink, self.strpath) # type: ignore[arg-type,return-value]
return error.checked_call(os.readlink, self.strpath) # type: ignore[arg-type,return-value,unused-ignore]

def mklinkto(self, oldname):
"""Posix style hard link to another name."""
Expand Down Expand Up @@ -757,15 +756,11 @@ def open(self, mode="r", ensure=False, encoding=None):
if ensure:
self.dirpath().ensure(dir=1)
if encoding:
# Using type ignore here because of this error:
# error: Argument 1 has incompatible type overloaded function;
# expected "Callable[[str, Any, Any], TextIOWrapper]" [arg-type]
# Which seems incorrect, given io.open supports the given argument types.
return error.checked_call(
io.open,
self.strpath,
mode,
encoding=encoding, # type:ignore[arg-type]
encoding=encoding,
)
return error.checked_call(open, self.strpath, mode)

Expand Down Expand Up @@ -966,12 +961,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 @@ -1277,13 +1270,7 @@ def mkdtemp(cls, rootdir=None):

if rootdir is None:
rootdir = cls.get_temproot()
# Using type ignore here because of this error:
# error: Argument 1 has incompatible type overloaded function; expected "Callable[[str], str]" [arg-type]
# Which seems incorrect, given tempfile.mkdtemp supports the given argument types.
path = error.checked_call(
tempfile.mkdtemp,
dir=str(rootdir), # type:ignore[arg-type]
)
path = error.checked_call(tempfile.mkdtemp, dir=str(rootdir))
return cls(path)

@classmethod
Expand Down
1 change: 1 addition & 0 deletions src/_pytest/assertion/__init__.py
@@ -1,5 +1,6 @@
# mypy: allow-untyped-defs
"""Support for presenting detailed information in failing assertions."""

import sys
from typing import Any
from typing import Generator
Expand Down
14 changes: 6 additions & 8 deletions src/_pytest/assertion/rewrite.py
Expand Up @@ -289,15 +289,13 @@ def get_data(self, pathname: Union[str, bytes]) -> bytes:
else:
from importlib.abc import TraversableResources

def get_resource_reader(self, name: str) -> TraversableResources: # type: ignore
def get_resource_reader(self, name: str) -> TraversableResources:
if sys.version_info < (3, 11):
from importlib.readers import FileReader
else:
from importlib.resources.readers import FileReader

return FileReader( # type:ignore[no-any-return]
types.SimpleNamespace(path=self._rewritten_names[name])
)
return FileReader(types.SimpleNamespace(path=self._rewritten_names[name]))


def _write_pyc_fp(
Expand Down Expand Up @@ -672,9 +670,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 @@ -975,7 +973,7 @@ def visit_NamedExpr(self, name: ast.NamedExpr) -> Tuple[ast.NamedExpr, str]:
# name if it's a local variable or _should_repr_global_name()
# thinks it's acceptable.
locs = ast.Call(self.builtin("locals"), [], [])
target_id = name.target.id # type: ignore[attr-defined]
target_id = name.target.id
inlocs = ast.Compare(ast.Constant(target_id), [ast.In()], [locs])
dorepr = self.helper("_should_repr_global_name", name)
test = ast.BoolOp(ast.Or(), [inlocs, dorepr])
Expand Down
6 changes: 3 additions & 3 deletions src/_pytest/assertion/util.py
@@ -1,5 +1,6 @@
# mypy: allow-untyped-defs
"""Utilities for assertion debugging."""

import collections.abc
import os
import pprint
Expand Down Expand Up @@ -222,10 +223,9 @@ def assertrepr_compare(
except outcomes.Exit:
raise
except Exception:
repr_crash = _pytest._code.ExceptionInfo.from_current()._getreprcrash()
explanation = [
"(pytest_assertion plugin: representation of details failed: {}.".format(
_pytest._code.ExceptionInfo.from_current()._getreprcrash()
),
f"(pytest_assertion plugin: representation of details failed: {repr_crash}.",
" Probably an object has a faulty __repr__.)",
]

Expand Down
3 changes: 2 additions & 1 deletion src/_pytest/cacheprovider.py
@@ -1,5 +1,6 @@
# mypy: allow-untyped-defs
"""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 @@ -432,7 +433,7 @@ def pytest_collection_modifyitems(
return res

def _get_increasing_order(self, items: Iterable[nodes.Item]) -> List[nodes.Item]:
return sorted(items, key=lambda item: item.path.stat().st_mtime, reverse=True) # type: ignore[no-any-return]
return sorted(items, key=lambda item: item.path.stat().st_mtime, reverse=True)

def pytest_sessionfinish(self) -> None:
config = self.config
Expand Down

0 comments on commit c0532dd

Please sign in to comment.