Skip to content

Commit

Permalink
Manual fixes in order to use format and not % for UP031
Browse files Browse the repository at this point in the history
  • Loading branch information
Pierre-Sassoulas committed Jan 31, 2024
1 parent 057ada0 commit f300f7c
Show file tree
Hide file tree
Showing 27 changed files with 97 additions and 122 deletions.
6 changes: 0 additions & 6 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -135,12 +135,6 @@ select = [
"UP", # pyupgrade
]
ignore = [
# whitespace before ':'
"E203",
# Unused imports
"F401",
# TODO Temporarily disabled
"UP031",
]

[tool.ruff.lint.isort]
Expand Down
4 changes: 3 additions & 1 deletion src/_pytest/_io/saferepr.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ def _format_repr_exception(exc: BaseException, obj: object) -> str:
raise
except BaseException as exc:
exc_info = f"unpresentable exception ({_try_repr_or_str(exc)})"
return f"<[{exc_info} raised in repr()] {type(obj).__name__} object at 0x{id(obj):x}>"
return (
f"<[{exc_info} raised in repr()] {type(obj).__name__} object at 0x{id(obj):x}>"
)


def _ellipsize(s: str, maxsize: int) -> str:
Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/_py/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -675,7 +675,7 @@ def new(self, **kw):
else:
kw.setdefault("dirname", dirname)
kw.setdefault("sep", self.sep)
obj.strpath = normpath("%(dirname)s%(sep)s%(basename)s" % kw)
obj.strpath = normpath("{dirname}{sep}{basename}".format(**kw))
return obj

def _getbyspec(self, spec: str) -> list[str]:
Expand Down
4 changes: 3 additions & 1 deletion src/_pytest/cacheprovider.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,9 @@ def pytest_collection_modifyitems(

noun = "failure" if self._previously_failed_count == 1 else "failures"
suffix = " first" if self.config.getoption("failedfirst") else ""
self._report_status = f"rerun previous {self._previously_failed_count} {noun}{suffix}"
self._report_status = (
f"rerun previous {self._previously_failed_count} {noun}{suffix}"
)

if self._skipped_files > 0:
files_noun = "file" if self._skipped_files == 1 else "files"
Expand Down
7 changes: 1 addition & 6 deletions src/_pytest/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1375,12 +1375,7 @@ def _checkversion(self) -> None:

if Version(minver) > Version(pytest.__version__):
raise pytest.UsageError(
"%s: 'minversion' requires pytest-%s, actual pytest-%s'"
% (
self.inipath,
minver,
pytest.__version__,
)
f"{self.inipath}: 'minversion' requires pytest-{minver}, actual pytest-{pytest.__version__}'"
)

def _validate_config_options(self) -> None:
Expand Down
3 changes: 1 addition & 2 deletions src/_pytest/debugging.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,8 +265,7 @@ def _init_pdb(cls, method, *args, **kwargs):
elif capturing:
tw.sep(
">",
"PDB %s (IO-capturing turned off for %s)"
% (method, capturing),
f"PDB {method} (IO-capturing turned off for {capturing})",
)
else:
tw.sep(">", f"PDB {method}")
Expand Down
4 changes: 2 additions & 2 deletions src/_pytest/doctest.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,9 +487,9 @@ def _mock_aware_unwrap(
return real_unwrap(func, stop=lambda obj: _is_mocked(obj) or _stop(func))
except Exception as e:
warnings.warn(
"Got %r when unwrapping %r. This is usually caused "
f"Got {e!r} when unwrapping {func!r}. This is usually caused "
"by a violation of Python's object protocol; see e.g. "
"https://github.com/pytest-dev/pytest/issues/5080" % (e, func),
"https://github.com/pytest-dev/pytest/issues/5080",
PytestWarning,
)
raise
Expand Down
8 changes: 6 additions & 2 deletions src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,7 +737,9 @@ def node(self):
if node is None and scope is Scope.Class:
# Fallback to function item itself.
node = self._pyfuncitem
assert node, f'Could not obtain a node for scope "{scope}" for function {self._pyfuncitem!r}'
assert (
node
), f'Could not obtain a node for scope "{scope}" for function {self._pyfuncitem!r}'
return node

def _check_scope(
Expand Down Expand Up @@ -840,7 +842,9 @@ def formatrepr(self) -> "FixtureLookupErrorRepr":
if faclist:
available.add(name)
if self.argname in available:
msg = f" recursive dependency involving fixture '{self.argname}' detected"
msg = (
f" recursive dependency involving fixture '{self.argname}' detected"
)
else:
msg = f"fixture '{self.argname}' not found"
msg += "\n available fixtures: {}".format(", ".join(sorted(available)))
Expand Down
5 changes: 2 additions & 3 deletions src/_pytest/helpconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,8 @@ def pytest_cmdline_parse() -> Generator[None, Config, Config]:
path = config.option.debug
debugfile = open(path, "w", encoding="utf-8")
debugfile.write(
"versions pytest-%s, "
"python-%s\ninvocation_dir=%s\ncwd=%s\nargs=%s\n\n"
% (
"versions pytest-{}, "
"python-{}\ninvocation_dir={}\ncwd={}\nargs={}\n\n".format(
pytest.__version__,
".".join(map(str, sys.version_info)),
config.invocation_params.dir,
Expand Down
3 changes: 1 addition & 2 deletions src/_pytest/outcomes.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,7 @@ def importorskip(

if verattr is None or Version(verattr) < Version(minversion):
raise Skipped(
"module %r has __version__ %r, required is: %r"
% (modname, verattr, minversion),
f"module {modname!r} has __version__ {verattr!r}, required is: {minversion!r}",
allow_module_level=True,
)
return mod
11 changes: 4 additions & 7 deletions src/_pytest/pytester.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def pytest_runtest_protocol(self, item: Item) -> Generator[None, object, object]
"*** After:",
*(str(f) for f in lines2),
"***** %s FD leakage detected" % len(leaked_files),
"*** function %s:%s: %s " % item.location,
"*** function {}:{}: {} ".format(*item.location),
"See issue #2366",
]
item.warn(PytestWarning("\n".join(error)))
Expand Down Expand Up @@ -373,8 +373,8 @@ def matchreport(
values.append(rep)
if not values:
raise ValueError(
"could not find test report matching %r: "
"no test reports at all!" % (inamepart,)
f"could not find test report matching {inamepart!r}: "
"no test reports at all!"
)
if len(values) > 1:
raise ValueError(
Expand Down Expand Up @@ -1423,10 +1423,7 @@ def run(
def handle_timeout() -> None:
__tracebackhide__ = True

timeout_message = (
f"{timeout} second timeout expired running:"
f" {cmdargs}"
)
timeout_message = f"{timeout} second timeout expired running: {cmdargs}"

popen.kill()
popen.wait()
Expand Down
22 changes: 11 additions & 11 deletions src/_pytest/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,9 @@ def pytest_pycollect_makeitem(
elif getattr(obj, "__test__", True):
if is_generator(obj):
res: Function = Function.from_parent(collector, name=name)
reason = f"yield tests were removed in pytest 4.0 - {name} will be ignored"
reason = (
f"yield tests were removed in pytest 4.0 - {name} will be ignored"
)
res.add_marker(MARK_GEN.xfail(run=False, reason=reason))
res.warn(PytestCollectionWarning(reason))
return res
Expand Down Expand Up @@ -523,12 +525,12 @@ def importtestmodule(
except ImportPathMismatchError as e:
raise nodes.Collector.CollectError(
"import file mismatch:\n"
"imported module %r has this __file__ attribute:\n"
" %s\n"
"imported module {!r} has this __file__ attribute:\n"
" {}\n"
"which is not the same as the test file we want to collect:\n"
" %s\n"
" {}\n"
"HINT: remove __pycache__ / .pyc files and/or use a "
"unique basename for your test file modules" % e.args
"unique basename for your test file modules".format(*e.args)
) from e
except ImportError as e:
exc_info = ExceptionInfo.from_current()
Expand Down Expand Up @@ -764,19 +766,17 @@ def collect(self) -> Iterable[Union[nodes.Item, nodes.Collector]]:
assert self.parent is not None
self.warn(
PytestCollectionWarning(
"cannot collect test class %r because it has a "
"__init__ constructor (from: %s)"
% (self.obj.__name__, self.parent.nodeid)
f"cannot collect test class {self.obj.__name__!r} because it has a "
f"__init__ constructor (from: {self.parent.nodeid})"
)
)
return []
elif hasnew(self.obj):
assert self.parent is not None
self.warn(
PytestCollectionWarning(
"cannot collect test class %r because it has a "
"__new__ constructor (from: %s)"
% (self.obj.__name__, self.parent.nodeid)
f"cannot collect test class {self.obj.__name__!r} because it has a "
f"__new__ constructor (from: {self.parent.nodeid})"
)
)
return []
Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def getworkerinfoline(node):
return node._workerinfocache
except AttributeError:
d = node.workerinfo
ver = "%s.%s.%s" % d["version_info"][:3]
ver = "{}.{}.{}".format(*d["version_info"][:3])
node._workerinfocache = s = "[{}] {} -- Python {} {}".format(
d["id"], d["sysplatform"], ver, d["executable"]
)
Expand Down
3 changes: 1 addition & 2 deletions src/_pytest/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,7 @@ def pytest_terminal_summary(terminalreporter: "TerminalReporter") -> None:
if verbose < 2 and rep.duration < durations_min:
tr.write_line("")
tr.write_line(
"(%s durations < %gs hidden. Use -vv to show these durations.)"
% (len(dlist) - i, durations_min)
f"({len(dlist) - i} durations < {durations_min:g}s hidden. Use -vv to show these durations.)"
)
break
tr.write_line(f"{rep.duration:02.2f}s {rep.when:<8} {rep.nodeid}")
Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/setuponly.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def _show_fixture_action(
scope_indent = list(reversed(Scope)).index(fixturedef._scope)
tw.write(" " * 2 * scope_indent)
tw.write(
"{step} {scope} {fixture}".format(
"{step} {scope} {fixture}".format( # noqa UP032 (Readability)
step=msg.ljust(8), # align the output to TEARDOWN
scope=fixturedef.scope[0].upper(),
fixture=fixturedef.argname,
Expand Down
4 changes: 3 additions & 1 deletion src/_pytest/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -672,7 +672,9 @@ def _get_progress_information_message(self) -> str:
return f" [ {collected} / {collected} ]"
else:
if collected:
return f" [{len(self._progress_nodeids_reported) * 100 // collected:3d}%]"
return (
f" [{len(self._progress_nodeids_reported) * 100 // collected:3d}%]"
)
return " [100%]"

def _write_progress_information_filling_space(self) -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/unittest.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ def _addexcinfo(self, rawexcinfo: "_SysExcInfoType") -> None:
except BaseException:
fail(
"ERROR: Unknown Incompatible Exception "
"representation:\n%r" % (rawexcinfo,),
f"representation:\n{rawexcinfo!r}",
pytrace=False,
)
except KeyboardInterrupt:
Expand Down
4 changes: 1 addition & 3 deletions src/_pytest/warning_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,7 @@ class PytestExperimentalApiWarning(PytestWarning, FutureWarning):

@classmethod
def simple(cls, apiname: str) -> "PytestExperimentalApiWarning":
return cls(
f"{apiname} is an experimental api that may change over time"
)
return cls(f"{apiname} is an experimental api that may change over time")


@final
Expand Down
32 changes: 15 additions & 17 deletions testing/python/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -2197,8 +2197,9 @@ def test_arg(arg2):
pass
def test_check():
assert values == ["new1", "new2", "fin2", "fin1"]
"""
% locals()
""".format(
**locals()
)
)
reprec = pytester.inline_run("-s")
reprec.assertoutcome(passed=2)
Expand Down Expand Up @@ -3058,21 +3059,21 @@ def test_finalizer_order_on_parametrization(
) -> None:
"""#246"""
pytester.makepyfile(
"""
f"""
import pytest
values = []
@pytest.fixture(scope=%(scope)r, params=["1"])
@pytest.fixture(scope={scope!r}, params=["1"])
def fix1(request):
return request.param
@pytest.fixture(scope=%(scope)r)
@pytest.fixture(scope={scope!r})
def fix2(request, base):
def cleanup_fix2():
assert not values, "base should not have been finalized"
request.addfinalizer(cleanup_fix2)
@pytest.fixture(scope=%(scope)r)
@pytest.fixture(scope={scope!r})
def base(request, fix1):
def cleanup_base():
values.append("fin_base")
Expand All @@ -3086,7 +3087,6 @@ def test_baz(base, fix2):
def test_other():
pass
"""
% {"scope": scope}
)
reprec = pytester.inline_run("-lvs")
reprec.assertoutcome(passed=3)
Expand Down Expand Up @@ -3272,42 +3272,40 @@ class TestRequestScopeAccess:

def test_setup(self, pytester: Pytester, scope, ok, error) -> None:
pytester.makepyfile(
"""
f"""
import pytest
@pytest.fixture(scope=%r, autouse=True)
@pytest.fixture(scope={scope!r}, autouse=True)
def myscoped(request):
for x in %r:
for x in {ok.split()!r}:
assert hasattr(request, x)
for x in %r:
for x in {error.split()!r}:
pytest.raises(AttributeError, lambda:
getattr(request, x))
assert request.session
assert request.config
def test_func():
pass
"""
% (scope, ok.split(), error.split())
)
reprec = pytester.inline_run("-l")
reprec.assertoutcome(passed=1)

def test_funcarg(self, pytester: Pytester, scope, ok, error) -> None:
pytester.makepyfile(
"""
f"""
import pytest
@pytest.fixture(scope=%r)
@pytest.fixture(scope={scope!r})
def arg(request):
for x in %r:
for x in {ok.split()!r}:
assert hasattr(request, x)
for x in %r:
for x in {error.split()!r}:
pytest.raises(AttributeError, lambda:
getattr(request, x))
assert request.session
assert request.config
def test_func(arg):
pass
"""
% (scope, ok.split(), error.split())
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
Expand Down
9 changes: 5 additions & 4 deletions testing/test_assertrewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -781,11 +781,10 @@ def test_zipfile(self, pytester: Pytester) -> None:
f.close()
z.chmod(256)
pytester.makepyfile(
"""
f"""
import sys
sys.path.append(%r)
sys.path.append({z_fn!r})
import test_gum.test_lizard"""
% (z_fn,)
)
assert pytester.runpytest().ret == ExitCode.NO_TESTS_COLLECTED

Expand Down Expand Up @@ -2035,7 +2034,9 @@ def test_foo():
assert test_foo_pyc.is_file()

# normal file: not touched by pytest, normal cache tag
bar_init_pyc = get_cache_dir(bar_init) / f"__init__.{sys.implementation.cache_tag}.pyc"
bar_init_pyc = (
get_cache_dir(bar_init) / f"__init__.{sys.implementation.cache_tag}.pyc"
)
assert bar_init_pyc.is_file()


Expand Down
Loading

0 comments on commit f300f7c

Please sign in to comment.