[ruff] Add ruff's check and autofix existing issues

This commit is contained in:
Pierre Sassoulas 2024-02-02 14:49:15 +01:00
parent bdfc5c80d8
commit 514376fe29
19 changed files with 39 additions and 36 deletions

View File

@ -133,6 +133,7 @@ select = [
"F", # pyflakes "F", # pyflakes
"I", # isort "I", # isort
"UP", # pyupgrade "UP", # pyupgrade
"RUF", # ruff
"W", # pycodestyle "W", # pycodestyle
] ]
ignore = [ ignore = [
@ -156,6 +157,12 @@ ignore = [
"D402", # First line should not be the function's signature "D402", # First line should not be the function's signature
"D404", # First word of the docstring should not be "This" "D404", # First word of the docstring should not be "This"
"D415", # First line should end with a period, question mark, or exclamation point "D415", # First line should end with a period, question mark, or exclamation point
# ruff ignore
"RUF001", # String contains ambiguous character
"RUF003", # Comment contains ambiguous character
"RUF005", # Consider `(x, *y)` instead of concatenation
"RUF012", # Mutable class attributes should be annotated with `typing.ClassVar`
"RUF015", # Prefer `next(iter(x))` over single element slice
] ]
[tool.ruff.format] [tool.ruff.format]

View File

@ -1018,7 +1018,7 @@ class FormattedExcinfo:
extraline: Optional[str] = ( extraline: Optional[str] = (
"!!! Recursion error detected, but an error occurred locating the origin of recursion.\n" "!!! 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" " The following exception happened when comparing locals in the stack frame:\n"
f" {type(e).__name__}: {str(e)}\n" f" {type(e).__name__}: {e!s}\n"
f" Displaying first and last {max_frames} stack frames out of {len(traceback)}." f" Displaying first and last {max_frames} stack frames out of {len(traceback)}."
) )
# Type ignored because adding two instances of a List subtype # Type ignored because adding two instances of a List subtype

View File

@ -1105,9 +1105,7 @@ class LocalPath:
modname = self.purebasename modname = self.purebasename
spec = importlib.util.spec_from_file_location(modname, str(self)) spec = importlib.util.spec_from_file_location(modname, str(self))
if spec is None or spec.loader is None: if spec is None or spec.loader is None:
raise ImportError( raise ImportError(f"Can't find module {modname} at location {self!s}")
f"Can't find module {modname} at location {str(self)}"
)
mod = importlib.util.module_from_spec(spec) mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod) spec.loader.exec_module(mod)
return mod return mod

View File

@ -27,7 +27,7 @@ _S = TypeVar("_S")
# https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions # https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions
class NotSetType(enum.Enum): class NotSetType(enum.Enum):
token = 0 token = 0
NOTSET: Final = NotSetType.token # noqa: E305 NOTSET: Final = NotSetType.token
# fmt: on # fmt: on

View File

@ -671,7 +671,7 @@ class PytestPluginManager(PluginManager):
if dirpath in path.parents or path == dirpath: if dirpath in path.parents or path == dirpath:
if mod in mods: if mod in mods:
raise AssertionError( raise AssertionError(
f"While trying to load conftest path {str(conftestpath)}, " f"While trying to load conftest path {conftestpath!s}, "
f"found that the module {mod} is already loaded with path {mod.__file__}. " f"found that the module {mod} is already loaded with path {mod.__file__}. "
"This is not supposed to happen. Please report this issue to pytest." "This is not supposed to happen. Please report this issue to pytest."
) )

View File

@ -1225,7 +1225,7 @@ def fixture(
@overload @overload
def fixture( # noqa: F811 def fixture(
fixture_function: None = ..., fixture_function: None = ...,
*, *,
scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ..., scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ...,
@ -1239,7 +1239,7 @@ def fixture( # noqa: F811
... ...
def fixture( # noqa: F811 def fixture(
fixture_function: Optional[FixtureFunction] = None, fixture_function: Optional[FixtureFunction] = None,
*, *,
scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = "function", scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = "function",
@ -1673,7 +1673,7 @@ class FixtureManager:
raise NotImplementedError() raise NotImplementedError()
@overload @overload
def parsefactories( # noqa: F811 def parsefactories(
self, self,
node_or_obj: object, node_or_obj: object,
nodeid: Optional[str], nodeid: Optional[str],
@ -1682,7 +1682,7 @@ class FixtureManager:
) -> None: ) -> None:
raise NotImplementedError() raise NotImplementedError()
def parsefactories( # noqa: F811 def parsefactories(
self, self,
node_or_obj: Union[nodes.Node, object], node_or_obj: Union[nodes.Node, object],
nodeid: Union[str, NotSetType, None] = NOTSET, nodeid: Union[str, NotSetType, None] = NOTSET,

View File

@ -375,7 +375,7 @@ def record_testsuite_property(request: FixtureRequest) -> Callable[[str, object]
xml = request.config.stash.get(xml_key, None) xml = request.config.stash.get(xml_key, None)
if xml is not None: if xml is not None:
record_func = xml.add_global_property # noqa record_func = xml.add_global_property
return record_func return record_func

View File

@ -726,12 +726,12 @@ class Session(nodes.Collector):
... ...
@overload @overload
def perform_collect( # noqa: F811 def perform_collect(
self, args: Optional[Sequence[str]] = ..., genitems: bool = ... self, args: Optional[Sequence[str]] = ..., genitems: bool = ...
) -> Sequence[Union[nodes.Item, nodes.Collector]]: ) -> Sequence[Union[nodes.Item, nodes.Collector]]:
... ...
def perform_collect( # noqa: F811 def perform_collect(
self, args: Optional[Sequence[str]] = None, genitems: bool = True self, args: Optional[Sequence[str]] = None, genitems: bool = True
) -> Sequence[Union[nodes.Item, nodes.Collector]]: ) -> Sequence[Union[nodes.Item, nodes.Collector]]:
"""Perform the collection phase for this session. """Perform the collection phase for this session.

View File

@ -406,7 +406,7 @@ def normalize_mark_list(
for mark in mark_list: for mark in mark_list:
mark_obj = getattr(mark, "mark", mark) mark_obj = getattr(mark, "mark", mark)
if not isinstance(mark_obj, Mark): if not isinstance(mark_obj, Mark):
raise TypeError(f"got {repr(mark_obj)} instead of Mark") raise TypeError(f"got {mark_obj!r} instead of Mark")
yield mark_obj yield mark_obj

View File

@ -358,7 +358,7 @@ class PyobjMixin(nodes.Node):
# hook is not called for them. # hook is not called for them.
# fmt: off # fmt: off
class _EmptyClass: pass # noqa: E701 class _EmptyClass: pass # noqa: E701
IGNORED_ATTRIBUTES = frozenset.union( # noqa: E305 IGNORED_ATTRIBUTES = frozenset.union(
frozenset(), frozenset(),
# Module. # Module.
dir(types.ModuleType("empty_module")), dir(types.ModuleType("empty_module")),

View File

@ -730,7 +730,7 @@ def approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:
# Type ignored because the error is wrong -- not unreachable. # Type ignored because the error is wrong -- not unreachable.
and not isinstance(expected, STRING_TYPES) # type: ignore[unreachable] and not isinstance(expected, STRING_TYPES) # type: ignore[unreachable]
): ):
msg = f"pytest.approx() only supports ordered sequences, but got: {repr(expected)}" msg = f"pytest.approx() only supports ordered sequences, but got: {expected!r}"
raise TypeError(msg) raise TypeError(msg)
else: else:
cls = ApproxScalar cls = ApproxScalar
@ -780,7 +780,7 @@ def raises(
@overload @overload
def raises( # noqa: F811 def raises(
expected_exception: Union[Type[E], Tuple[Type[E], ...]], expected_exception: Union[Type[E], Tuple[Type[E], ...]],
func: Callable[..., Any], func: Callable[..., Any],
*args: Any, *args: Any,
@ -789,7 +789,7 @@ def raises( # noqa: F811
... ...
def raises( # noqa: F811 def raises(
expected_exception: Union[Type[E], Tuple[Type[E], ...]], *args: Any, **kwargs: Any expected_exception: Union[Type[E], Tuple[Type[E], ...]], *args: Any, **kwargs: Any
) -> Union["RaisesContext[E]", _pytest._code.ExceptionInfo[E]]: ) -> Union["RaisesContext[E]", _pytest._code.ExceptionInfo[E]]:
r"""Assert that a code block/function call raises an exception type, or one of its subclasses. r"""Assert that a code block/function call raises an exception type, or one of its subclasses.

View File

@ -47,13 +47,11 @@ def deprecated_call(
@overload @overload
def deprecated_call( # noqa: F811 def deprecated_call(func: Callable[..., T], *args: Any, **kwargs: Any) -> T:
func: Callable[..., T], *args: Any, **kwargs: Any
) -> T:
... ...
def deprecated_call( # noqa: F811 def deprecated_call(
func: Optional[Callable[..., Any]] = None, *args: Any, **kwargs: Any func: Optional[Callable[..., Any]] = None, *args: Any, **kwargs: Any
) -> Union["WarningsRecorder", Any]: ) -> Union["WarningsRecorder", Any]:
"""Assert that code produces a ``DeprecationWarning`` or ``PendingDeprecationWarning`` or ``FutureWarning``. """Assert that code produces a ``DeprecationWarning`` or ``PendingDeprecationWarning`` or ``FutureWarning``.
@ -97,7 +95,7 @@ def warns(
@overload @overload
def warns( # noqa: F811 def warns(
expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]],
func: Callable[..., T], func: Callable[..., T],
*args: Any, *args: Any,
@ -106,7 +104,7 @@ def warns( # noqa: F811
... ...
def warns( # noqa: F811 def warns(
expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = Warning, expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = Warning,
*args: Any, *args: Any,
match: Optional[Union[str, Pattern[str]]] = None, match: Optional[Union[str, Pattern[str]]] = None,

View File

@ -17,7 +17,7 @@ import pytest
def ignore_encoding_warning(): def ignore_encoding_warning():
with warnings.catch_warnings(): with warnings.catch_warnings():
with contextlib.suppress(NameError): # new in 3.10 with contextlib.suppress(NameError): # new in 3.10
warnings.simplefilter("ignore", EncodingWarning) # type: ignore [name-defined] # noqa: F821 warnings.simplefilter("ignore", EncodingWarning) # type: ignore [name-defined]
yield yield

View File

@ -1032,7 +1032,7 @@ def test_log_set_path(pytester: Pytester) -> None:
def pytest_runtest_setup(item): def pytest_runtest_setup(item):
config = item.config config = item.config
logging_plugin = config.pluginmanager.get_plugin("logging-plugin") logging_plugin = config.pluginmanager.get_plugin("logging-plugin")
report_file = os.path.join({repr(report_dir_base)}, item._request.node.name) report_file = os.path.join({report_dir_base!r}, item._request.node.name)
logging_plugin.set_log_path(report_file) logging_plugin.set_log_path(report_file)
return (yield) return (yield)
""" """

View File

@ -3086,7 +3086,7 @@ class TestFixtureMarker:
def test_other(): def test_other():
pass pass
""" # noqa: UP031 (python syntax issues) """ # noqa: UP031 (python syntax issues)
% {"scope": scope} # noqa: UP031 (python syntax issues) % {"scope": scope}
) )
reprec = pytester.inline_run("-lvs") reprec = pytester.inline_run("-lvs")
reprec.assertoutcome(passed=3) reprec.assertoutcome(passed=3)

View File

@ -147,7 +147,7 @@ class TestRaises:
try: try:
pytest.raises(ValueError, int, "0") pytest.raises(ValueError, int, "0")
except pytest.fail.Exception as e: except pytest.fail.Exception as e:
assert e.msg == f"DID NOT RAISE {repr(ValueError)}" assert e.msg == f"DID NOT RAISE {ValueError!r}"
else: else:
assert False, "Expected pytest.raises.Exception" assert False, "Expected pytest.raises.Exception"
@ -155,7 +155,7 @@ class TestRaises:
with pytest.raises(ValueError): with pytest.raises(ValueError):
pass pass
except pytest.fail.Exception as e: except pytest.fail.Exception as e:
assert e.msg == f"DID NOT RAISE {repr(ValueError)}" assert e.msg == f"DID NOT RAISE {ValueError!r}"
else: else:
assert False, "Expected pytest.raises.Exception" assert False, "Expected pytest.raises.Exception"

View File

@ -914,16 +914,16 @@ class TestAssert_reprcompare:
assert expl == [ assert expl == [
r"'hyv\xe4' == 'hyva\u0308'", r"'hyv\xe4' == 'hyva\u0308'",
"", "",
f"- {str(right)}", f"- {right!s}",
f"+ {str(left)}", f"+ {left!s}",
] ]
expl = callequal(left, right, verbose=2) expl = callequal(left, right, verbose=2)
assert expl == [ assert expl == [
r"'hyv\xe4' == 'hyva\u0308'", r"'hyv\xe4' == 'hyva\u0308'",
"", "",
f"- {str(right)}", f"- {right!s}",
f"+ {str(left)}", f"+ {left!s}",
] ]

View File

@ -190,7 +190,7 @@ class TestDoctests:
) )
doctest = f""" doctest = f"""
>>> "{test_string}" >>> "{test_string}"
{repr(test_string)} {test_string!r}
""" """
fn = pytester.path / "test_encoding.txt" fn = pytester.path / "test_encoding.txt"
fn.write_text(doctest, encoding=encoding) fn.write_text(doctest, encoding=encoding)

View File

@ -227,7 +227,7 @@ class TestInlineRunModulesCleanup:
def spy_factory(self): def spy_factory(self):
class SysModulesSnapshotSpy: class SysModulesSnapshotSpy:
instances: List["SysModulesSnapshotSpy"] = [] # noqa: F821 instances: List["SysModulesSnapshotSpy"] = []
def __init__(self, preserve=None) -> None: def __init__(self, preserve=None) -> None:
SysModulesSnapshotSpy.instances.append(self) SysModulesSnapshotSpy.instances.append(self)
@ -725,7 +725,7 @@ def test_run_result_repr() -> None:
# known exit code # known exit code
r = pytester_mod.RunResult(1, outlines, errlines, duration=0.5) r = pytester_mod.RunResult(1, outlines, errlines, duration=0.5)
assert repr(r) == ( assert repr(r) == (
f"<RunResult ret={str(pytest.ExitCode.TESTS_FAILED)} len(stdout.lines)=3" f"<RunResult ret={pytest.ExitCode.TESTS_FAILED!s} len(stdout.lines)=3"
" len(stderr.lines)=4 duration=0.50s>" " len(stderr.lines)=4 duration=0.50s>"
) )