Skip to content

Commit 791543b

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent e300124 commit 791543b

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

+236
-469
lines changed

doc/en/example/multipython.py

+8-12
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,12 @@ def dumps(self, obj):
3333
dumpfile = self.picklefile.with_name("dump.py")
3434
dumpfile.write_text(
3535
textwrap.dedent(
36-
r"""
36+
rf"""
3737
import pickle
38-
f = open({!r}, 'wb')
39-
s = pickle.dump({!r}, f, protocol=2)
38+
f = open({str(self.picklefile)!r}, 'wb')
39+
s = pickle.dump({obj!r}, f, protocol=2)
4040
f.close()
41-
""".format(
42-
str(self.picklefile), obj
43-
)
41+
"""
4442
)
4543
)
4644
subprocess.run((self.pythonpath, str(dumpfile)), check=True)
@@ -49,17 +47,15 @@ def load_and_is_true(self, expression):
4947
loadfile = self.picklefile.with_name("load.py")
5048
loadfile.write_text(
5149
textwrap.dedent(
52-
r"""
50+
rf"""
5351
import pickle
54-
f = open({!r}, 'rb')
52+
f = open({str(self.picklefile)!r}, 'rb')
5553
obj = pickle.load(f)
5654
f.close()
57-
res = eval({!r})
55+
res = eval({expression!r})
5856
if not res:
5957
raise SystemExit(1)
60-
""".format(
61-
str(self.picklefile), expression
62-
)
58+
"""
6359
)
6460
)
6561
print(loadfile)

src/_pytest/_code/code.py

+3-10
Original file line numberDiff line numberDiff line change
@@ -587,9 +587,7 @@ def traceback(self, value: Traceback) -> None:
587587
def __repr__(self) -> str:
588588
if self._excinfo is None:
589589
return "<ExceptionInfo for raises contextmanager>"
590-
return "<{} {} tblen={}>".format(
591-
self.__class__.__name__, saferepr(self._excinfo[1]), len(self.traceback)
592-
)
590+
return f"<{self.__class__.__name__} {saferepr(self._excinfo[1])} tblen={len(self.traceback)}>"
593591

594592
def exconly(self, tryshort: bool = False) -> str:
595593
"""Return the exception as a string.
@@ -1017,13 +1015,8 @@ def _truncate_recursive_traceback(
10171015
extraline: Optional[str] = (
10181016
"!!! Recursion error detected, but an error occurred locating the origin of recursion.\n"
10191017
" The following exception happened when comparing locals in the stack frame:\n"
1020-
" {exc_type}: {exc_msg}\n"
1021-
" Displaying first and last {max_frames} stack frames out of {total}."
1022-
).format(
1023-
exc_type=type(e).__name__,
1024-
exc_msg=str(e),
1025-
max_frames=max_frames,
1026-
total=len(traceback),
1018+
f" {type(e).__name__}: {str(e)}\n"
1019+
f" Displaying first and last {max_frames} stack frames out of {len(traceback)}."
10271020
)
10281021
# Type ignored because adding two instances of a List subtype
10291022
# currently incorrectly has type List instead of the subtype.

src/_pytest/_io/saferepr.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,7 @@ def _format_repr_exception(exc: BaseException, obj: object) -> str:
1919
raise
2020
except BaseException as exc:
2121
exc_info = f"unpresentable exception ({_try_repr_or_str(exc)})"
22-
return "<[{} raised in repr()] {} object at 0x{:x}>".format(
23-
exc_info, type(obj).__name__, id(obj)
24-
)
22+
return f"<[{exc_info} raised in repr()] {type(obj).__name__} object at 0x{id(obj):x}>"
2523

2624

2725
def _ellipsize(s: str, maxsize: int) -> str:

src/_pytest/_io/terminalwriter.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -184,9 +184,7 @@ def _write_source(self, lines: Sequence[str], indents: Sequence[str] = ()) -> No
184184
"""
185185
if indents and len(indents) != len(lines):
186186
raise ValueError(
187-
"indents size ({}) should have same size as lines ({})".format(
188-
len(indents), len(lines)
189-
)
187+
f"indents size ({len(indents)}) should have same size as lines ({len(lines)})"
190188
)
191189
if not indents:
192190
indents = [""] * len(lines)

src/_pytest/assertion/util.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -303,8 +303,8 @@ def _diff_text(left: str, right: str, verbose: int = 0) -> List[str]:
303303
if i > 42:
304304
i -= 10 # Provide some context
305305
explanation += [
306-
"Skipping {} identical trailing "
307-
"characters in diff, use -v to show".format(i)
306+
f"Skipping {i} identical trailing "
307+
"characters in diff, use -v to show"
308308
]
309309
left = left[:-i]
310310
right = right[:-i]

src/_pytest/cacheprovider.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -369,15 +369,11 @@ def pytest_collection_modifyitems(
369369

370370
noun = "failure" if self._previously_failed_count == 1 else "failures"
371371
suffix = " first" if self.config.getoption("failedfirst") else ""
372-
self._report_status = "rerun previous {count} {noun}{suffix}".format(
373-
count=self._previously_failed_count, suffix=suffix, noun=noun
374-
)
372+
self._report_status = f"rerun previous {self._previously_failed_count} {noun}{suffix}"
375373

376374
if self._skipped_files > 0:
377375
files_noun = "file" if self._skipped_files == 1 else "files"
378-
self._report_status += " (skipped {files} {files_noun})".format(
379-
files=self._skipped_files, files_noun=files_noun
380-
)
376+
self._report_status += f" (skipped {self._skipped_files} {files_noun})"
381377
else:
382378
self._report_status = "no previously failed tests, "
383379
if self.config.getoption("last_failed_no_failures") == "none":

src/_pytest/capture.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -791,9 +791,7 @@ def set_fixture(self, capture_fixture: "CaptureFixture[Any]") -> None:
791791
current_fixture = self._capture_fixture.request.fixturename
792792
requested_fixture = capture_fixture.request.fixturename
793793
capture_fixture.request.raiseerror(
794-
"cannot use {} and {} at the same time".format(
795-
requested_fixture, current_fixture
796-
)
794+
f"cannot use {requested_fixture} and {current_fixture} at the same time"
797795
)
798796
self._capture_fixture = capture_fixture
799797

src/_pytest/compat.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -244,9 +244,7 @@ def get_real_func(obj):
244244
from _pytest._io.saferepr import saferepr
245245

246246
raise ValueError(
247-
("could not find real function of {start}\nstopped at {current}").format(
248-
start=saferepr(start_obj), current=saferepr(obj)
249-
)
247+
f"could not find real function of {saferepr(start_obj)}\nstopped at {saferepr(obj)}"
250248
)
251249
if isinstance(obj, functools.partial):
252250
obj = obj.func

src/_pytest/config/__init__.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -1615,9 +1615,7 @@ def _get_override_ini_value(self, name: str) -> Optional[str]:
16151615
key, user_ini_value = ini_config.split("=", 1)
16161616
except ValueError as e:
16171617
raise UsageError(
1618-
"-o/--override-ini expects option=value style (got: {!r}).".format(
1619-
ini_config
1620-
)
1618+
f"-o/--override-ini expects option=value style (got: {ini_config!r})."
16211619
) from e
16221620
else:
16231621
if key == name:

src/_pytest/config/findpaths.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -213,9 +213,7 @@ def determine_setup(
213213
rootdir = absolutepath(os.path.expandvars(rootdir_cmd_arg))
214214
if not rootdir.is_dir():
215215
raise UsageError(
216-
"Directory '{}' not found. Check your '--rootdir' option.".format(
217-
rootdir
218-
)
216+
f"Directory '{rootdir}' not found. Check your '--rootdir' option."
219217
)
220218
assert rootdir is not None
221219
return rootdir, inipath, inicfg or {}

src/_pytest/fixtures.py

+11-25
Original file line numberDiff line numberDiff line change
@@ -602,13 +602,9 @@ def _compute_fixture_value(self, fixturedef: "FixtureDef[object]") -> None:
602602
fixtures_not_supported = getattr(funcitem, "nofuncargs", False)
603603
if has_params and fixtures_not_supported:
604604
msg = (
605-
"{name} does not support fixtures, maybe unittest.TestCase subclass?\n"
606-
"Node id: {nodeid}\n"
607-
"Function type: {typename}"
608-
).format(
609-
name=funcitem.name,
610-
nodeid=funcitem.nodeid,
611-
typename=type(funcitem).__name__,
605+
f"{funcitem.name} does not support fixtures, maybe unittest.TestCase subclass?\n"
606+
f"Node id: {funcitem.nodeid}\n"
607+
f"Function type: {type(funcitem).__name__}"
612608
)
613609
fail(msg, pytrace=False)
614610
if has_params:
@@ -741,9 +737,7 @@ def node(self):
741737
if node is None and scope is Scope.Class:
742738
# Fallback to function item itself.
743739
node = self._pyfuncitem
744-
assert node, 'Could not obtain a node for scope "{}" for function {!r}'.format(
745-
scope, self._pyfuncitem
746-
)
740+
assert node, f'Could not obtain a node for scope "{scope}" for function {self._pyfuncitem!r}'
747741
return node
748742

749743
def _check_scope(
@@ -846,9 +840,7 @@ def formatrepr(self) -> "FixtureLookupErrorRepr":
846840
if faclist:
847841
available.add(name)
848842
if self.argname in available:
849-
msg = " recursive dependency involving fixture '{}' detected".format(
850-
self.argname
851-
)
843+
msg = f" recursive dependency involving fixture '{self.argname}' detected"
852844
else:
853845
msg = f"fixture '{self.argname}' not found"
854846
msg += "\n available fixtures: {}".format(", ".join(sorted(available)))
@@ -941,15 +933,13 @@ def _eval_scope_callable(
941933
result = scope_callable(fixture_name=fixture_name, config=config) # type: ignore[call-arg]
942934
except Exception as e:
943935
raise TypeError(
944-
"Error evaluating {} while defining fixture '{}'.\n"
945-
"Expected a function with the signature (*, fixture_name, config)".format(
946-
scope_callable, fixture_name
947-
)
936+
f"Error evaluating {scope_callable} while defining fixture '{fixture_name}'.\n"
937+
"Expected a function with the signature (*, fixture_name, config)"
948938
) from e
949939
if not isinstance(result, str):
950940
fail(
951-
"Expected {} to return a 'str' while defining fixture '{}', but it returned:\n"
952-
"{!r}".format(scope_callable, fixture_name, result),
941+
f"Expected {scope_callable} to return a 'str' while defining fixture '{fixture_name}', but it returned:\n"
942+
f"{result!r}",
953943
pytrace=False,
954944
)
955945
return result
@@ -1091,9 +1081,7 @@ def cache_key(self, request: SubRequest) -> object:
10911081
return request.param_index if not hasattr(request, "param") else request.param
10921082

10931083
def __repr__(self) -> str:
1094-
return "<FixtureDef argname={!r} scope={!r} baseid={!r}>".format(
1095-
self.argname, self.scope, self.baseid
1096-
)
1084+
return f"<FixtureDef argname={self.argname!r} scope={self.scope!r} baseid={self.baseid!r}>"
10971085

10981086

10991087
def resolve_fixture_function(
@@ -1209,9 +1197,7 @@ def __call__(self, function: FixtureFunction) -> FixtureFunction:
12091197
if name == "request":
12101198
location = getlocation(function)
12111199
fail(
1212-
"'request' is a reserved word for fixtures, use another name:\n {}".format(
1213-
location
1214-
),
1200+
f"'request' is a reserved word for fixtures, use another name:\n {location}",
12151201
pytrace=False,
12161202
)
12171203

src/_pytest/helpconfig.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -137,9 +137,7 @@ def unset_tracing() -> None:
137137
def showversion(config: Config) -> None:
138138
if config.option.version > 1:
139139
sys.stdout.write(
140-
"This is pytest version {}, imported from {}\n".format(
141-
pytest.__version__, pytest.__file__
142-
)
140+
f"This is pytest version {pytest.__version__}, imported from {pytest.__file__}\n"
143141
)
144142
plugininfo = getpluginversioninfo(config)
145143
if plugininfo:

src/_pytest/junitxml.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -274,9 +274,7 @@ def _warn_incompatibility_with_xunit2(
274274
if xml is not None and xml.family not in ("xunit1", "legacy"):
275275
request.node.warn(
276276
PytestWarning(
277-
"{fixture_name} is incompatible with junit_family '{family}' (use 'legacy' or 'xunit1')".format(
278-
fixture_name=fixture_name, family=xml.family
279-
)
277+
f"{fixture_name} is incompatible with junit_family '{xml.family}' (use 'legacy' or 'xunit1')"
280278
)
281279
)
282280

src/_pytest/logging.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -626,9 +626,9 @@ def get_log_level_for_setting(config: Config, *setting_names: str) -> Optional[i
626626
except ValueError as e:
627627
# Python logging does not recognise this as a logging level
628628
raise UsageError(
629-
"'{}' is not recognized as a logging level name for "
630-
"'{}'. Please consider passing the "
631-
"logging level num instead.".format(log_level, setting_name)
629+
f"'{log_level}' is not recognized as a logging level name for "
630+
f"'{setting_name}'. Please consider passing the "
631+
"logging level num instead."
632632
) from e
633633

634634

src/_pytest/mark/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -269,8 +269,8 @@ def pytest_configure(config: Config) -> None:
269269

270270
if empty_parameterset not in ("skip", "xfail", "fail_at_collect", None, ""):
271271
raise UsageError(
272-
"{!s} must be one of skip, xfail or fail_at_collect"
273-
" but it is {!r}".format(EMPTY_PARAMETERSET_OPTION, empty_parameterset)
272+
f"{EMPTY_PARAMETERSET_OPTION!s} must be one of skip, xfail or fail_at_collect"
273+
f" but it is {empty_parameterset!r}"
274274
)
275275

276276

src/_pytest/monkeypatch.py

+3-7
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,7 @@ def annotated_getattr(obj: object, name: str, ann: str) -> object:
9191
obj = getattr(obj, name)
9292
except AttributeError as e:
9393
raise AttributeError(
94-
"{!r} object at {} has no attribute {!r}".format(
95-
type(obj).__name__, ann, name
96-
)
94+
f"{type(obj).__name__!r} object at {ann} has no attribute {name!r}"
9795
) from e
9896
return obj
9997

@@ -321,10 +319,8 @@ def setenv(self, name: str, value: str, prepend: Optional[str] = None) -> None:
321319
if not isinstance(value, str):
322320
warnings.warn( # type: ignore[unreachable]
323321
PytestWarning(
324-
"Value of environment variable {name} type should be str, but got "
325-
"{value!r} (type: {type}); converted to str implicitly".format(
326-
name=name, value=value, type=type(value).__name__
327-
)
322+
f"Value of environment variable {name} type should be str, but got "
323+
f"{value!r} (type: {type(value).__name__}); converted to str implicitly"
328324
),
329325
stacklevel=2,
330326
)

src/_pytest/nodes.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -230,9 +230,7 @@ def warn(self, warning: Warning) -> None:
230230
# enforce type checks here to avoid getting a generic type error later otherwise.
231231
if not isinstance(warning, Warning):
232232
raise ValueError(
233-
"warning must be an instance of Warning or subclass, got {!r}".format(
234-
warning
235-
)
233+
f"warning must be an instance of Warning or subclass, got {warning!r}"
236234
)
237235
path, lineno = get_fslocation_from_item(self)
238236
assert lineno is not None

src/_pytest/pathlib.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -103,9 +103,7 @@ def on_rm_rf_error(
103103
if func not in (os.open,):
104104
warnings.warn(
105105
PytestWarning(
106-
"(rm_rf) unknown function {} when removing {}:\n{}: {}".format(
107-
func, path, type(exc), exc
108-
)
106+
f"(rm_rf) unknown function {func} when removing {path}:\n{type(exc)}: {exc}"
109107
)
110108
)
111109
return False
@@ -244,7 +242,7 @@ def make_numbered_dir(root: Path, prefix: str, mode: int = 0o700) -> Path:
244242
else:
245243
raise OSError(
246244
"could not create numbered dir with prefix "
247-
"{prefix} in {root} after 10 tries".format(prefix=prefix, root=root)
245+
f"{prefix} in {root} after 10 tries"
248246
)
249247

250248

src/_pytest/pytester.py

+4-8
Original file line numberDiff line numberDiff line change
@@ -378,9 +378,7 @@ def matchreport(
378378
)
379379
if len(values) > 1:
380380
raise ValueError(
381-
"found 2 or more testreports matching {!r}: {}".format(
382-
inamepart, values
383-
)
381+
f"found 2 or more testreports matching {inamepart!r}: {values}"
384382
)
385383
return values[0]
386384

@@ -1266,9 +1264,7 @@ def getitem(
12661264
for item in items:
12671265
if item.name == funcname:
12681266
return item
1269-
assert 0, "{!r} item not found in module:\n{}\nitems: {}".format(
1270-
funcname, source, items
1271-
)
1267+
assert 0, f"{funcname!r} item not found in module:\n{source}\nitems: {items}"
12721268

12731269
def getitems(self, source: Union[str, "os.PathLike[str]"]) -> List[Item]:
12741270
"""Return all test items collected from the module.
@@ -1428,8 +1424,8 @@ def handle_timeout() -> None:
14281424
__tracebackhide__ = True
14291425

14301426
timeout_message = (
1431-
"{seconds} second timeout expired running:"
1432-
" {command}".format(seconds=timeout, command=cmdargs)
1427+
f"{timeout} second timeout expired running:"
1428+
f" {cmdargs}"
14331429
)
14341430

14351431
popen.kill()

0 commit comments

Comments
 (0)