Skip to content

Commit 4788165

Browse files
[ruff UP031] Fix to use format specifiers instead of percent format
1 parent da53e29 commit 4788165

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

52 files changed

+202
-212
lines changed

bench/bench.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import pytest # noqa: F401
99

1010
script = sys.argv[1:] if len(sys.argv) > 1 else ["empty.py"]
11-
cProfile.run("pytest.cmdline.main(%r)" % script, "prof")
11+
cProfile.run(f"pytest.cmdline.main({script!r})", "prof")
1212
p = pstats.Stats("prof")
1313
p.strip_dirs()
1414
p.sort_stats("cumulative")

doc/en/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@
236236
html_title = "pytest documentation"
237237

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

241241
# The name of an image file (relative to this directory) to place at the top
242242
# of the sidebar.

extra/get_issues.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def report(issues):
6060
kind = _get_kind(issue)
6161
status = issue["state"]
6262
number = issue["number"]
63-
link = "https://github.com/pytest-dev/pytest/issues/%s/" % number
63+
link = f"https://github.com/pytest-dev/pytest/issues/{number}/"
6464
print("----")
6565
print(status, kind, link)
6666
print(title)
@@ -69,7 +69,7 @@ def report(issues):
6969
# print("\n".join(lines[:3]))
7070
# if len(lines) > 3 or len(body) > 240:
7171
# print("...")
72-
print("\n\nFound %s open issues" % len(issues))
72+
print(f"\n\nFound {len(issues)} open issues")
7373

7474

7575
if __name__ == "__main__":

src/_pytest/_code/code.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -940,7 +940,7 @@ def repr_traceback_entry(
940940
s = self.get_source(source, line_index, excinfo, short=short)
941941
lines.extend(s)
942942
if short:
943-
message = "in %s" % (entry.name)
943+
message = f"in {entry.name}"
944944
else:
945945
message = excinfo and excinfo.typename or ""
946946
entry_path = entry.path

src/_pytest/_io/pprint.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -616,7 +616,7 @@ def _safe_repr(
616616
vrepr = self._safe_repr(v, context, maxlevels, level)
617617
append(f"{krepr}: {vrepr}")
618618
context.remove(objid)
619-
return "{%s}" % ", ".join(components)
619+
return "{{{}}}".format(", ".join(components))
620620

621621
if (issubclass(typ, list) and r is list.__repr__) or (
622622
issubclass(typ, tuple) and r is tuple.__repr__

src/_pytest/_io/terminalwriter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ def markup(self, text: str, **markup: bool) -> str:
104104
if self.hasmarkup:
105105
esc = [self._esctable[name] for name, on in markup.items() if on]
106106
if esc:
107-
text = "".join("\x1b[%sm" % cod for cod in esc) + text + "\x1b[0m"
107+
text = "".join(f"\x1b[{cod}m" for cod in esc) + text + "\x1b[0m"
108108
return text
109109

110110
def sep(

src/_pytest/_py/path.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -659,7 +659,7 @@ def new(self, **kw):
659659
)
660660
if "basename" in kw:
661661
if "purebasename" in kw or "ext" in kw:
662-
raise ValueError("invalid specification %r" % kw)
662+
raise ValueError(f"invalid specification {kw!r}")
663663
else:
664664
pb = kw.setdefault("purebasename", purebasename)
665665
try:
@@ -705,7 +705,7 @@ def _getbyspec(self, spec: str) -> list[str]:
705705
elif name == "ext":
706706
res.append(ext)
707707
else:
708-
raise ValueError("invalid part specification %r" % name)
708+
raise ValueError(f"invalid part specification {name!r}")
709709
return res
710710

711711
def dirpath(self, *args, **kwargs):
@@ -1026,7 +1026,7 @@ def atime(self):
10261026
return self.stat().atime
10271027

10281028
def __repr__(self):
1029-
return "local(%r)" % self.strpath
1029+
return f"local({self.strpath!r})"
10301030

10311031
def __str__(self):
10321032
"""Return string representation of the Path."""

src/_pytest/assertion/rewrite.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def find_spec(
101101
state = self.config.stash[assertstate_key]
102102
if self._early_rewrite_bailout(name, state):
103103
return None
104-
state.trace("find_module called for: %s" % name)
104+
state.trace(f"find_module called for: {name}")
105105

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

274274
self.config.issue_config_time_warning(
275275
PytestAssertRewriteWarning(
276-
"Module already imported so cannot be rewritten: %s" % name
276+
f"Module already imported so cannot be rewritten: {name}"
277277
),
278278
stacklevel=5,
279279
)
@@ -374,29 +374,29 @@ def _read_pyc(
374374
return None
375375
# Check for invalid or out of date pyc file.
376376
if len(data) != (16):
377-
trace("_read_pyc(%s): invalid pyc (too short)" % source)
377+
trace(f"_read_pyc({source}): invalid pyc (too short)")
378378
return None
379379
if data[:4] != importlib.util.MAGIC_NUMBER:
380-
trace("_read_pyc(%s): invalid pyc (bad magic number)" % source)
380+
trace(f"_read_pyc({source}): invalid pyc (bad magic number)")
381381
return None
382382
if data[4:8] != b"\x00\x00\x00\x00":
383-
trace("_read_pyc(%s): invalid pyc (unsupported flags)" % source)
383+
trace(f"_read_pyc({source}): invalid pyc (unsupported flags)")
384384
return None
385385
mtime_data = data[8:12]
386386
if int.from_bytes(mtime_data, "little") != mtime & 0xFFFFFFFF:
387-
trace("_read_pyc(%s): out of date" % source)
387+
trace(f"_read_pyc({source}): out of date")
388388
return None
389389
size_data = data[12:16]
390390
if int.from_bytes(size_data, "little") != size & 0xFFFFFFFF:
391-
trace("_read_pyc(%s): invalid pyc (incorrect size)" % source)
391+
trace(f"_read_pyc({source}): invalid pyc (incorrect size)")
392392
return None
393393
try:
394394
co = marshal.load(fp)
395395
except Exception as e:
396396
trace(f"_read_pyc({source}): marshal.load error {e}")
397397
return None
398398
if not isinstance(co, types.CodeType):
399-
trace("_read_pyc(%s): not a code object" % source)
399+
trace(f"_read_pyc({source}): not a code object")
400400
return None
401401
return co
402402

src/_pytest/assertion/util.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ def _diff_text(left: str, right: str, verbose: int = 0) -> List[str]:
292292
if i > 42:
293293
i -= 10 # Provide some context
294294
explanation = [
295-
"Skipping %s identical leading characters in diff, use -v to show" % i
295+
f"Skipping {i} identical leading characters in diff, use -v to show"
296296
]
297297
left = left[i:]
298298
right = right[i:]
@@ -493,7 +493,7 @@ def _compare_eq_dict(
493493
common = set_left.intersection(set_right)
494494
same = {k: left[k] for k in common if left[k] == right[k]}
495495
if same and verbose < 2:
496-
explanation += ["Omitting %s identical items, use -vv to show" % len(same)]
496+
explanation += [f"Omitting {len(same)} identical items, use -vv to show"]
497497
elif same:
498498
explanation += ["Common items:"]
499499
explanation += highlighter(pprint.pformat(same)).splitlines()
@@ -560,7 +560,7 @@ def _compare_eq_cls(
560560
if same or diff:
561561
explanation += [""]
562562
if same and verbose < 2:
563-
explanation.append("Omitting %s identical items, use -vv to show" % len(same))
563+
explanation.append(f"Omitting {len(same)} identical items, use -vv to show")
564564
elif same:
565565
explanation += ["Matching attributes:"]
566566
explanation += highlighter(pprint.pformat(same)).splitlines()
@@ -590,7 +590,7 @@ def _notin_text(term: str, text: str, verbose: int = 0) -> List[str]:
590590
tail = text[index + len(term) :]
591591
correct_text = head + tail
592592
diff = _diff_text(text, correct_text, verbose)
593-
newdiff = ["%s is contained here:" % saferepr(term, maxsize=42)]
593+
newdiff = [f"{saferepr(term, maxsize=42)} is contained here:"]
594594
for line in diff:
595595
if line.startswith("Skipping"):
596596
continue

src/_pytest/cacheprovider.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -332,7 +332,7 @@ def get_last_failed_paths(self) -> Set[Path]:
332332

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

338338
def pytest_runtest_logreport(self, report: TestReport) -> None:
@@ -588,21 +588,21 @@ def cacheshow(config: Config, session: Session) -> int:
588588
dummy = object()
589589
basedir = config.cache._cachedir
590590
vdir = basedir / Cache._CACHE_PREFIX_VALUES
591-
tw.sep("-", "cache values for %r" % glob)
591+
tw.sep("-", f"cache values for {glob!r}")
592592
for valpath in sorted(x for x in vdir.rglob(glob) if x.is_file()):
593593
key = str(valpath.relative_to(vdir))
594594
val = config.cache.get(key, dummy)
595595
if val is dummy:
596-
tw.line("%s contains unreadable content, will be ignored" % key)
596+
tw.line(f"{key} contains unreadable content, will be ignored")
597597
else:
598-
tw.line("%s contains:" % key)
598+
tw.line(f"{key} contains:")
599599
for line in pformat(val).splitlines():
600600
tw.line(" " + line)
601601

602602
ddir = basedir / Cache._CACHE_PREFIX_DIRS
603603
if ddir.is_dir():
604604
contents = sorted(ddir.rglob(glob))
605-
tw.sep("-", "cache directories for %r" % glob)
605+
tw.sep("-", f"cache directories for {glob!r}")
606606
for p in contents:
607607
# if p.is_dir():
608608
# print("%s/" % p.relative_to(basedir))

0 commit comments

Comments
 (0)