Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ruff rules PT for pytest #2372

Merged
merged 2 commits into from
Feb 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ lint.select = [
"PIE",
"PLC",
"PLE",
"PT",
"RUF",
"S",
"UP",
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def test_check_file_with_changes(capsys, imperfect) -> None:


def test_sorted_imports_multiple_configs() -> None:
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="You can either specify custom configuration options"):
api.sort_code_string("import os", config=Config(line_length=80), line_length=80)


Expand Down
3 changes: 2 additions & 1 deletion tests/unit/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ def test_colored_printer_diff_output(capsys):
def test_colorama_not_available_handled_gracefully(capsys):
with pytest.raises(SystemExit) as system_exit:
_ = isort.format.create_terminal_printer(color=True)
assert system_exit.value.code and int(system_exit.value.code) > 0
assert system_exit.value.code
assert int(system_exit.value.code) > 0
_, err = capsys.readouterr()
assert "colorama" in err
assert "colors extra" in err
Expand Down
12 changes: 6 additions & 6 deletions tests/unit/test_isort.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ def test_line_length() -> None:
test_input = (
"from .test import a_very_long_function_name_that_exceeds_the_normal_pep8_line_length\n"
)
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="wrap_length must be set lower than or equal to line_le"):
test_output = isort.code(code=REALLY_LONG_IMPORT, line_length=80, wrap_length=99)
assert (
isort.code(REALLY_LONG_IMPORT, line_length=100, wrap_length=99)
Expand Down Expand Up @@ -3777,7 +3777,7 @@ def test_argument_parsing() -> None:
assert args["only_sections"] is True


@pytest.mark.parametrize("multiprocess", (False, True))
@pytest.mark.parametrize("multiprocess", [False, True])
def test_command_line(tmpdir, capfd, multiprocess: bool) -> None:
from isort.main import main

Expand Down Expand Up @@ -3805,7 +3805,7 @@ def test_command_line(tmpdir, capfd, multiprocess: bool) -> None:
assert str(tmpdir.join("file2.py")) in out


@pytest.mark.parametrize("quiet", (False, True))
@pytest.mark.parametrize("quiet", [False, True])
def test_quiet(tmpdir, capfd, quiet: bool) -> None:
if sys.platform.startswith("win"):
return
Expand All @@ -3822,7 +3822,7 @@ def test_quiet(tmpdir, capfd, quiet: bool) -> None:
assert bool(out) != quiet


@pytest.mark.parametrize("enabled", (False, True))
@pytest.mark.parametrize("enabled", [False, True])
def test_safety_skips(tmpdir, enabled: bool) -> None:
tmpdir.join("victim.py").write("# ...")
toxdir = tmpdir.mkdir(".tox")
Expand Down Expand Up @@ -3864,11 +3864,11 @@ def test_safety_skips(tmpdir, enabled: bool) -> None:

@pytest.mark.parametrize(
"skip_glob_assert",
(
[
([], 0, {os.sep.join(("code", "file.py"))}),
(["**/*.py"], 1, set()),
(["*/code/*.py"], 1, set()),
),
],
)
def test_skip_glob(tmpdir, skip_glob_assert: Tuple[List[str], int, Set[str]]) -> None:
skip_glob, skipped_count, file_names_expected = skip_glob_assert
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_literal.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def test_invalid_syntax():


def test_invalid_sort_type():
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="Trying to sort using an undefined sort_type. Defined"):
isort.literal.assignment("x = [1, 2, 3", "tuple-list-not-exist", "py")


Expand Down
12 changes: 8 additions & 4 deletions tests/unit/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -1102,12 +1102,14 @@ def main_check(args):
(tmp_path / "no_imports.py").write_text("...")

out, error = main_check([str(python_file), "--skip-gitignore", "--filter-files", "--check"])
assert "has_imports.py" in error and "no_imports.py" not in error
assert "has_imports.py" in error
assert "no_imports.py" not in error

(tmp_path / ".gitignore").write_text("has_imports.py")

out, error = main_check([str(python_file), "--check"])
assert "has_imports.py" in error and "no_imports.py" not in error
assert "has_imports.py" in error
assert "no_imports.py" not in error

out, error = main_check([str(python_file), "--skip-gitignore", "--filter-files", "--check"])
assert "Skipped" in out
Expand All @@ -1119,14 +1121,16 @@ def main_check(args):
subfolder_file.write_text(import_content)

out, error = main_check([str(tmp_path), "--skip-gitignore", "--filter-files", "--check"])
assert "has_imports.py" in error and "nested_dir/has_imports.py" not in error
assert "has_imports.py" in error
assert "nested_dir/has_imports.py" not in error

# Should work with relative path
currentdir = os.getcwd()
os.chdir(tmp_path)

out, error = main_check([".", "--skip-gitignore", "--filter-files", "--check"])
assert "has_imports.py" in error and "nested_dir/has_imports.py" not in error
assert "has_imports.py" in error
assert "nested_dir/has_imports.py" not in error

(tmp_path / ".gitignore").write_text(
"""
Expand Down
10 changes: 5 additions & 5 deletions tests/unit/test_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ def test_fuzz_skip_line(line, in_quote, index, section_comments, needs_import):


@pytest.mark.parametrize(
"raw_line, expected",
(
("raw_line", "expected"),
[
("from . cimport a", "from . cimport a"),
("from.cimport a", "from . cimport a"),
("from..cimport a", "from .. cimport a"),
Expand All @@ -95,14 +95,14 @@ def test_fuzz_skip_line(line, in_quote, index, section_comments, needs_import):
("from..import a", "from .. import a"),
("import *", "import *"),
("import*", "import *"),
("from . import a", "from . import a"),
("from . import a", "from . import a"), # noqa: PT014
("from .import a", "from . import a"),
("from ..import a", "from .. import a"),
("from . cimport a", "from . cimport a"),
("from . cimport a", "from . cimport a"), # noqa: PT014
("from .cimport a", "from . cimport a"),
("from ..cimport a", "from .. cimport a"),
("from\t.\timport a", "from . import a"),
),
],
)
def test_normalize_line(raw_line, expected):
line, returned_raw_line = parse.normalize_line(raw_line)
Expand Down
22 changes: 12 additions & 10 deletions tests/unit/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,9 @@ def test_init(self):
def test_init_unsupported_settings_fails_gracefully(self):
with pytest.raises(exceptions.UnsupportedSettings):
Config(apply=True)
try:
with pytest.raises(exceptions.UnsupportedSettings) as error:
Config(apply=True)
except exceptions.UnsupportedSettings as error:
assert error.unsupported_settings == {"apply": {"value": True, "source": "runtime"}}
assert error.value.unsupported_settings == {"apply": {"value": True, "source": "runtime"}}

def test_known_settings(self):
assert Config(known_third_party=["one"]).known_third_party == frozenset({"one"})
Expand All @@ -35,7 +34,7 @@ def test_invalid_settings_path(self):
Config(settings_path="this_couldnt_possibly_actually_exists/could_it")

def test_invalid_pyversion(self):
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="The python version 10 is not supported."):
Config(py_version=10)

def test_invalid_profile(self):
Expand Down Expand Up @@ -222,11 +221,11 @@ def test_as_bool():
assert settings._as_bool("FALSE") is False
assert settings._as_bool("faLSE") is False
assert settings._as_bool("f") is False
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="invalid truth value"):
settings._as_bool("")
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="invalid truth value falsey"):
settings._as_bool("falsey")
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="invalid truth value truthy"):
settings._as_bool("truthy")


Expand Down Expand Up @@ -277,15 +276,18 @@ def test_find_all_configs(tmpdir):

config_info_1 = config_trie.search(str(dir1 / "test1.py"))
assert config_info_1[0] == str(setup_cfg_file)
assert config_info_1[0] == str(setup_cfg_file) and config_info_1[1]["profile"] == "django"
assert config_info_1[0] == str(setup_cfg_file)
assert config_info_1[1]["profile"] == "django"

config_info_2 = config_trie.search(str(dir2 / "test2.py"))
assert config_info_2[0] == str(pyproject_toml_file)
assert config_info_2[0] == str(pyproject_toml_file) and config_info_2[1]["profile"] == "hug"
assert config_info_2[0] == str(pyproject_toml_file)
assert config_info_2[1]["profile"] == "hug"

config_info_3 = config_trie.search(str(dir3 / "test3.py"))
assert config_info_3[0] == str(isort_cfg_file)
assert config_info_3[0] == str(isort_cfg_file) and config_info_3[1]["profile"] == "black"
assert config_info_3[0] == str(isort_cfg_file)
assert config_info_3[1]["profile"] == "black"

config_info_4 = config_trie.search(str(tmpdir / "file4.py"))
assert config_info_4[0] == "default"
6 changes: 3 additions & 3 deletions tests/unit/test_wrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ def test_import_statement():


@pytest.mark.parametrize(
"multi_line_output, expected",
(
("multi_line_output", "expected"),
[
(
WrapModes.VERTICAL_HANGING_INDENT, # type: ignore
"""from a import (
Expand All @@ -35,7 +35,7 @@ def test_import_statement():
"""from a import (
b as c) # comment that is long enough that this import doesn't fit in one line (parens)""",
),
),
],
)
def test_line__comment_with_brackets__expects_unchanged_comment(multi_line_output, expected):
content = (
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/test_wrap_modes.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ def test_backslash_grid():
)


@pytest.mark.parametrize("include_trailing_comma", (False, True))
@pytest.mark.parametrize("line_length", (18, 19))
@pytest.mark.parametrize("multi_line_output", (4, 5))
@pytest.mark.parametrize("include_trailing_comma", [False, True])
@pytest.mark.parametrize("line_length", [18, 19])
@pytest.mark.parametrize("multi_line_output", [4, 5])
def test_vertical_grid_size_near_line_length(
multi_line_output: int,
line_length: int,
Expand Down Expand Up @@ -259,7 +259,7 @@ def test_fuzz_hanging_indent(
reject()


@pytest.mark.parametrize("include_trailing_comma", (True, False))
@pytest.mark.parametrize("include_trailing_comma", [True, False])
def test_hanging_indent__with_include_trailing_comma__expect_same_result(include_trailing_comma):
result = isort.wrap_modes.hanging_indent(
statement="from datetime import ",
Expand Down