[ruff UP031] Fix to use format specifiers instead of percent format

This commit is contained in:
Pierre Sassoulas
2024-04-30 18:06:26 +02:00
parent da53e29780
commit 4788165e69
52 changed files with 202 additions and 212 deletions

View File

@@ -940,7 +940,7 @@ class FormattedExcinfo:
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

View File

@@ -616,7 +616,7 @@ class PrettyPrinter:
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__

View File

@@ -104,7 +104,7 @@ class TerminalWriter:
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(

View File

@@ -659,7 +659,7 @@ class LocalPath:
)
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:
@@ -705,7 +705,7 @@ class LocalPath:
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):
@@ -1026,7 +1026,7 @@ class LocalPath:
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."""

View File

@@ -101,7 +101,7 @@ class AssertionRewritingHook(importlib.abc.MetaPathFinder, importlib.abc.Loader)
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
@@ -273,7 +273,7 @@ class AssertionRewritingHook(importlib.abc.MetaPathFinder, importlib.abc.Loader)
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,
)
@@ -374,21 +374,21 @@ 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)
@@ -396,7 +396,7 @@ def _read_pyc(
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

View File

@@ -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:]
@@ -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()
@@ -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()
@@ -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

View File

@@ -332,7 +332,7 @@ class LFPlugin:
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:
@@ -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))

View File

@@ -738,7 +738,7 @@ class CaptureManager:
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

View File

@@ -798,7 +798,7 @@ class PytestPluginManager(PluginManager):
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":
@@ -847,9 +847,9 @@ class PytestPluginManager(PluginManager):
# "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
@@ -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}"
)
@@ -1185,7 +1184,7 @@ class Config:
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:
@@ -1435,7 +1434,7 @@ class Config:
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__):

View File

@@ -313,23 +313,23 @@ class Argument:
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)
@@ -383,7 +383,7 @@ class OptionGroup:
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)
@@ -441,7 +441,9 @@ class MyOptionParser(argparse.ArgumentParser):
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))
@@ -520,7 +522,7 @@ class DropShorterLongHelpFormatter(argparse.HelpFormatter):
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("-", "")

View File

@@ -181,8 +181,7 @@ class pytestPDB:
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()

View File

@@ -374,7 +374,7 @@ class DoctestItem(Item):
).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)
]
@@ -382,7 +382,7 @@ class DoctestItem(Item):
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]:
@@ -563,7 +563,7 @@ class DoctestModule(Module):
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

View File

@@ -675,7 +675,7 @@ class TopRequest(FixtureRequest):
return self._pyfuncitem
def __repr__(self) -> str:
return "<FixtureRequest for %r>" % (self.node)
return f"<FixtureRequest for {self.node!r}>"
def _fillfixtures(self) -> None:
item = self._pyfuncitem
@@ -1897,7 +1897,7 @@ def _showfixtures_main(config: Config, session: "Session") -> None:
continue
tw.write(f"{argname}", green=True)
if fixturedef.scope != "function":
tw.write(" [%s scope]" % fixturedef.scope, cyan=True)
tw.write(f" [{fixturedef.scope} scope]", cyan=True)
tw.write(f" -- {prettypath}", yellow=True)
tw.write("\n")
doc = inspect.getdoc(fixturedef.func)

View File

@@ -121,11 +121,11 @@ def pytest_cmdline_parse() -> Generator[None, Config, Config]:
)
config.trace.root.setwriter(debugfile.write)
undo_tracing = config.pluginmanager.enable_tracing()
sys.stderr.write("writing pytest debug information to %s\n" % path)
sys.stderr.write(f"writing pytest debug information to {path}\n")
def unset_tracing() -> None:
debugfile.close()
sys.stderr.write("wrote pytest debug information to %s\n" % debugfile.name)
sys.stderr.write(f"wrote pytest debug information to {debugfile.name}\n")
config.trace.root.setwriter(None)
undo_tracing()
@@ -185,7 +185,7 @@ def showhelp(config: Config) -> None:
if help is None:
raise TypeError(f"help argument cannot be None for {name}")
spec = f"{name} ({type}):"
tw.write(" %s" % spec)
tw.write(f" {spec}")
spec_len = len(spec)
if spec_len > (indent_len - 3):
# Display help starting at a new line.

View File

@@ -53,9 +53,9 @@ def bin_xml_escape(arg: object) -> str:
def repl(matchobj: Match[str]) -> str:
i = ord(matchobj.group())
if i <= 0xFF:
return "#x%02X" % i
return f"#x{i:02X}"
else:
return "#x%04X" % i
return f"#x{i:04X}"
# The spec range of valid chars is:
# Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
@@ -149,7 +149,7 @@ class _NodeReporter:
self.attrs = temp_attrs
def to_xml(self) -> ET.Element:
testcase = ET.Element("testcase", self.attrs, time="%.3f" % self.duration)
testcase = ET.Element("testcase", self.attrs, time=f"{self.duration:.3f}")
properties = self.make_properties_node()
if properties is not None:
testcase.append(properties)
@@ -670,7 +670,7 @@ class LogXML:
failures=str(self.stats["failure"]),
skipped=str(self.stats["skipped"]),
tests=str(numtests),
time="%.3f" % suite_time_delta,
time=f"{suite_time_delta:.3f}",
timestamp=datetime.fromtimestamp(self.suite_start_time).isoformat(),
hostname=platform.node(),
)

View File

@@ -122,7 +122,7 @@ def pytest_cmdline_main(config: Config) -> Optional[Union[int, ExitCode]]:
parts = line.split(":", 1)
name = parts[0]
rest = parts[1] if len(parts) == 2 else ""
tw.write("@pytest.mark.%s:" % name, bold=True)
tw.write(f"@pytest.mark.{name}:", bold=True)
tw.line(rest)
tw.line()
config._ensure_unconfigure()

View File

@@ -552,9 +552,9 @@ class MarkGenerator:
fail(f"Unknown '{name}' mark, did you mean 'parametrize'?")
warnings.warn(
"Unknown pytest.mark.%s - is this a typo? You can register "
f"Unknown pytest.mark.{name} - is this a typo? You can register "
"custom marks to avoid this warning - for details, see "
"https://docs.pytest.org/en/stable/how-to/mark.html" % name,
"https://docs.pytest.org/en/stable/how-to/mark.html",
PytestUnknownMarkWarning,
2,
)

View File

@@ -65,7 +65,7 @@ def pytest_unconfigure(config: Config) -> None:
# Write summary.
tr.write_sep("=", "Sending information to Paste Service")
pastebinurl = create_new_paste(sessionlog)
tr.write_line("pastebin session-log: %s\n" % pastebinurl)
tr.write_line(f"pastebin session-log: {pastebinurl}\n")
def create_new_paste(contents: Union[str, bytes]) -> str:
@@ -85,7 +85,7 @@ def create_new_paste(contents: Union[str, bytes]) -> str:
urlopen(url, data=urlencode(params).encode("ascii")).read().decode("utf-8")
)
except OSError as exc_info: # urllib errors
return "bad response: %s" % exc_info
return f"bad response: {exc_info}"
m = re.search(r'href="/raw/(\w+)"', response)
if m:
return f"{url}/show/{m.group(1)}"

View File

@@ -182,13 +182,13 @@ class LsofFdLeakChecker:
leaked_files = [t for t in lines2 if t[0] in new_fds]
if leaked_files:
error = [
"***** %s FD leakage detected" % len(leaked_files),
f"***** {len(leaked_files)} FD leakage detected",
*(str(f) for f in leaked_files),
"*** Before:",
*(str(f) for f in lines1),
"*** After:",
*(str(f) for f in lines2),
"***** %s FD leakage detected" % len(leaked_files),
f"***** {len(leaked_files)} FD leakage detected",
"*** function {}:{}: {} ".format(*item.location),
"See issue #2366",
]
@@ -313,7 +313,7 @@ class HookRecorder:
del self.calls[i]
return call
lines = [f"could not find call {name!r}, in:"]
lines.extend([" %s" % x for x in self.calls])
lines.extend([f" {x}" for x in self.calls])
fail("\n".join(lines))
def getcall(self, name: str) -> RecordedHookCall:
@@ -1204,7 +1204,9 @@ class Pytester:
if str(x).startswith("--basetemp"):
break
else:
new_args.append("--basetemp=%s" % self.path.parent.joinpath("basetemp"))
new_args.append(
"--basetemp={}".format(self.path.parent.joinpath("basetemp"))
)
return new_args
def parseconfig(self, *args: Union[str, "os.PathLike[str]"]) -> Config:
@@ -1485,7 +1487,7 @@ class Pytester:
"""
__tracebackhide__ = True
p = make_numbered_dir(root=self.path, prefix="runpytest-", mode=0o700)
args = ("--basetemp=%s" % p, *args)
args = (f"--basetemp={p}", *args)
plugins = [x for x in self.plugins if isinstance(x, str)]
if plugins:
args = ("-p", plugins[0], *args)
@@ -1593,7 +1595,7 @@ class LineMatcher:
self._log("matched: ", repr(line))
break
else:
msg = "line %r not found in output" % line
msg = f"line {line!r} not found in output"
self._log(msg)
self._fail(msg)
@@ -1605,7 +1607,7 @@ class LineMatcher:
for i, line in enumerate(self.lines):
if fnline == line or fnmatch(line, fnline):
return self.lines[i + 1 :]
raise ValueError("line %r not found in output" % fnline)
raise ValueError(f"line {fnline!r} not found in output")
def _log(self, *args) -> None:
self._log_output.append(" ".join(str(x) for x in args))
@@ -1690,7 +1692,7 @@ class LineMatcher:
started = True
break
elif match_func(nextline, line):
self._log("%s:" % match_nickname, repr(line))
self._log(f"{match_nickname}:", repr(line))
self._log(
"{:>{width}}".format("with:", width=wnick), repr(nextline)
)

View File

@@ -224,7 +224,7 @@ def pytest_pycollect_makeitem(
filename, lineno = getfslineno(obj)
warnings.warn_explicit(
message=PytestCollectionWarning(
"cannot collect %r because it is not a function." % name
f"cannot collect {name!r} because it is not a function."
),
category=None,
filename=str(filename),

View File

@@ -232,10 +232,10 @@ def _report_unserialization_failure(
url = "https://github.com/pytest-dev/pytest/issues"
stream = StringIO()
pprint("-" * 100, stream=stream)
pprint("INTERNALERROR: Unknown entry type returned: %s" % type_name, stream=stream)
pprint("report_name: %s" % report_class, stream=stream)
pprint(f"INTERNALERROR: Unknown entry type returned: {type_name}", stream=stream)
pprint(f"report_name: {report_class}", stream=stream)
pprint(reportdict, stream=stream)
pprint("Please report this bug at %s" % url, stream=stream)
pprint(f"Please report this bug at {url}", stream=stream)
pprint("-" * 100, stream=stream)
raise RuntimeError(stream.getvalue())

View File

@@ -90,7 +90,7 @@ def pytest_terminal_summary(terminalreporter: "TerminalReporter") -> None:
if not durations:
tr.write_sep("=", "slowest durations")
else:
tr.write_sep("=", "slowest %s durations" % durations)
tr.write_sep("=", f"slowest {durations} durations")
dlist = dlist[:durations]
for i, rep in enumerate(dlist):

View File

@@ -117,7 +117,7 @@ def evaluate_condition(item: Item, mark: Mark, condition: object) -> Tuple[bool,
result = eval(condition_code, globals_)
except SyntaxError as exc:
msglines = [
"Error evaluating %r condition" % mark.name,
f"Error evaluating {mark.name!r} condition",
" " + condition,
" " + " " * (exc.offset or 0) + "^",
"SyntaxError: invalid syntax",
@@ -125,7 +125,7 @@ def evaluate_condition(item: Item, mark: Mark, condition: object) -> Tuple[bool,
fail("\n".join(msglines), pytrace=False)
except Exception as exc:
msglines = [
"Error evaluating %r condition" % mark.name,
f"Error evaluating {mark.name!r} condition",
" " + condition,
*traceback.format_exception_only(type(exc), exc),
]
@@ -137,7 +137,7 @@ def evaluate_condition(item: Item, mark: Mark, condition: object) -> Tuple[bool,
result = bool(condition)
except Exception as exc:
msglines = [
"Error evaluating %r condition as a boolean" % mark.name,
f"Error evaluating {mark.name!r} condition as a boolean",
*traceback.format_exception_only(type(exc), exc),
]
fail("\n".join(msglines), pytrace=False)
@@ -149,7 +149,7 @@ def evaluate_condition(item: Item, mark: Mark, condition: object) -> Tuple[bool,
else:
# XXX better be checked at collection time
msg = (
"Error evaluating %r: " % mark.name
f"Error evaluating {mark.name!r}: "
+ "you need to specify reason=STRING when using booleans as conditions."
)
fail(msg, pytrace=False)

View File

@@ -640,7 +640,7 @@ class TerminalReporter:
self._write_progress_information_filling_space()
else:
self.ensure_newline()
self._tw.write("[%s]" % rep.node.gateway.id)
self._tw.write(f"[{rep.node.gateway.id}]")
if self._show_progress_info:
self._tw.write(
self._get_progress_information_message() + " ", cyan=True
@@ -818,7 +818,9 @@ class TerminalReporter:
plugininfo = config.pluginmanager.list_plugin_distinfo()
if plugininfo:
result.append("plugins: %s" % ", ".join(_plugin_nameversions(plugininfo)))
result.append(
"plugins: {}".format(", ".join(_plugin_nameversions(plugininfo)))
)
return result
def pytest_collection_finish(self, session: "Session") -> None: