Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Jan 31, 2024
1 parent e300124 commit 791543b
Show file tree
Hide file tree
Showing 52 changed files with 236 additions and 469 deletions.
20 changes: 8 additions & 12 deletions doc/en/example/multipython.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,12 @@ def dumps(self, obj):
dumpfile = self.picklefile.with_name("dump.py")
dumpfile.write_text(
textwrap.dedent(
r"""
rf"""
import pickle
f = open({!r}, 'wb')
s = pickle.dump({!r}, f, protocol=2)
f = open({str(self.picklefile)!r}, 'wb')
s = pickle.dump({obj!r}, f, protocol=2)
f.close()
""".format(
str(self.picklefile), obj
)
"""
)
)
subprocess.run((self.pythonpath, str(dumpfile)), check=True)
Expand All @@ -49,17 +47,15 @@ def load_and_is_true(self, expression):
loadfile = self.picklefile.with_name("load.py")
loadfile.write_text(
textwrap.dedent(
r"""
rf"""
import pickle
f = open({!r}, 'rb')
f = open({str(self.picklefile)!r}, 'rb')
obj = pickle.load(f)
f.close()
res = eval({!r})
res = eval({expression!r})
if not res:
raise SystemExit(1)
""".format(
str(self.picklefile), expression
)
"""
)
)
print(loadfile)
Expand Down
13 changes: 3 additions & 10 deletions src/_pytest/_code/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -587,9 +587,7 @@ def traceback(self, value: Traceback) -> None:
def __repr__(self) -> str:
if self._excinfo is None:
return "<ExceptionInfo for raises contextmanager>"
return "<{} {} tblen={}>".format(
self.__class__.__name__, saferepr(self._excinfo[1]), len(self.traceback)
)
return f"<{self.__class__.__name__} {saferepr(self._excinfo[1])} tblen={len(self.traceback)}>"

def exconly(self, tryshort: bool = False) -> str:
"""Return the exception as a string.
Expand Down Expand Up @@ -1017,13 +1015,8 @@ def _truncate_recursive_traceback(
extraline: Optional[str] = (
"!!! Recursion error detected, but an error occurred locating the origin of recursion.\n"
" The following exception happened when comparing locals in the stack frame:\n"
" {exc_type}: {exc_msg}\n"
" Displaying first and last {max_frames} stack frames out of {total}."
).format(
exc_type=type(e).__name__,
exc_msg=str(e),
max_frames=max_frames,
total=len(traceback),
f" {type(e).__name__}: {str(e)}\n"
f" Displaying first and last {max_frames} stack frames out of {len(traceback)}."
)
# Type ignored because adding two instances of a List subtype
# currently incorrectly has type List instead of the subtype.
Expand Down
4 changes: 1 addition & 3 deletions src/_pytest/_io/saferepr.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ 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 "<[{} raised in repr()] {} object at 0x{:x}>".format(
exc_info, type(obj).__name__, id(obj)
)
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
4 changes: 1 addition & 3 deletions src/_pytest/_io/terminalwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,7 @@ def _write_source(self, lines: Sequence[str], indents: Sequence[str] = ()) -> No
"""
if indents and len(indents) != len(lines):
raise ValueError(
"indents size ({}) should have same size as lines ({})".format(
len(indents), len(lines)
)
f"indents size ({len(indents)}) should have same size as lines ({len(lines)})"
)
if not indents:
indents = [""] * len(lines)
Expand Down
4 changes: 2 additions & 2 deletions src/_pytest/assertion/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,8 +303,8 @@ def _diff_text(left: str, right: str, verbose: int = 0) -> List[str]:
if i > 42:
i -= 10 # Provide some context
explanation += [
"Skipping {} identical trailing "
"characters in diff, use -v to show".format(i)
f"Skipping {i} identical trailing "
"characters in diff, use -v to show"
]
left = left[:-i]
right = right[:-i]
Expand Down
8 changes: 2 additions & 6 deletions src/_pytest/cacheprovider.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,15 +369,11 @@ 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 = "rerun previous {count} {noun}{suffix}".format(
count=self._previously_failed_count, suffix=suffix, noun=noun
)
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"
self._report_status += " (skipped {files} {files_noun})".format(
files=self._skipped_files, files_noun=files_noun
)
self._report_status += f" (skipped {self._skipped_files} {files_noun})"
else:
self._report_status = "no previously failed tests, "
if self.config.getoption("last_failed_no_failures") == "none":
Expand Down
4 changes: 1 addition & 3 deletions src/_pytest/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -791,9 +791,7 @@ def set_fixture(self, capture_fixture: "CaptureFixture[Any]") -> None:
current_fixture = self._capture_fixture.request.fixturename
requested_fixture = capture_fixture.request.fixturename
capture_fixture.request.raiseerror(
"cannot use {} and {} at the same time".format(
requested_fixture, current_fixture
)
f"cannot use {requested_fixture} and {current_fixture} at the same time"
)
self._capture_fixture = capture_fixture

Expand Down
4 changes: 1 addition & 3 deletions src/_pytest/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,9 +244,7 @@ def get_real_func(obj):
from _pytest._io.saferepr import saferepr

raise ValueError(
("could not find real function of {start}\nstopped at {current}").format(
start=saferepr(start_obj), current=saferepr(obj)
)
f"could not find real function of {saferepr(start_obj)}\nstopped at {saferepr(obj)}"
)
if isinstance(obj, functools.partial):
obj = obj.func
Expand Down
4 changes: 1 addition & 3 deletions src/_pytest/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1615,9 +1615,7 @@ def _get_override_ini_value(self, name: str) -> Optional[str]:
key, user_ini_value = ini_config.split("=", 1)
except ValueError as e:
raise UsageError(
"-o/--override-ini expects option=value style (got: {!r}).".format(
ini_config
)
f"-o/--override-ini expects option=value style (got: {ini_config!r})."
) from e
else:
if key == name:
Expand Down
4 changes: 1 addition & 3 deletions src/_pytest/config/findpaths.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,7 @@ def determine_setup(
rootdir = absolutepath(os.path.expandvars(rootdir_cmd_arg))
if not rootdir.is_dir():
raise UsageError(
"Directory '{}' not found. Check your '--rootdir' option.".format(
rootdir
)
f"Directory '{rootdir}' not found. Check your '--rootdir' option."
)
assert rootdir is not None
return rootdir, inipath, inicfg or {}
Expand Down
36 changes: 11 additions & 25 deletions src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -602,13 +602,9 @@ def _compute_fixture_value(self, fixturedef: "FixtureDef[object]") -> None:
fixtures_not_supported = getattr(funcitem, "nofuncargs", False)
if has_params and fixtures_not_supported:
msg = (
"{name} does not support fixtures, maybe unittest.TestCase subclass?\n"
"Node id: {nodeid}\n"
"Function type: {typename}"
).format(
name=funcitem.name,
nodeid=funcitem.nodeid,
typename=type(funcitem).__name__,
f"{funcitem.name} does not support fixtures, maybe unittest.TestCase subclass?\n"
f"Node id: {funcitem.nodeid}\n"
f"Function type: {type(funcitem).__name__}"
)
fail(msg, pytrace=False)
if has_params:
Expand Down Expand Up @@ -741,9 +737,7 @@ def node(self):
if node is None and scope is Scope.Class:
# Fallback to function item itself.
node = self._pyfuncitem
assert node, 'Could not obtain a node for scope "{}" for function {!r}'.format(
scope, self._pyfuncitem
)
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 @@ -846,9 +840,7 @@ def formatrepr(self) -> "FixtureLookupErrorRepr":
if faclist:
available.add(name)
if self.argname in available:
msg = " recursive dependency involving fixture '{}' detected".format(
self.argname
)
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 Expand Up @@ -941,15 +933,13 @@ def _eval_scope_callable(
result = scope_callable(fixture_name=fixture_name, config=config) # type: ignore[call-arg]
except Exception as e:
raise TypeError(
"Error evaluating {} while defining fixture '{}'.\n"
"Expected a function with the signature (*, fixture_name, config)".format(
scope_callable, fixture_name
)
f"Error evaluating {scope_callable} while defining fixture '{fixture_name}'.\n"
"Expected a function with the signature (*, fixture_name, config)"
) from e
if not isinstance(result, str):
fail(
"Expected {} to return a 'str' while defining fixture '{}', but it returned:\n"
"{!r}".format(scope_callable, fixture_name, result),
f"Expected {scope_callable} to return a 'str' while defining fixture '{fixture_name}', but it returned:\n"
f"{result!r}",
pytrace=False,
)
return result
Expand Down Expand Up @@ -1091,9 +1081,7 @@ def cache_key(self, request: SubRequest) -> object:
return request.param_index if not hasattr(request, "param") else request.param

def __repr__(self) -> str:
return "<FixtureDef argname={!r} scope={!r} baseid={!r}>".format(
self.argname, self.scope, self.baseid
)
return f"<FixtureDef argname={self.argname!r} scope={self.scope!r} baseid={self.baseid!r}>"


def resolve_fixture_function(
Expand Down Expand Up @@ -1209,9 +1197,7 @@ def __call__(self, function: FixtureFunction) -> FixtureFunction:
if name == "request":
location = getlocation(function)
fail(
"'request' is a reserved word for fixtures, use another name:\n {}".format(
location
),
f"'request' is a reserved word for fixtures, use another name:\n {location}",
pytrace=False,
)

Expand Down
4 changes: 1 addition & 3 deletions src/_pytest/helpconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,7 @@ def unset_tracing() -> None:
def showversion(config: Config) -> None:
if config.option.version > 1:
sys.stdout.write(
"This is pytest version {}, imported from {}\n".format(
pytest.__version__, pytest.__file__
)
f"This is pytest version {pytest.__version__}, imported from {pytest.__file__}\n"
)
plugininfo = getpluginversioninfo(config)
if plugininfo:
Expand Down
4 changes: 1 addition & 3 deletions src/_pytest/junitxml.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,9 +274,7 @@ def _warn_incompatibility_with_xunit2(
if xml is not None and xml.family not in ("xunit1", "legacy"):
request.node.warn(
PytestWarning(
"{fixture_name} is incompatible with junit_family '{family}' (use 'legacy' or 'xunit1')".format(
fixture_name=fixture_name, family=xml.family
)
f"{fixture_name} is incompatible with junit_family '{xml.family}' (use 'legacy' or 'xunit1')"
)
)

Expand Down
6 changes: 3 additions & 3 deletions src/_pytest/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,9 +626,9 @@ def get_log_level_for_setting(config: Config, *setting_names: str) -> Optional[i
except ValueError as e:
# Python logging does not recognise this as a logging level
raise UsageError(
"'{}' is not recognized as a logging level name for "
"'{}'. Please consider passing the "
"logging level num instead.".format(log_level, setting_name)
f"'{log_level}' is not recognized as a logging level name for "
f"'{setting_name}'. Please consider passing the "
"logging level num instead."
) from e


Expand Down
4 changes: 2 additions & 2 deletions src/_pytest/mark/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,8 +269,8 @@ def pytest_configure(config: Config) -> None:

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


Expand Down
10 changes: 3 additions & 7 deletions src/_pytest/monkeypatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,7 @@ def annotated_getattr(obj: object, name: str, ann: str) -> object:
obj = getattr(obj, name)
except AttributeError as e:
raise AttributeError(
"{!r} object at {} has no attribute {!r}".format(
type(obj).__name__, ann, name
)
f"{type(obj).__name__!r} object at {ann} has no attribute {name!r}"
) from e
return obj

Expand Down Expand Up @@ -321,10 +319,8 @@ def setenv(self, name: str, value: str, prepend: Optional[str] = None) -> None:
if not isinstance(value, str):
warnings.warn( # type: ignore[unreachable]
PytestWarning(
"Value of environment variable {name} type should be str, but got "
"{value!r} (type: {type}); converted to str implicitly".format(
name=name, value=value, type=type(value).__name__
)
f"Value of environment variable {name} type should be str, but got "
f"{value!r} (type: {type(value).__name__}); converted to str implicitly"
),
stacklevel=2,
)
Expand Down
4 changes: 1 addition & 3 deletions src/_pytest/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,9 +230,7 @@ def warn(self, warning: Warning) -> None:
# enforce type checks here to avoid getting a generic type error later otherwise.
if not isinstance(warning, Warning):
raise ValueError(
"warning must be an instance of Warning or subclass, got {!r}".format(
warning
)
f"warning must be an instance of Warning or subclass, got {warning!r}"
)
path, lineno = get_fslocation_from_item(self)
assert lineno is not None
Expand Down
6 changes: 2 additions & 4 deletions src/_pytest/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,7 @@ def on_rm_rf_error(
if func not in (os.open,):
warnings.warn(
PytestWarning(
"(rm_rf) unknown function {} when removing {}:\n{}: {}".format(
func, path, type(exc), exc
)
f"(rm_rf) unknown function {func} when removing {path}:\n{type(exc)}: {exc}"
)
)
return False
Expand Down Expand Up @@ -244,7 +242,7 @@ def make_numbered_dir(root: Path, prefix: str, mode: int = 0o700) -> Path:
else:
raise OSError(
"could not create numbered dir with prefix "
"{prefix} in {root} after 10 tries".format(prefix=prefix, root=root)
f"{prefix} in {root} after 10 tries"
)


Expand Down
12 changes: 4 additions & 8 deletions src/_pytest/pytester.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,9 +378,7 @@ def matchreport(
)
if len(values) > 1:
raise ValueError(
"found 2 or more testreports matching {!r}: {}".format(
inamepart, values
)
f"found 2 or more testreports matching {inamepart!r}: {values}"
)
return values[0]

Expand Down Expand Up @@ -1266,9 +1264,7 @@ def getitem(
for item in items:
if item.name == funcname:
return item
assert 0, "{!r} item not found in module:\n{}\nitems: {}".format(
funcname, source, items
)
assert 0, f"{funcname!r} item not found in module:\n{source}\nitems: {items}"

Check warning on line 1267 in src/_pytest/pytester.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/pytester.py#L1267

Added line #L1267 was not covered by tests

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

timeout_message = (
"{seconds} second timeout expired running:"
" {command}".format(seconds=timeout, command=cmdargs)
f"{timeout} second timeout expired running:"
f" {cmdargs}"
)

popen.kill()
Expand Down
Loading

0 comments on commit 791543b

Please sign in to comment.