diff options
author | Daniƫl van Noord <13665637+DanielNoord@users.noreply.github.com> | 2021-09-04 18:52:55 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-09-04 18:52:55 +0200 |
commit | 25000863761220c1aa5db129e3cd41f5fe51b167 (patch) | |
tree | d211e4464a8aef25f969adffe7ba7cb6df8b8981 /tests/lint | |
parent | 6c818310fd0e2396b6333ad623da577bf84e361e (diff) | |
download | pylint-git-25000863761220c1aa5db129e3cd41f5fe51b167.tar.gz |
Add typing with `PyAnnotate` to `./tests` (#4950)
* Add mypy_extensions to requirement for ``NoReturn``
Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
Diffstat (limited to 'tests/lint')
-rw-r--r-- | tests/lint/test_pylinter.py | 11 | ||||
-rw-r--r-- | tests/lint/test_utils.py | 6 | ||||
-rw-r--r-- | tests/lint/unittest_expand_modules.py | 4 | ||||
-rw-r--r-- | tests/lint/unittest_lint.py | 103 |
4 files changed, 69 insertions, 55 deletions
diff --git a/tests/lint/test_pylinter.py b/tests/lint/test_pylinter.py index f07531430..a1ea5351a 100644 --- a/tests/lint/test_pylinter.py +++ b/tests/lint/test_pylinter.py @@ -1,16 +1,23 @@ +from typing import Any from unittest.mock import patch +from _pytest.capture import CaptureFixture from astroid import AstroidBuildingError +from mypy_extensions import NoReturn +from py._path.local import LocalPath # type: ignore +from pylint.lint.pylinter import PyLinter from pylint.utils import FileState -def raise_exception(*args, **kwargs): +def raise_exception(*args: Any, **kwargs: Any) -> NoReturn: raise AstroidBuildingError(modname="spam") @patch.object(FileState, "iter_spurious_suppression_messages", raise_exception) -def test_crash_in_file(linter, capsys, tmpdir): +def test_crash_in_file( + linter: PyLinter, capsys: CaptureFixture, tmpdir: LocalPath +) -> None: args = linter.load_command_line_configuration([__file__]) linter.crash_file_path = str(tmpdir / "pylint-crash-%Y") linter.check(args) diff --git a/tests/lint/test_utils.py b/tests/lint/test_utils.py index 7fcdc5dec..80e7287f0 100644 --- a/tests/lint/test_utils.py +++ b/tests/lint/test_utils.py @@ -1,7 +1,9 @@ +from pathlib import PosixPath + from pylint.lint.utils import get_fatal_error_message, prepare_crash_report -def test_prepare_crash_report(tmp_path): +def test_prepare_crash_report(tmp_path: PosixPath) -> None: exception_content = "Exmessage" python_file = tmp_path / "myfile.py" python_content = "from shadok import MagicFaucet" @@ -22,7 +24,7 @@ def test_prepare_crash_report(tmp_path): assert "raise Exception(exception_content)" in template_content -def test_get_fatal_error_message(): +def test_get_fatal_error_message() -> None: python_path = "mypath.py" crash_path = "crash.txt" msg = get_fatal_error_message(python_path, crash_path) diff --git a/tests/lint/unittest_expand_modules.py b/tests/lint/unittest_expand_modules.py index f3ec8364f..ef98cf575 100644 --- a/tests/lint/unittest_expand_modules.py +++ b/tests/lint/unittest_expand_modules.py @@ -10,7 +10,7 @@ import pytest from pylint.lint.expand_modules import _is_in_ignore_list_re, expand_modules -def test__is_in_ignore_list_re_match(): +def test__is_in_ignore_list_re_match() -> None: patterns = [ re.compile(".*enchilada.*"), re.compile("unittest_.*"), @@ -21,7 +21,7 @@ def test__is_in_ignore_list_re_match(): assert _is_in_ignore_list_re("src/tests/whatever.xml", patterns) -def test__is_in_ignore_list_re_nomatch(): +def test__is_in_ignore_list_re_nomatch() -> None: patterns = [ re.compile(".*enchilada.*"), re.compile("unittest_.*"), diff --git a/tests/lint/unittest_lint.py b/tests/lint/unittest_lint.py index 110a2061c..18656ad74 100644 --- a/tests/lint/unittest_lint.py +++ b/tests/lint/unittest_lint.py @@ -48,9 +48,11 @@ from io import StringIO from os import chdir, getcwd from os.path import abspath, basename, dirname, isdir, join, sep from shutil import rmtree +from typing import Iterable, Iterator, List, Optional, Tuple import platformdirs import pytest +from _pytest.capture import CaptureFixture from pylint import checkers, config, exceptions, interfaces, lint, testutils from pylint.checkers.utils import check_messages @@ -78,7 +80,7 @@ else: @contextmanager -def fake_home(): +def fake_home() -> Iterator: folder = tempfile.mkdtemp("fake-home") old_home = os.environ.get(HOME) try: @@ -107,7 +109,7 @@ DATA_DIR = join(HERE, "..", "data") @contextmanager -def tempdir(): +def tempdir() -> Iterator[str]: """Create a temp directory and change the current location to it. This is supposed to be used with a *with* statement. @@ -126,7 +128,7 @@ def tempdir(): rmtree(abs_tmp) -def create_files(paths, chroot="."): +def create_files(paths: List[str], chroot: str = ".") -> None: """Creates directories and files found in <path>. :param list paths: list of relative paths to files or directories @@ -165,15 +167,15 @@ def create_files(paths, chroot="."): @pytest.fixture -def fake_path(): +def fake_path() -> Iterator[Iterable[str]]: orig = list(sys.path) - fake = [1, 2, 3] + fake: Iterable[str] = ["1", "2", "3"] sys.path[:] = fake yield fake sys.path[:] = orig -def test_no_args(fake_path): +def test_no_args(fake_path: List[int]) -> None: with lint.fix_import_path([]): assert sys.path == fake_path assert sys.path == fake_path @@ -182,7 +184,7 @@ def test_no_args(fake_path): @pytest.mark.parametrize( "case", [["a/b/"], ["a/b"], ["a/b/__init__.py"], ["a/"], ["a"]] ) -def test_one_arg(fake_path, case): +def test_one_arg(fake_path: List[str], case: List[str]) -> None: with tempdir() as chroot: create_files(["a/b/__init__.py"]) expected = [join(chroot, "a")] + fake_path @@ -246,14 +248,14 @@ def reporter(): @pytest.fixture -def init_linter(linter): +def init_linter(linter: PyLinter) -> PyLinter: linter.open() linter.set_current_module("toto") linter.file_state = FileState("toto") return linter -def test_pylint_visit_method_taken_in_account(linter): +def test_pylint_visit_method_taken_in_account(linter: PyLinter) -> None: class CustomChecker(checkers.BaseChecker): __implements__ = interfaces.IAstroidChecker name = "custom" @@ -270,7 +272,7 @@ def test_pylint_visit_method_taken_in_account(linter): linter.check("abc") -def test_enable_message(init_linter): +def test_enable_message(init_linter: PyLinter) -> None: linter = init_linter assert linter.is_message_enabled("W0101") assert linter.is_message_enabled("W0102") @@ -287,7 +289,7 @@ def test_enable_message(init_linter): assert linter.is_message_enabled("W0102", 1) -def test_enable_message_category(init_linter): +def test_enable_message_category(init_linter: PyLinter) -> None: linter = init_linter assert linter.is_message_enabled("W0101") assert linter.is_message_enabled("C0202") @@ -306,7 +308,7 @@ def test_enable_message_category(init_linter): assert linter.is_message_enabled("C0202", line=1) -def test_message_state_scope(init_linter): +def test_message_state_scope(init_linter: PyLinter) -> None: class FakeConfig: confidence = ["HIGH"] @@ -324,7 +326,7 @@ def test_message_state_scope(init_linter): ) -def test_enable_message_block(init_linter): +def test_enable_message_block(init_linter: PyLinter) -> None: linter = init_linter linter.open() filepath = join(REGRTEST_DATA_DIR, "func_block_disable_msg.py") @@ -382,7 +384,7 @@ def test_enable_message_block(init_linter): assert fs._suppression_mapping["E1101", 110] == 109 -def test_enable_by_symbol(init_linter): +def test_enable_by_symbol(init_linter: PyLinter) -> None: """messages can be controlled by symbolic names. The state is consistent across symbols and numbers. @@ -411,7 +413,7 @@ def test_enable_by_symbol(init_linter): assert linter.is_message_enabled("dangerous-default-value", 1) -def test_enable_report(linter): +def test_enable_report(linter: PyLinter) -> None: assert linter.report_is_enabled("RP0001") linter.disable("RP0001") assert not linter.report_is_enabled("RP0001") @@ -419,19 +421,19 @@ def test_enable_report(linter): assert linter.report_is_enabled("RP0001") -def test_report_output_format_aliased(linter): +def test_report_output_format_aliased(linter: PyLinter) -> None: text.register(linter) linter.set_option("output-format", "text") assert linter.reporter.__class__.__name__ == "TextReporter" -def test_set_unsupported_reporter(linter): +def test_set_unsupported_reporter(linter: PyLinter) -> None: text.register(linter) with pytest.raises(exceptions.InvalidReporterError): linter.set_option("output-format", "missing.module.Class") -def test_set_option_1(linter): +def test_set_option_1(linter: PyLinter) -> None: linter.set_option("disable", "C0111,W0234") assert not linter.is_message_enabled("C0111") assert not linter.is_message_enabled("W0234") @@ -440,7 +442,7 @@ def test_set_option_1(linter): assert not linter.is_message_enabled("non-iterator-returned") -def test_set_option_2(linter): +def test_set_option_2(linter: PyLinter) -> None: linter.set_option("disable", ("C0111", "W0234")) assert not linter.is_message_enabled("C0111") assert not linter.is_message_enabled("W0234") @@ -449,14 +451,14 @@ def test_set_option_2(linter): assert not linter.is_message_enabled("non-iterator-returned") -def test_enable_checkers(linter): +def test_enable_checkers(linter: PyLinter) -> None: linter.disable("design") assert not ("design" in [c.name for c in linter.prepare_checkers()]) linter.enable("design") assert "design" in [c.name for c in linter.prepare_checkers()] -def test_errors_only(linter): +def test_errors_only(linter: PyLinter) -> None: linter.error_mode() checkers = linter.prepare_checkers() checker_names = {c.name for c in checkers} @@ -464,13 +466,13 @@ def test_errors_only(linter): assert set() == should_not & checker_names -def test_disable_similar(linter): +def test_disable_similar(linter: PyLinter) -> None: linter.set_option("disable", "RP0801") linter.set_option("disable", "R0801") assert not ("similarities" in [c.name for c in linter.prepare_checkers()]) -def test_disable_alot(linter): +def test_disable_alot(linter: PyLinter) -> None: """check that we disabled a lot of checkers""" linter.set_option("reports", False) linter.set_option("disable", "R,C,W") @@ -479,7 +481,7 @@ def test_disable_alot(linter): assert not (cname in checker_names), cname -def test_addmessage(linter): +def test_addmessage(linter: PyLinter) -> None: linter.set_reporter(testutils.GenericTestReporter()) linter.open() linter.set_current_module("0123") @@ -491,7 +493,7 @@ def test_addmessage(linter): ] == linter.reporter.messages -def test_addmessage_invalid(linter): +def test_addmessage_invalid(linter: PyLinter) -> None: linter.set_reporter(testutils.GenericTestReporter()) linter.open() linter.set_current_module("0123") @@ -512,7 +514,7 @@ def test_addmessage_invalid(linter): assert str(cm.value) == "Message C0321 must provide Node, got None" -def test_load_plugin_command_line(): +def test_load_plugin_command_line() -> None: dummy_plugin_path = join(REGRTEST_DATA_DIR, "dummy_plugin") sys.path.append(dummy_plugin_path) @@ -528,7 +530,7 @@ def test_load_plugin_command_line(): sys.path.remove(dummy_plugin_path) -def test_load_plugin_config_file(): +def test_load_plugin_config_file() -> None: dummy_plugin_path = join(REGRTEST_DATA_DIR, "dummy_plugin") sys.path.append(dummy_plugin_path) config_path = join(REGRTEST_DATA_DIR, "dummy_plugin.rc") @@ -545,7 +547,7 @@ def test_load_plugin_config_file(): sys.path.remove(dummy_plugin_path) -def test_load_plugin_configuration(): +def test_load_plugin_configuration() -> None: dummy_plugin_path = join(REGRTEST_DATA_DIR, "dummy_plugin") sys.path.append(dummy_plugin_path) @@ -562,20 +564,20 @@ def test_load_plugin_configuration(): assert run.linter.config.black_list == ["foo", "bar", "bin"] -def test_init_hooks_called_before_load_plugins(): +def test_init_hooks_called_before_load_plugins() -> None: with pytest.raises(RuntimeError): Run(["--load-plugins", "unexistant", "--init-hook", "raise RuntimeError"]) with pytest.raises(RuntimeError): Run(["--init-hook", "raise RuntimeError", "--load-plugins", "unexistant"]) -def test_analyze_explicit_script(linter): +def test_analyze_explicit_script(linter: PyLinter) -> None: linter.set_reporter(testutils.GenericTestReporter()) linter.check(os.path.join(DATA_DIR, "ascript")) assert ["C: 2: Line too long (175/100)"] == linter.reporter.messages -def test_full_documentation(linter): +def test_full_documentation(linter: PyLinter) -> None: out = StringIO() linter.print_full_documentation(out) output = out.getvalue() @@ -593,7 +595,7 @@ def test_full_documentation(linter): assert re.search(regexp, output) -def test_list_msgs_enabled(init_linter, capsys): +def test_list_msgs_enabled(init_linter: PyLinter, capsys: CaptureFixture) -> None: linter = init_linter linter.enable("W0101", scope="package") linter.disable("W0102", scope="package") @@ -616,12 +618,12 @@ def test_list_msgs_enabled(init_linter, capsys): @pytest.fixture -def pop_pylintrc(): +def pop_pylintrc() -> None: os.environ.pop("PYLINTRC", None) @pytest.mark.usefixtures("pop_pylintrc") -def test_pylint_home(): +def test_pylint_home() -> None: uhome = os.path.expanduser("~") if uhome == "~": expected = ".pylint.d" @@ -645,7 +647,7 @@ def test_pylint_home(): @pytest.mark.usefixtures("pop_pylintrc") -def test_pylintrc(): +def test_pylintrc() -> None: with fake_home(): current_dir = getcwd() chdir(os.path.dirname(os.path.abspath(sys.executable))) @@ -661,7 +663,7 @@ def test_pylintrc(): @pytest.mark.usefixtures("pop_pylintrc") -def test_pylintrc_parentdir(): +def test_pylintrc_parentdir() -> None: with tempdir() as chroot: create_files( @@ -689,7 +691,7 @@ def test_pylintrc_parentdir(): @pytest.mark.usefixtures("pop_pylintrc") -def test_pylintrc_parentdir_no_package(): +def test_pylintrc_parentdir_no_package() -> None: with tempdir() as chroot: with fake_home(): create_files(["a/pylintrc", "a/b/pylintrc", "a/b/c/d/__init__.py"]) @@ -706,31 +708,31 @@ def test_pylintrc_parentdir_no_package(): class TestPreprocessOptions: - def _callback(self, name, value): + def _callback(self, name: str, value: Optional[str]) -> None: self.args.append((name, value)) - def test_value_equal(self): - self.args = [] + def test_value_equal(self) -> None: + self.args: List[Tuple[str, Optional[str]]] = [] preprocess_options( ["--foo", "--bar=baz", "--qu=ux"], {"foo": (self._callback, False), "qu": (self._callback, True)}, ) assert [("foo", None), ("qu", "ux")] == self.args - def test_value_space(self): + def test_value_space(self) -> None: self.args = [] preprocess_options(["--qu", "ux"], {"qu": (self._callback, True)}) assert [("qu", "ux")] == self.args @staticmethod - def test_error_missing_expected_value(): + def test_error_missing_expected_value() -> None: with pytest.raises(ArgumentPreprocessingError): preprocess_options(["--foo", "--bar", "--qu=ux"], {"bar": (None, True)}) with pytest.raises(ArgumentPreprocessingError): preprocess_options(["--foo", "--bar"], {"bar": (None, True)}) @staticmethod - def test_error_unexpected_value(): + def test_error_unexpected_value() -> None: with pytest.raises(ArgumentPreprocessingError): preprocess_options( ["--foo", "--bar=spam", "--qu=ux"], {"bar": (None, False)} @@ -739,14 +741,17 @@ class TestPreprocessOptions: class _CustomPyLinter(PyLinter): # pylint: disable=too-many-ancestors - def should_analyze_file(self, modname, path, is_argument=False): + @staticmethod + def should_analyze_file(modname: str, path: str, is_argument: bool = False) -> bool: if os.path.basename(path) == "wrong.py": return False - return super().should_analyze_file(modname, path, is_argument=is_argument) + return super(_CustomPyLinter, _CustomPyLinter).should_analyze_file( + modname, path, is_argument=is_argument + ) -def test_custom_should_analyze_file(): +def test_custom_should_analyze_file() -> None: """Check that we can write custom should_analyze_file that work even for arguments. """ @@ -775,7 +780,7 @@ def test_custom_should_analyze_file(): # we do the check with jobs=1 as well, so that we are sure that the duplicates # are created by the multiprocessing problem. @pytest.mark.parametrize("jobs", [1, 2]) -def test_multiprocessing(jobs): +def test_multiprocessing(jobs: int) -> None: """Check that multiprocessing does not create duplicates.""" # For the bug (#3584) to show up we need more than one file with issues # per process @@ -804,7 +809,7 @@ def test_multiprocessing(jobs): assert len(messages) == len(set(messages)) -def test_filename_with__init__(init_linter): +def test_filename_with__init__(init_linter: PyLinter) -> None: # This tracks a regression where a file whose name ends in __init__.py, # such as flycheck__init__.py, would accidentally lead to linting the # entire containing directory. @@ -818,7 +823,7 @@ def test_filename_with__init__(init_linter): assert len(messages) == 0 -def test_by_module_statement_value(init_linter): +def test_by_module_statement_value(init_linter: PyLinter) -> None: """Test "statement" for each module analized of computed correctly.""" linter = init_linter linter.check(os.path.join(os.path.dirname(__file__), "data")) |