From fa54211da99f6c63dfe25249c2062ef6ba152bb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20van=20Noord?= <13665637+DanielNoord@users.noreply.github.com> Date: Thu, 14 Apr 2022 14:26:09 +0200 Subject: [PATCH 1/5] Use ``python-typing-update`` on half of the ``tests`` directory --- tests/pyreverse/conftest.py | 6 ++-- tests/pyreverse/test_diadefs.py | 12 ++++--- tests/pyreverse/test_diagrams.py | 5 ++- tests/pyreverse/test_inspector.py | 5 ++- tests/pyreverse/test_main.py | 6 +++- tests/pyreverse/test_printer.py | 6 ++-- tests/pyreverse/test_writer.py | 5 +-- tests/test_check_parallel.py | 11 ++++--- tests/test_func.py | 21 +++++++------ tests/test_functional.py | 10 +++--- tests/test_import_graph.py | 6 ++-- tests/test_pylint_runners.py | 11 ++++--- tests/test_regr.py | 16 ++++++---- tests/test_self.py | 31 ++++++++++--------- tests/test_similar.py | 11 ++++--- .../test_lint_module_output_update.py | 15 +++++---- tests/testutils/test_output_line.py | 6 ++-- tests/unittest_reporters_json.py | 6 ++-- tests/unittest_reporting.py | 7 +++-- tests/utils/unittest_ast_walker.py | 7 +++-- 20 files changed, 123 insertions(+), 80 deletions(-) diff --git a/tests/pyreverse/conftest.py b/tests/pyreverse/conftest.py index 52b9198836..d8b6ea9f44 100644 --- a/tests/pyreverse/conftest.py +++ b/tests/pyreverse/conftest.py @@ -2,7 +2,9 @@ # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt -from typing import Callable, Optional +from __future__ import annotations + +from collections.abc import Callable import pytest from astroid.nodes.scoped_nodes import Module @@ -65,7 +67,7 @@ def html_config() -> PyreverseConfig: @pytest.fixture(scope="session") def get_project() -> Callable: - def _get_project(module: str, name: Optional[str] = "No Name") -> Project: + def _get_project(module: str, name: str | None = "No Name") -> Project: """Return an astroid project representation.""" def _astroid_wrapper(func: Callable, modname: str) -> Module: diff --git a/tests/pyreverse/test_diadefs.py b/tests/pyreverse/test_diadefs.py index ecb601b0c6..059f756bcd 100644 --- a/tests/pyreverse/test_diadefs.py +++ b/tests/pyreverse/test_diadefs.py @@ -3,10 +3,14 @@ # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt """Unit test for the extensions.diadefslib modules.""" + # pylint: disable=redefined-outer-name + +from __future__ import annotations + import sys +from collections.abc import Callable from pathlib import Path -from typing import Callable, Dict, List, Tuple import pytest from astroid import nodes @@ -22,14 +26,14 @@ from pylint.testutils.pyreverse import PyreverseConfig -def _process_classes(classes: List[DiagramEntity]) -> List[Tuple[bool, str]]: +def _process_classes(classes: list[DiagramEntity]) -> list[tuple[bool, str]]: """Extract class names of a list.""" return sorted((isinstance(c.node, nodes.ClassDef), c.title) for c in classes) def _process_relations( - relations: Dict[str, List[Relationship]] -) -> List[Tuple[str, str, str]]: + relations: dict[str, list[Relationship]] +) -> list[tuple[str, str, str]]: """Extract relation indices from a relation list.""" result = [] for rel_type, rels in relations.items(): diff --git a/tests/pyreverse/test_diagrams.py b/tests/pyreverse/test_diagrams.py index f10af571db..b4a59a571c 100644 --- a/tests/pyreverse/test_diagrams.py +++ b/tests/pyreverse/test_diagrams.py @@ -3,7 +3,10 @@ # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt """Unit test for the diagrams modules.""" -from typing import Callable + +from __future__ import annotations + +from collections.abc import Callable from pylint.pyreverse.diadefslib import DefaultDiadefGenerator, DiadefsHandler from pylint.pyreverse.inspector import Linker diff --git a/tests/pyreverse/test_inspector.py b/tests/pyreverse/test_inspector.py index 8f053c1486..db0f4656a0 100644 --- a/tests/pyreverse/test_inspector.py +++ b/tests/pyreverse/test_inspector.py @@ -3,10 +3,13 @@ # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt """For the visitors.diadefs module.""" + # pylint: disable=redefined-outer-name +from __future__ import annotations + import os -from typing import Callable +from collections.abc import Callable import astroid import pytest diff --git a/tests/pyreverse/test_main.py b/tests/pyreverse/test_main.py index 072542c3a7..b5ea3fda90 100644 --- a/tests/pyreverse/test_main.py +++ b/tests/pyreverse/test_main.py @@ -3,9 +3,13 @@ # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt """Unittest for the main module.""" + +from __future__ import annotations + import os import sys -from typing import Any, Iterator +from collections.abc import Iterator +from typing import Any from unittest import mock import pytest diff --git a/tests/pyreverse/test_printer.py b/tests/pyreverse/test_printer.py index 9128fc6ddf..3822383db0 100644 --- a/tests/pyreverse/test_printer.py +++ b/tests/pyreverse/test_printer.py @@ -2,7 +2,7 @@ # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt -from typing import Type +from __future__ import annotations import pytest from astroid import nodes @@ -29,7 +29,7 @@ ], ) def test_explicit_layout( - layout: Layout, printer_class: Type[Printer], expected_content: str, line_index: int + layout: Layout, printer_class: type[Printer], expected_content: str, line_index: int ) -> None: printer = printer_class(title="unittest", layout=layout) assert printer.lines[line_index].strip() == expected_content @@ -39,7 +39,7 @@ def test_explicit_layout( "layout, printer_class", [(Layout.BOTTOM_TO_TOP, PlantUmlPrinter), (Layout.RIGHT_TO_LEFT, PlantUmlPrinter)], ) -def test_unsupported_layout(layout: Layout, printer_class: Type[Printer]): +def test_unsupported_layout(layout: Layout, printer_class: type[Printer]): with pytest.raises(ValueError): printer_class(title="unittest", layout=layout) diff --git a/tests/pyreverse/test_writer.py b/tests/pyreverse/test_writer.py index d3b2d8f448..a031050924 100644 --- a/tests/pyreverse/test_writer.py +++ b/tests/pyreverse/test_writer.py @@ -4,11 +4,12 @@ """Unit test for ``DiagramWriter``.""" +from __future__ import annotations import codecs import os +from collections.abc import Callable, Iterator from difflib import unified_diff -from typing import Callable, Iterator, List from unittest.mock import Mock import pytest @@ -53,7 +54,7 @@ def __init__(self): setattr(self, attr, value) -def _file_lines(path: str) -> List[str]: +def _file_lines(path: str) -> list[str]: # we don't care about the actual encoding, but python3 forces us to pick one with codecs.open(path, encoding="latin1") as stream: lines = [ diff --git a/tests/test_check_parallel.py b/tests/test_check_parallel.py index 898b02893d..7023c80b01 100644 --- a/tests/test_check_parallel.py +++ b/tests/test_check_parallel.py @@ -6,10 +6,11 @@ # pylint: disable=protected-access,missing-function-docstring,no-self-use +from __future__ import annotations + import argparse import multiprocessing import os -from typing import List import dill import pytest @@ -41,7 +42,7 @@ def _gen_file_data(idx: int = 0) -> FileItem: return file_data -def _gen_file_datas(count: int = 1) -> List[FileItem]: +def _gen_file_datas(count: int = 1) -> list[FileItem]: return [_gen_file_data(idx) for idx in range(count)] @@ -62,7 +63,7 @@ class SequentialTestChecker(BaseChecker): def __init__(self, linter: PyLinter) -> None: super().__init__(linter) - self.data: List[str] = [] + self.data: list[str] = [] self.linter = linter def process_module(self, _node: nodes.Module) -> None: @@ -101,7 +102,7 @@ class ParallelTestChecker(BaseChecker, MapReduceMixin): def __init__(self, linter: PyLinter) -> None: super().__init__(linter) - self.data: List[str] = [] + self.data: list[str] = [] self.linter = linter def open(self) -> None: @@ -116,7 +117,7 @@ def close(self) -> None: def get_map_data(self): return self.data - def reduce_map_data(self, linter: PyLinter, data: List[List[str]]) -> None: + def reduce_map_data(self, linter: PyLinter, data: list[list[str]]) -> None: recombined = type(self)(linter) recombined.open() aggregated = [] diff --git a/tests/test_func.py b/tests/test_func.py index 207c9b8c9b..de7ebbc54e 100644 --- a/tests/test_func.py +++ b/tests/test_func.py @@ -4,17 +4,18 @@ """Functional/non regression tests for pylint.""" +from __future__ import annotations + import re import sys -from os.path import abspath, dirname, join -from typing import List, Optional, Tuple +from os.path import dirname, join import pytest from pylint.testutils import UPDATE_FILE, UPDATE_OPTION, _get_tests_info, linter -INPUT_DIR = join(dirname(abspath(__file__)), "input") -MSG_DIR = join(dirname(abspath(__file__)), "messages") +INPUT_DIR = join(dirname(__file__), "input") +MSG_DIR = join(dirname(__file__), "messages") FILTER_RGX = None @@ -29,13 +30,13 @@ def exception_str(self, ex) -> str: # pylint: disable=unused-argument class LintTestUsingModule: - INPUT_DIR: Optional[str] = None + INPUT_DIR: str | None = None DEFAULT_PACKAGE = "input" package = DEFAULT_PACKAGE linter = linter - module: Optional[str] = None - depends: Optional[List[Tuple[str, str]]] = None - output: Optional[str] = None + module: str | None = None + depends: list[tuple[str, str]] | None = None + output: str | None = None def _test_functionality(self) -> None: if self.module: @@ -54,7 +55,7 @@ def _check_result(self, got: str) -> None: ) assert self._get_expected() == got, error_msg - def _test(self, tocheck: List[str]) -> None: + def _test(self, tocheck: list[str]) -> None: if self.module and INFO_TEST_RGX.match(self.module): self.linter.enable("I") else: @@ -137,7 +138,7 @@ def test_functionality( def __test_functionality( - module_file: str, messages_file: str, dependencies: List[Tuple[str, str]] + module_file: str, messages_file: str, dependencies: list[tuple[str, str]] ) -> None: lint_test = LintTestUpdate() if UPDATE_FILE.exists() else LintTestUsingModule() lint_test.module = module_file.replace(".py", "") diff --git a/tests/test_functional.py b/tests/test_functional.py index 14d2384d9f..a286e8f2a2 100644 --- a/tests/test_functional.py +++ b/tests/test_functional.py @@ -3,9 +3,11 @@ # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt """Functional full-module tests for PyLint.""" + +from __future__ import annotations + import sys from pathlib import Path -from typing import Union import pytest from _pytest.config import Config @@ -46,9 +48,9 @@ def test_functional( ) -> None: __tracebackhide__ = True # pylint: disable=unused-variable if UPDATE_FILE.exists(): - lint_test: Union[ - LintModuleOutputUpdate, testutils.LintModuleTest - ] = LintModuleOutputUpdate(test_file, pytestconfig) + lint_test: ( + LintModuleOutputUpdate | testutils.LintModuleTest + ) = LintModuleOutputUpdate(test_file, pytestconfig) else: lint_test = testutils.LintModuleTest(test_file, pytestconfig) lint_test.setUp() diff --git a/tests/test_import_graph.py b/tests/test_import_graph.py index 269370d54b..12b8ab3af8 100644 --- a/tests/test_import_graph.py +++ b/tests/test_import_graph.py @@ -4,10 +4,12 @@ # pylint: disable=redefined-outer-name +from __future__ import annotations + import os import shutil +from collections.abc import Iterator from os.path import exists -from typing import Iterator, Union import pytest from _pytest.fixtures import SubRequest @@ -18,7 +20,7 @@ @pytest.fixture -def dest(request: SubRequest) -> Iterator[Union[Iterator, Iterator[str]]]: +def dest(request: SubRequest) -> Iterator[Iterator | Iterator[str]]: dest = request.param yield dest try: diff --git a/tests/test_pylint_runners.py b/tests/test_pylint_runners.py index 303b433d35..a0e1a352bd 100644 --- a/tests/test_pylint_runners.py +++ b/tests/test_pylint_runners.py @@ -1,11 +1,12 @@ # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt - # pylint: disable=missing-module-docstring, missing-function-docstring -import os + +from __future__ import annotations + import sys -from typing import Callable +from collections.abc import Callable from unittest.mock import patch import pytest @@ -18,7 +19,7 @@ "runner", [run_epylint, run_pylint, run_pyreverse, run_symilar] ) def test_runner(runner: Callable, tmpdir: LocalPath) -> None: - filepath = os.path.abspath(__file__) + filepath = __file__ testargs = ["", filepath] with tmpdir.as_cwd(): with patch.object(sys, "argv", testargs): @@ -32,7 +33,7 @@ def test_runner(runner: Callable, tmpdir: LocalPath) -> None: ) def test_runner_with_arguments(runner: Callable, tmpdir: LocalPath) -> None: """Check the runners with arguments as parameter instead of sys.argv.""" - filepath = os.path.abspath(__file__) + filepath = __file__ testargs = [filepath] with tmpdir.as_cwd(): with pytest.raises(SystemExit) as err: diff --git a/tests/test_regr.py b/tests/test_regr.py index c795bf8131..de80d8cbd9 100644 --- a/tests/test_regr.py +++ b/tests/test_regr.py @@ -5,12 +5,16 @@ """Non regression tests for pylint, which requires a too specific configuration to be incorporated in the automatic functional test framework """ + # pylint: disable=redefined-outer-name +from __future__ import annotations + import os import sys -from os.path import abspath, dirname, join -from typing import Callable, Iterator, List, cast +from collections.abc import Callable, Iterator +from os.path import dirname, join +from typing import cast import astroid import pytest @@ -18,7 +22,7 @@ from pylint import testutils from pylint.lint.pylinter import PyLinter -REGR_DATA = join(dirname(abspath(__file__)), "regrtest_data") +REGR_DATA = join(dirname(__file__), "regrtest_data") sys.path.insert(1, REGR_DATA) @@ -63,7 +67,7 @@ def Equals(expected): ], ) def test_package( - finalize_linter: PyLinter, file_names: List[str], check: Callable + finalize_linter: PyLinter, file_names: list[str], check: Callable ) -> None: finalize_linter.check(file_names) finalize_linter.reporter = cast( # Due to fixture @@ -81,7 +85,7 @@ def test_package( [join(REGR_DATA, "try_finally_disable_msg_crash")], ], ) -def test_crash(finalize_linter: PyLinter, file_names: List[str]) -> None: +def test_crash(finalize_linter: PyLinter, file_names: list[str]) -> None: finalize_linter.check(file_names) @@ -142,5 +146,5 @@ def test_pylint_config_attr() -> None: @pytest.mark.timeout(30) @pytest.mark.parametrize("file_names", ([join(REGR_DATA, "hang", "pkg4972.string")],)) -def test_hang(finalize_linter: PyLinter, file_names: List[str]) -> None: +def test_hang(finalize_linter: PyLinter, file_names: list[str]) -> None: finalize_linter.check(file_names) diff --git a/tests/test_self.py b/tests/test_self.py index 24b564edea..a8a04d7730 100644 --- a/tests/test_self.py +++ b/tests/test_self.py @@ -4,6 +4,8 @@ # pylint: disable=too-many-public-methods +from __future__ import annotations + import configparser import contextlib import json @@ -14,11 +16,12 @@ import sys import textwrap import warnings +from collections.abc import Generator, Iterator from copy import copy from io import BytesIO, StringIO from os.path import abspath, dirname, join from pathlib import Path -from typing import TYPE_CHECKING, Any, Generator, Iterator, List, Optional, TextIO +from typing import TYPE_CHECKING, Any, TextIO from unittest import mock from unittest.mock import patch @@ -92,7 +95,7 @@ def _test_cwd() -> Generator[None, None, None]: class MultiReporter(BaseReporter): - def __init__(self, reporters: List[BaseReporter]) -> None: + def __init__(self, reporters: list[BaseReporter]) -> None: # pylint: disable=super-init-not-called # We don't call it because there is an attribute "linter" that is set inside the base class # and we have another setter here using yet undefined attribute. @@ -108,7 +111,7 @@ def handle_message(self, msg: Message) -> None: for rep in self._reporters: rep.handle_message(msg) - def _display(self, layout: "Section") -> None: + def _display(self, layout: Section) -> None: pass @property @@ -129,10 +132,10 @@ def linter(self, value: PyLinter) -> None: class TestRunTC: def _runtest( self, - args: List[str], + args: list[str], reporter: Any = None, - out: Optional[StringIO] = None, - code: Optional[int] = None, + out: StringIO | None = None, + code: int | None = None, ) -> None: if out is None: out = StringIO() @@ -149,7 +152,7 @@ def _runtest( assert pylint_code == code, msg @staticmethod - def _run_pylint(args: List[str], out: TextIO, reporter: Any = None) -> int: + def _run_pylint(args: list[str], out: TextIO, reporter: Any = None) -> int: args = args + ["--persistent=no"] with _patch_streams(out): with pytest.raises(SystemExit) as cm: @@ -164,7 +167,7 @@ def _clean_paths(output: str) -> str: output = re.sub(CLEAN_PATH, "", output, flags=re.MULTILINE) return output.replace("\\", "/") - def _test_output(self, args: List[str], expected_output: str) -> None: + def _test_output(self, args: list[str], expected_output: str) -> None: out = StringIO() self._run_pylint(args, out=out) actual_output = self._clean_paths(out.getvalue()) @@ -172,7 +175,7 @@ def _test_output(self, args: List[str], expected_output: str) -> None: assert expected_output.strip() in actual_output.strip() def _test_output_file( - self, args: List[str], filename: LocalPath, expected_output: str + self, args: list[str], filename: LocalPath, expected_output: str ) -> None: """Run Pylint with the ``output`` option set (must be included in the ``args`` passed to this method!) and check the file content afterwards. @@ -328,10 +331,8 @@ def test_json_report_when_file_has_syntax_error(self) -> None: # So each version wants a different column number... if platform.python_implementation() == "PyPy": column = 9 - elif sys.version_info >= (3, 8): - column = 9 else: - column = 15 + column = 9 expected = { "obj": "", "column": column, @@ -602,7 +603,7 @@ def test_stdin_syntaxerror(self) -> None: assert mock_stdin.call_count == 1 def test_version(self) -> None: - def check(lines: List[str]) -> None: + def check(lines: list[str]) -> None: assert lines[0].startswith("pylint ") assert lines[1].startswith("astroid ") assert lines[2].startswith("Python ") @@ -766,7 +767,7 @@ def test_fail_on_edge_case(self, opts, out): def test_modify_sys_path() -> None: @contextlib.contextmanager def test_environ_pythonpath( - new_pythonpath: Optional[str], + new_pythonpath: str | None, ) -> Generator[None, None, None]: original_pythonpath = os.environ.get("PYTHONPATH") if new_pythonpath: @@ -1289,7 +1290,7 @@ class TestCallbackOptions: (["--long-help"], "Environment variables:"), ], ) - def test_output_of_callback_options(command: List[str], expected: str) -> None: + def test_output_of_callback_options(command: list[str], expected: str) -> None: """Test whether certain strings are in the output of a callback command.""" process = subprocess.run( diff --git a/tests/test_similar.py b/tests/test_similar.py index f595102bca..2c258a0193 100644 --- a/tests/test_similar.py +++ b/tests/test_similar.py @@ -2,14 +2,17 @@ # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt +from __future__ import annotations + import contextlib import os import re import sys import warnings +from collections.abc import Iterator from io import StringIO from os.path import abspath, dirname, join -from typing import Iterator, List, TextIO +from typing import TextIO import pytest @@ -31,7 +34,7 @@ def _patch_streams(out: TextIO) -> Iterator: class TestSimilarCodeChecker: - def _runtest(self, args: List[str], code: int) -> None: + def _runtest(self, args: list[str], code: int) -> None: """Runs the tests and sees if output code is as expected.""" out = StringIO() pylint_code = self._run_pylint(args, out=out) @@ -42,7 +45,7 @@ def _runtest(self, args: List[str], code: int) -> None: assert pylint_code == code, msg @staticmethod - def _run_pylint(args: List[str], out: TextIO) -> int: + def _run_pylint(args: list[str], out: TextIO) -> int: """Runs pylint with a patched output.""" args = args + ["--persistent=no"] with _patch_streams(out): @@ -58,7 +61,7 @@ def _clean_paths(output: str) -> str: output = re.sub(CLEAN_PATH, "", output, flags=re.MULTILINE) return output.replace("\\", "/") - def _test_output(self, args: List[str], expected_output: str) -> None: + def _test_output(self, args: list[str], expected_output: str) -> None: """Tests if the output of a pylint run is as expected.""" out = StringIO() self._run_pylint(args, out=out) diff --git a/tests/testutils/test_lint_module_output_update.py b/tests/testutils/test_lint_module_output_update.py index 6d46f84b47..1c9e589af7 100644 --- a/tests/testutils/test_lint_module_output_update.py +++ b/tests/testutils/test_lint_module_output_update.py @@ -3,8 +3,11 @@ # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt # pylint: disable=redefined-outer-name + +from __future__ import annotations + +from collections.abc import Callable from pathlib import Path -from typing import Callable, Tuple import pytest @@ -16,8 +19,8 @@ @pytest.fixture() def lint_module_fixture( tmp_path: Path, -) -> Callable[[str], Tuple[Path, Path, LintModuleOutputUpdate]]: - def inner(base: str) -> Tuple[Path, Path, LintModuleOutputUpdate]: +) -> Callable[[str], tuple[Path, Path, LintModuleOutputUpdate]]: + def inner(base: str) -> tuple[Path, Path, LintModuleOutputUpdate]: filename = tmp_path / f"{base}.py" expected_output_file = tmp_path / f"{base}.txt" lmou = LintModuleOutputUpdate( @@ -38,7 +41,7 @@ def test_not_py38(tmp_path: Path) -> None: @pytest.mark.skipif(not PY38_PLUS, reason="Requires python 3.8 or superior") def test_lint_module_output_update_fail_before( - lint_module_fixture: Callable[[str], Tuple[Path, Path, LintModuleOutputUpdate]] + lint_module_fixture: Callable[[str], tuple[Path, Path, LintModuleOutputUpdate]] ) -> None: """There is a fail before the output need to be updated.""" filename, expected_output_file, lmou = lint_module_fixture("foo") @@ -51,7 +54,7 @@ def test_lint_module_output_update_fail_before( @pytest.mark.skipif(not PY38_PLUS, reason="Requires python 3.8 or superior") def test_lint_module_output_update_effective( - lint_module_fixture: Callable[[str], Tuple[Path, Path, LintModuleOutputUpdate]] + lint_module_fixture: Callable[[str], tuple[Path, Path, LintModuleOutputUpdate]] ) -> None: """The file is updated following a successful tests with wrong output.""" filename, expected_output_file, lmou = lint_module_fixture("foo") @@ -66,7 +69,7 @@ def test_lint_module_output_update_effective( @pytest.mark.skipif(not PY38_PLUS, reason="Requires python 3.8 or superior") def test_lint_module_output_update_remove_useless_txt( - lint_module_fixture: Callable[[str], Tuple[Path, Path, LintModuleOutputUpdate]] + lint_module_fixture: Callable[[str], tuple[Path, Path, LintModuleOutputUpdate]] ) -> None: """The file is updated following a successful tests with wrong output.""" filename, expected_output_file, lmou = lint_module_fixture("fine_name") diff --git a/tests/testutils/test_output_line.py b/tests/testutils/test_output_line.py index 6e6335ecc5..0a194b9735 100644 --- a/tests/testutils/test_output_line.py +++ b/tests/testutils/test_output_line.py @@ -4,7 +4,9 @@ # pylint: disable=redefined-outer-name -from typing import Callable, Optional +from __future__ import annotations + +from collections.abc import Callable import pytest @@ -151,7 +153,7 @@ def test_output_line_from_csv_error() -> None: "confidence,expected_confidence", [[None, "UNDEFINED"], ["INFERENCE", "INFERENCE"]] ) def test_output_line_from_csv_deprecated( - confidence: Optional[str], expected_confidence: str + confidence: str | None, expected_confidence: str ) -> None: """Test that the OutputLine NamedTuple is instantiated correctly with from_csv. Test OutputLine's of length 5 or 6. diff --git a/tests/unittest_reporters_json.py b/tests/unittest_reporters_json.py index 3e80c259af..d4462a83df 100644 --- a/tests/unittest_reporters_json.py +++ b/tests/unittest_reporters_json.py @@ -4,9 +4,11 @@ """Test for the JSON reporter.""" +from __future__ import annotations + import json from io import StringIO -from typing import Any, Dict, List +from typing import Any from pylint import checkers from pylint.lint import PyLinter @@ -74,7 +76,7 @@ def test_simple_json_output_no_score_with_end_line() -> None: assert json.dumps(report) == json.dumps(expected) -def get_linter_result(score: bool, message: Dict[str, Any]) -> List[Dict[str, Any]]: +def get_linter_result(score: bool, message: dict[str, Any]) -> list[dict[str, Any]]: output = StringIO() reporter = JSONReporter(output) linter = PyLinter(reporter=reporter) diff --git a/tests/unittest_reporting.py b/tests/unittest_reporting.py index 3831464237..9d01dd8dfc 100644 --- a/tests/unittest_reporting.py +++ b/tests/unittest_reporting.py @@ -3,6 +3,9 @@ # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt # pylint: disable=redefined-outer-name + +from __future__ import annotations + import sys import warnings from contextlib import redirect_stdout @@ -159,7 +162,7 @@ def __init__(self, output=None): def writeln(self, string=""): pass - def _display(self, layout: "Section") -> None: + def _display(self, layout: Section) -> None: pass @@ -334,7 +337,7 @@ def test_multi_format_output(tmp_path): def test_display_results_is_renamed(): class CustomReporter(TextReporter): - def _display(self, layout: "Section") -> None: + def _display(self, layout: Section) -> None: return None reporter = CustomReporter() diff --git a/tests/utils/unittest_ast_walker.py b/tests/utils/unittest_ast_walker.py index ec271bee78..c0ec6b8e6f 100644 --- a/tests/utils/unittest_ast_walker.py +++ b/tests/utils/unittest_ast_walker.py @@ -2,8 +2,9 @@ # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt +from __future__ import annotations + import warnings -from typing import Dict, Set import astroid @@ -13,7 +14,7 @@ class TestASTWalker: class MockLinter: - def __init__(self, msgs: Dict[str, bool]) -> None: + def __init__(self, msgs: dict[str, bool]) -> None: self._msgs = msgs def is_message_enabled(self, msgid: str) -> bool: @@ -21,7 +22,7 @@ def is_message_enabled(self, msgid: str) -> bool: class Checker: def __init__(self) -> None: - self.called: Set[str] = set() + self.called: set[str] = set() @check_messages("first-message") def visit_module(self, module): # pylint: disable=unused-argument From 725ee2fc8fae32100ca98155ae972f65bf902128 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20van=20Noord?= <13665637+DanielNoord@users.noreply.github.com> Date: Thu, 14 Apr 2022 14:49:09 +0200 Subject: [PATCH 2/5] Fix test --- tests/test_self.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_self.py b/tests/test_self.py index a8a04d7730..e2b859a21c 100644 --- a/tests/test_self.py +++ b/tests/test_self.py @@ -331,8 +331,10 @@ def test_json_report_when_file_has_syntax_error(self) -> None: # So each version wants a different column number... if platform.python_implementation() == "PyPy": column = 9 - else: + elif sys.version_info >= (3, 8): column = 9 + else: + column = 15 expected = { "obj": "", "column": column, From 99e32f9d2a2872027e4996207567817b5e61d559 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20van=20Noord?= <13665637+DanielNoord@users.noreply.github.com> Date: Thu, 14 Apr 2022 18:27:29 +0200 Subject: [PATCH 3/5] Apply suggestions from code review Co-authored-by: Marc Mueller <30130371+cdce8p@users.noreply.github.com> --- tests/test_func.py | 4 ++-- tests/test_pylint_runners.py | 4 ++-- tests/test_regr.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/test_func.py b/tests/test_func.py index de7ebbc54e..95e97d8a33 100644 --- a/tests/test_func.py +++ b/tests/test_func.py @@ -14,8 +14,8 @@ from pylint.testutils import UPDATE_FILE, UPDATE_OPTION, _get_tests_info, linter -INPUT_DIR = join(dirname(__file__), "input") -MSG_DIR = join(dirname(__file__), "messages") +INPUT_DIR = join(dirname(abspath(__file__)), "input") +MSG_DIR = join(dirname(abspath(__file__)), "messages") FILTER_RGX = None diff --git a/tests/test_pylint_runners.py b/tests/test_pylint_runners.py index a0e1a352bd..bab781d77e 100644 --- a/tests/test_pylint_runners.py +++ b/tests/test_pylint_runners.py @@ -19,7 +19,7 @@ "runner", [run_epylint, run_pylint, run_pyreverse, run_symilar] ) def test_runner(runner: Callable, tmpdir: LocalPath) -> None: - filepath = __file__ + filepath = os.path.abspath(__file__) testargs = ["", filepath] with tmpdir.as_cwd(): with patch.object(sys, "argv", testargs): @@ -33,7 +33,7 @@ def test_runner(runner: Callable, tmpdir: LocalPath) -> None: ) def test_runner_with_arguments(runner: Callable, tmpdir: LocalPath) -> None: """Check the runners with arguments as parameter instead of sys.argv.""" - filepath = __file__ + filepath = os.path.abspath(__file__) testargs = [filepath] with tmpdir.as_cwd(): with pytest.raises(SystemExit) as err: diff --git a/tests/test_regr.py b/tests/test_regr.py index de80d8cbd9..8ed88ab1aa 100644 --- a/tests/test_regr.py +++ b/tests/test_regr.py @@ -22,7 +22,7 @@ from pylint import testutils from pylint.lint.pylinter import PyLinter -REGR_DATA = join(dirname(__file__), "regrtest_data") +REGR_DATA = join(dirname(abspath(__file__)), "regrtest_data") sys.path.insert(1, REGR_DATA) From d97b54ae420778bac21dc120b04d236b020530ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20van=20Noord?= <13665637+DanielNoord@users.noreply.github.com> Date: Thu, 14 Apr 2022 18:43:41 +0200 Subject: [PATCH 4/5] Fix imports --- tests/test_func.py | 1 + tests/test_pylint_runners.py | 1 + tests/test_regr.py | 1 + 3 files changed, 3 insertions(+) diff --git a/tests/test_func.py b/tests/test_func.py index 95e97d8a33..16dc36d85d 100644 --- a/tests/test_func.py +++ b/tests/test_func.py @@ -9,6 +9,7 @@ import re import sys from os.path import dirname, join +from posixpath import abspath import pytest diff --git a/tests/test_pylint_runners.py b/tests/test_pylint_runners.py index bab781d77e..b06046e225 100644 --- a/tests/test_pylint_runners.py +++ b/tests/test_pylint_runners.py @@ -5,6 +5,7 @@ from __future__ import annotations +import os import sys from collections.abc import Callable from unittest.mock import patch diff --git a/tests/test_regr.py b/tests/test_regr.py index 8ed88ab1aa..9b7a957b0f 100644 --- a/tests/test_regr.py +++ b/tests/test_regr.py @@ -14,6 +14,7 @@ import sys from collections.abc import Callable, Iterator from os.path import dirname, join +from posixpath import abspath from typing import cast import astroid From 1bf7ae5b989b2c7dfe9143e0f934dc7c2e1de012 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20van=20Noord?= <13665637+DanielNoord@users.noreply.github.com> Date: Thu, 14 Apr 2022 18:54:26 +0200 Subject: [PATCH 5/5] Don't trust autocomplete --- tests/test_func.py | 3 +-- tests/test_regr.py | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/tests/test_func.py b/tests/test_func.py index 16dc36d85d..17ff23ff5a 100644 --- a/tests/test_func.py +++ b/tests/test_func.py @@ -8,8 +8,7 @@ import re import sys -from os.path import dirname, join -from posixpath import abspath +from os.path import abspath, dirname, join import pytest diff --git a/tests/test_regr.py b/tests/test_regr.py index 9b7a957b0f..32f714b885 100644 --- a/tests/test_regr.py +++ b/tests/test_regr.py @@ -13,8 +13,7 @@ import os import sys from collections.abc import Callable, Iterator -from os.path import dirname, join -from posixpath import abspath +from os.path import abspath, dirname, join from typing import cast import astroid