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

[pre-commit.ci] pre-commit autoupdate #12274

Merged
merged 4 commits into from
Apr 30, 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
2 changes: 2 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,5 @@ c9df77cbd6a365dcb73c39618e4842711817e871
4546d5445aaefe6a03957db028c263521dfb5c4b
# Migration to ruff / ruff format
4588653b2497ed25976b7aaff225b889fb476756
# Use format specifiers instead of percent format
4788165e69d08e10fc6b9c0124083fb358e2e9b0
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: "v0.4.1"
rev: "v0.4.2"
hooks:
- id: ruff
args: ["--fix"]
Expand All @@ -21,7 +21,7 @@ repos:
hooks:
- id: python-use-type-annotations
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.9.0
rev: v1.10.0
hooks:
- id: mypy
files: ^(src/|testing/|scripts/)
Expand Down
2 changes: 1 addition & 1 deletion bench/bench.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import pytest # noqa: F401

script = sys.argv[1:] if len(sys.argv) > 1 else ["empty.py"]
cProfile.run("pytest.cmdline.main(%r)" % script, "prof")
cProfile.run(f"pytest.cmdline.main({script!r})", "prof")
p = pstats.Stats("prof")
p.strip_dirs()
p.sort_stats("cumulative")
Expand Down
2 changes: 1 addition & 1 deletion doc/en/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@
html_title = "pytest documentation"

# A shorter title for the navigation bar. Default is the same as html_title.
html_short_title = "pytest-%s" % release
html_short_title = f"pytest-{release}"

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
Expand Down
4 changes: 2 additions & 2 deletions extra/get_issues.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def report(issues):
kind = _get_kind(issue)
status = issue["state"]
number = issue["number"]
link = "https://github.com/pytest-dev/pytest/issues/%s/" % number
link = f"https://github.com/pytest-dev/pytest/issues/{number}/"
print("----")
print(status, kind, link)
print(title)
Expand All @@ -69,7 +69,7 @@ def report(issues):
# print("\n".join(lines[:3]))
# if len(lines) > 3 or len(body) > 240:
# print("...")
print("\n\nFound %s open issues" % len(issues))
print(f"\n\nFound {len(issues)} open issues")


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/_code/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -940,7 +940,7 @@ def repr_traceback_entry(
s = self.get_source(source, line_index, excinfo, short=short)
lines.extend(s)
if short:
message = "in %s" % (entry.name)
message = f"in {entry.name}"
else:
message = excinfo and excinfo.typename or ""
entry_path = entry.path
Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/_io/pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,7 @@ def _safe_repr(
vrepr = self._safe_repr(v, context, maxlevels, level)
append(f"{krepr}: {vrepr}")
context.remove(objid)
return "{%s}" % ", ".join(components)
return "{{{}}}".format(", ".join(components))

if (issubclass(typ, list) and r is list.__repr__) or (
issubclass(typ, tuple) and r is tuple.__repr__
Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/_io/terminalwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def markup(self, text: str, **markup: bool) -> str:
if self.hasmarkup:
esc = [self._esctable[name] for name, on in markup.items() if on]
if esc:
text = "".join("\x1b[%sm" % cod for cod in esc) + text + "\x1b[0m"
text = "".join(f"\x1b[{cod}m" for cod in esc) + text + "\x1b[0m"
return text

def sep(
Expand Down
6 changes: 3 additions & 3 deletions src/_pytest/_py/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -659,7 +659,7 @@ def new(self, **kw):
)
if "basename" in kw:
if "purebasename" in kw or "ext" in kw:
raise ValueError("invalid specification %r" % kw)
raise ValueError(f"invalid specification {kw!r}")
else:
pb = kw.setdefault("purebasename", purebasename)
try:
Expand Down Expand Up @@ -705,7 +705,7 @@ def _getbyspec(self, spec: str) -> list[str]:
elif name == "ext":
res.append(ext)
else:
raise ValueError("invalid part specification %r" % name)
raise ValueError(f"invalid part specification {name!r}")
return res

def dirpath(self, *args, **kwargs):
Expand Down Expand Up @@ -1026,7 +1026,7 @@ def atime(self):
return self.stat().atime

def __repr__(self):
return "local(%r)" % self.strpath
return f"local({self.strpath!r})"

def __str__(self):
"""Return string representation of the Path."""
Expand Down
16 changes: 8 additions & 8 deletions src/_pytest/assertion/rewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def find_spec(
state = self.config.stash[assertstate_key]
if self._early_rewrite_bailout(name, state):
return None
state.trace("find_module called for: %s" % name)
state.trace(f"find_module called for: {name}")

# Type ignored because mypy is confused about the `self` binding here.
spec = self._find_spec(name, path) # type: ignore
Expand Down Expand Up @@ -273,7 +273,7 @@ def _warn_already_imported(self, name: str) -> None:

self.config.issue_config_time_warning(
PytestAssertRewriteWarning(
"Module already imported so cannot be rewritten: %s" % name
f"Module already imported so cannot be rewritten: {name}"
),
stacklevel=5,
)
Expand Down Expand Up @@ -374,29 +374,29 @@ def _read_pyc(
return None
# Check for invalid or out of date pyc file.
if len(data) != (16):
trace("_read_pyc(%s): invalid pyc (too short)" % source)
trace(f"_read_pyc({source}): invalid pyc (too short)")
return None
if data[:4] != importlib.util.MAGIC_NUMBER:
trace("_read_pyc(%s): invalid pyc (bad magic number)" % source)
trace(f"_read_pyc({source}): invalid pyc (bad magic number)")
return None
if data[4:8] != b"\x00\x00\x00\x00":
trace("_read_pyc(%s): invalid pyc (unsupported flags)" % source)
trace(f"_read_pyc({source}): invalid pyc (unsupported flags)")
return None
mtime_data = data[8:12]
if int.from_bytes(mtime_data, "little") != mtime & 0xFFFFFFFF:
trace("_read_pyc(%s): out of date" % source)
trace(f"_read_pyc({source}): out of date")
return None
size_data = data[12:16]
if int.from_bytes(size_data, "little") != size & 0xFFFFFFFF:
trace("_read_pyc(%s): invalid pyc (incorrect size)" % source)
trace(f"_read_pyc({source}): invalid pyc (incorrect size)")
return None
try:
co = marshal.load(fp)
except Exception as e:
trace(f"_read_pyc({source}): marshal.load error {e}")
return None
if not isinstance(co, types.CodeType):
trace("_read_pyc(%s): not a code object" % source)
trace(f"_read_pyc({source}): not a code object")
return None
return co

Expand Down
8 changes: 4 additions & 4 deletions src/_pytest/assertion/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ def _diff_text(left: str, right: str, verbose: int = 0) -> List[str]:
if i > 42:
i -= 10 # Provide some context
explanation = [
"Skipping %s identical leading characters in diff, use -v to show" % i
f"Skipping {i} identical leading characters in diff, use -v to show"
]
left = left[i:]
right = right[i:]
Expand Down Expand Up @@ -493,7 +493,7 @@ def _compare_eq_dict(
common = set_left.intersection(set_right)
same = {k: left[k] for k in common if left[k] == right[k]}
if same and verbose < 2:
explanation += ["Omitting %s identical items, use -vv to show" % len(same)]
explanation += [f"Omitting {len(same)} identical items, use -vv to show"]
elif same:
explanation += ["Common items:"]
explanation += highlighter(pprint.pformat(same)).splitlines()
Expand Down Expand Up @@ -560,7 +560,7 @@ def _compare_eq_cls(
if same or diff:
explanation += [""]
if same and verbose < 2:
explanation.append("Omitting %s identical items, use -vv to show" % len(same))
explanation.append(f"Omitting {len(same)} identical items, use -vv to show")
elif same:
explanation += ["Matching attributes:"]
explanation += highlighter(pprint.pformat(same)).splitlines()
Expand Down Expand Up @@ -590,7 +590,7 @@ def _notin_text(term: str, text: str, verbose: int = 0) -> List[str]:
tail = text[index + len(term) :]
correct_text = head + tail
diff = _diff_text(text, correct_text, verbose)
newdiff = ["%s is contained here:" % saferepr(term, maxsize=42)]
newdiff = [f"{saferepr(term, maxsize=42)} is contained here:"]
for line in diff:
if line.startswith("Skipping"):
continue
Expand Down
10 changes: 5 additions & 5 deletions src/_pytest/cacheprovider.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ def get_last_failed_paths(self) -> Set[Path]:

def pytest_report_collectionfinish(self) -> Optional[str]:
if self.active and self.config.getoption("verbose") >= 0:
return "run-last-failure: %s" % self._report_status
return f"run-last-failure: {self._report_status}"
return None

def pytest_runtest_logreport(self, report: TestReport) -> None:
Expand Down Expand Up @@ -588,21 +588,21 @@ def cacheshow(config: Config, session: Session) -> int:
dummy = object()
basedir = config.cache._cachedir
vdir = basedir / Cache._CACHE_PREFIX_VALUES
tw.sep("-", "cache values for %r" % glob)
tw.sep("-", f"cache values for {glob!r}")
for valpath in sorted(x for x in vdir.rglob(glob) if x.is_file()):
key = str(valpath.relative_to(vdir))
val = config.cache.get(key, dummy)
if val is dummy:
tw.line("%s contains unreadable content, will be ignored" % key)
tw.line(f"{key} contains unreadable content, will be ignored")
else:
tw.line("%s contains:" % key)
tw.line(f"{key} contains:")
for line in pformat(val).splitlines():
tw.line(" " + line)

ddir = basedir / Cache._CACHE_PREFIX_DIRS
if ddir.is_dir():
contents = sorted(ddir.rglob(glob))
tw.sep("-", "cache directories for %r" % glob)
tw.sep("-", f"cache directories for {glob!r}")
for p in contents:
# if p.is_dir():
# print("%s/" % p.relative_to(basedir))
Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -738,7 +738,7 @@ def is_capturing(self) -> Union[str, bool]:
if self.is_globally_capturing():
return "global"
if self._capture_fixture:
return "fixture %s" % self._capture_fixture.request.fixturename
return f"fixture {self._capture_fixture.request.fixturename}"
return False

# Global capturing control
Expand Down
15 changes: 7 additions & 8 deletions src/_pytest/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -798,7 +798,7 @@ def consider_pluginarg(self, arg: str) -> None:
if arg.startswith("no:"):
name = arg[3:]
if name in essential_plugins:
raise UsageError("plugin %s cannot be disabled" % name)
raise UsageError(f"plugin {name} cannot be disabled")

# PR #4304: remove stepwise if cacheprovider is blocked.
if name == "cacheprovider":
Expand Down Expand Up @@ -847,9 +847,9 @@ def import_plugin(self, modname: str, consider_entry_points: bool = False) -> No
# "terminal" or "capture". Those plugins are registered under their
# basename for historic purposes but must be imported with the
# _pytest prefix.
assert isinstance(modname, str), (
"module name as text required, got %r" % modname
)
assert isinstance(
modname, str
), f"module name as text required, got {modname!r}"
if self.is_blocked(modname) or self.get_plugin(modname) is not None:
return

Expand Down Expand Up @@ -892,8 +892,7 @@ def _get_plugin_specs_as_list(
if isinstance(specs, collections.abc.Sequence):
return list(specs)
raise UsageError(
"Plugins may be specified as a sequence or a ','-separated string of plugin names. Got: %r"
% specs
f"Plugins may be specified as a sequence or a ','-separated string of plugin names. Got: {specs!r}"
)


Expand Down Expand Up @@ -1185,7 +1184,7 @@ def notify_exception(
res = self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo)
if not any(res):
for line in str(excrepr).split("\n"):
sys.stderr.write("INTERNALERROR> %s\n" % line)
sys.stderr.write(f"INTERNALERROR> {line}\n")
sys.stderr.flush()

def cwd_relative_nodeid(self, nodeid: str) -> str:
Expand Down Expand Up @@ -1435,7 +1434,7 @@ def _checkversion(self) -> None:

if not isinstance(minver, str):
raise pytest.UsageError(
"%s: 'minversion' must be a single value" % self.inipath
f"{self.inipath}: 'minversion' must be a single value"
)

if Version(minver) > Version(pytest.__version__):
Expand Down
20 changes: 11 additions & 9 deletions src/_pytest/config/argparsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,23 +313,23 @@ def _set_opt_strings(self, opts: Sequence[str]) -> None:
for opt in opts:
if len(opt) < 2:
raise ArgumentError(
"invalid option string %r: "
"must be at least two characters long" % opt,
f"invalid option string {opt!r}: "
"must be at least two characters long",
self,
)
elif len(opt) == 2:
if not (opt[0] == "-" and opt[1] != "-"):
raise ArgumentError(
"invalid short option string %r: "
"must be of the form -x, (x any non-dash char)" % opt,
f"invalid short option string {opt!r}: "
"must be of the form -x, (x any non-dash char)",
self,
)
self._short_opts.append(opt)
else:
if not (opt[0:2] == "--" and opt[2] != "-"):
raise ArgumentError(
"invalid long option string %r: "
"must start with --, followed by non-dash" % opt,
f"invalid long option string {opt!r}: "
"must start with --, followed by non-dash",
self,
)
self._long_opts.append(opt)
Expand Down Expand Up @@ -383,7 +383,7 @@ def addoption(self, *opts: str, **attrs: Any) -> None:
name for opt in self.options for name in opt.names()
)
if conflict:
raise ValueError("option names %s already added" % conflict)
raise ValueError(f"option names {conflict} already added")
option = Argument(*opts, **attrs)
self._addoption_instance(option, shortupper=False)

Expand Down Expand Up @@ -441,7 +441,9 @@ def parse_args( # type: ignore
if unrecognized:
for arg in unrecognized:
if arg and arg[0] == "-":
lines = ["unrecognized arguments: %s" % (" ".join(unrecognized))]
lines = [
"unrecognized arguments: {}".format(" ".join(unrecognized))
]
for k, v in sorted(self.extra_info.items()):
lines.append(f" {k}: {v}")
self.error("\n".join(lines))
Expand Down Expand Up @@ -520,7 +522,7 @@ def _format_action_invocation(self, action: argparse.Action) -> str:
continue
if not option.startswith("--"):
raise ArgumentError(
'long optional argument without "--": [%s]' % (option), option
f'long optional argument without "--": [{option}]', option
)
xxoption = option[2:]
shortened = xxoption.replace("-", "")
Expand Down
3 changes: 1 addition & 2 deletions src/_pytest/debugging.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,7 @@ def do_continue(self, arg):
else:
tw.sep(
">",
"PDB continue (IO-capturing resumed for %s)"
% capturing,
f"PDB continue (IO-capturing resumed for {capturing})",
)
assert capman is not None
capman.resume()
Expand Down
6 changes: 3 additions & 3 deletions src/_pytest/doctest.py
Original file line number Diff line number Diff line change
Expand Up @@ -374,15 +374,15 @@ def repr_failure( # type: ignore[override]
).split("\n")
else:
inner_excinfo = ExceptionInfo.from_exc_info(failure.exc_info)
lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)]
lines += [f"UNEXPECTED EXCEPTION: {inner_excinfo.value!r}"]
lines += [
x.strip("\n") for x in traceback.format_exception(*failure.exc_info)
]
reprlocation_lines.append((reprlocation, lines))
return ReprFailDoctest(reprlocation_lines)

def reportinfo(self) -> Tuple[Union["os.PathLike[str]", str], Optional[int], str]:
return self.path, self.dtest.lineno, "[doctest] %s" % self.name
return self.path, self.dtest.lineno, f"[doctest] {self.name}"


def _get_flag_lookup() -> Dict[str, int]:
Expand Down Expand Up @@ -563,7 +563,7 @@ def _from_module(self, module, object):
module = self.obj
except Collector.CollectError:
if self.config.getvalue("doctest_ignore_import_errors"):
skip("unable to import module %r" % self.path)
skip(f"unable to import module {self.path!r}")
else:
raise

Expand Down