def test_package(finalize_linter: PyLinter, file_names: list[str], check: Callable) -> None: finalize_linter.check(file_names) finalize_linter.reporter = cast( # Due to fixture testutils.GenericTestReporter, finalize_linter.reporter) got = finalize_linter.reporter.finalize().strip() assert check(got)
def test_docstring_message(linter: PyLinter) -> None: docstring_test = join(dirname(abspath(__file__)), "data", "docstring.py") linter.check([docstring_test]) msgs = linter.reporter.messages assert len(msgs) == 7 for msg, expected_symbol, expected_msg in zip( msgs, EXPECTED_SYMBOLS, EXPECTED_MSGS ): assert msg.symbol == expected_symbol assert msg.msg == expected_msg
def test_types_redefined(linter: PyLinter) -> None: elif_test = osp.join(osp.dirname(osp.abspath(__file__)), "data", "bad_builtin.py") with fix_import_path([elif_test]): linter.check([elif_test]) msgs = sorted(linter.reporter.messages, key=lambda item: item.line) assert len(msgs) == 2 for msg, expected in zip(msgs, EXPECTED): assert msg.symbol == "bad-builtin" assert msg.msg == expected
def test_check_package___init__(finalize_linter: PyLinter) -> None: filename = ["package.__init__"] finalize_linter.check(filename) checked = list(finalize_linter.stats.by_module.keys()) assert sorted(checked) == sorted(filename) os.chdir(join(REGR_DATA, "package")) finalize_linter.check(["__init__"]) checked = list(finalize_linter.stats.by_module.keys()) assert checked == ["__init__"]
def test_check_package___init__(finalize_linter: PyLinter) -> None: filename = ["package.__init__"] finalize_linter.check(filename) checked = list(finalize_linter.stats["by_module"].keys()) # type: ignore # Refactor of PyLinter.stats necessary assert checked == filename os.chdir(join(REGR_DATA, "package")) finalize_linter.check(["__init__"]) checked = list(finalize_linter.stats["by_module"].keys()) # type: ignore assert checked == ["__init__"]
def test_elseif_message(linter: PyLinter) -> None: elif_test = osp.join(osp.dirname(osp.abspath(__file__)), "data", "elif.py") linter.check([elif_test]) msgs = linter.reporter.messages assert len(msgs) == 2 for msg in msgs: assert msg.symbol == "else-if-used" assert msg.msg == 'Consider using "elif" instead of "else if"' assert msgs[0].line == 9 assert msgs[1].line == 21
def test_emptystring_message(linter: PyLinter) -> None: elif_test = osp.join(osp.dirname(osp.abspath(__file__)), "data", "empty_string_comparison.py") linter.check([elif_test]) msgs = linter.reporter.messages expected_lineno = [6, 9, 12, 15] assert len(msgs) == len(expected_lineno) for msg, lineno in zip(msgs, expected_lineno): assert msg.symbol == "compare-to-empty-string" assert msg.msg == "Avoid comparisons to empty string" assert msg.line == lineno
def test_comment_base_case(linter: PyLinter) -> None: comment_test = str(Path(__file__).parent.joinpath("data", "empty_comment.py")) linter.check([comment_test]) msgs = linter.reporter.messages assert len(msgs) == 4 for msg in msgs: assert msg.symbol == "empty-comment" assert msg.msg == "Line with empty comment" assert msgs[0].line == 2 assert msgs[1].line == 3 assert msgs[2].line == 5 assert msgs[3].line == 7
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) out, err = capsys.readouterr() assert not out assert not err files = tmpdir.listdir() assert len(files) == 1 assert "pylint-crash-20" in str(files[0]) with open(files[0], encoding="utf8") as f: content = f.read() assert "Failed to import module spam." in content
def test_base_checker_ordering() -> None: """Test ordering of checkers based on their __gt__ method.""" linter = PyLinter() fake_checker_1 = OtherBasicChecker() fake_checker_2 = LessBasicChecker() fake_checker_3 = DifferentBasicChecker() import_checker = ImportsChecker(linter) while_checker = WhileChecker(linter) type_checker = TypeChecker(linter) list_of_checkers = [ 1, fake_checker_1, fake_checker_2, fake_checker_3, type_checker, import_checker, while_checker, linter, ] assert sorted(list_of_checkers) == [ # type: ignore[type-var] linter, import_checker, type_checker, fake_checker_3, fake_checker_1, fake_checker_2, while_checker, 1, ] assert fake_checker_1 > fake_checker_3 assert fake_checker_2 > fake_checker_3 assert fake_checker_1 == fake_checker_2
def test_overlapping_exceptions(linter: PyLinter) -> None: test = join(dirname(__file__), "data", "overlapping_exceptions.py") linter.check([test]) msgs = linter.reporter.messages expected = [ (13, "Overlapping exceptions (SomeException and SomeException are the same)" ), ( 18, "Overlapping exceptions (SomeException is an ancestor class of SubclassException)", ), (23, "Overlapping exceptions (SomeException and AliasException are the same)" ), ( 28, "Overlapping exceptions (AliasException is an ancestor class of SubclassException)", ), (34, "Overlapping exceptions (SomeException and AliasException are the same)" ), ( 34, "Overlapping exceptions (SomeException is an ancestor class of SubclassException)", ), ( 34, "Overlapping exceptions (AliasException is an ancestor class of SubclassException)", ), ( 39, "Overlapping exceptions (ArithmeticError is an ancestor class of FloatingPointError)", ), ( 44, "Overlapping exceptions (ValueError is an ancestor class of UnicodeDecodeError)", ), ] assert len(msgs) == len(expected) for msg, exp in zip(msgs, expected): assert msg.msg_id == "W0714" assert msg.symbol == "overlapping-except" assert msg.category == "warning" assert (msg.line, msg.msg) == exp
def finalize_linter(linter: PyLinter) -> Iterator[PyLinter]: """Call reporter.finalize() to clean up pending messages if a test finished badly. """ yield linter linter.reporter = cast( # Due to fixture testutils.GenericTestReporter, linter.reporter) linter.reporter.finalize()
def test_overlapping_exceptions_py33(linter: PyLinter) -> None: """From Python 3.3 both IOError and socket.error are aliases for OSError.""" test = join(dirname(__file__), "data", "overlapping_exceptions_py33.py") linter.check([test]) msgs = linter.reporter.messages expected = [ (7, "Overlapping exceptions (IOError and OSError are the same)"), (12, "Overlapping exceptions (socket.error and OSError are the same)"), ( 17, "Overlapping exceptions (socket.error is an ancestor class of ConnectionError)", ), ] assert len(msgs) == len(expected) for msg, exp in zip(msgs, expected): assert msg.msg_id == "W0714" assert msg.symbol == "overlapping-except" assert msg.category == "warning" assert (msg.line, msg.msg) == exp
def generate_interactive_config(linter: PyLinter) -> None: print("Starting interactive pylint configuration generation") format_type = utils.get_and_validate_format() to_file, output_file_name = utils.get_and_validate_output_file() if format_type == "toml": config_string = linter._generate_config_file() else: output_stream = StringIO() with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) linter.generate_config(stream=output_stream, skipsections=("Commands", )) config_string = output_stream.getvalue() if to_file: with open(output_file_name, "w", encoding="utf-8") as f: print(config_string, file=f) print(f"Wrote configuration file to {output_file_name.resolve()}") else: print(config_string)
def _get_global_options_documentation(linter: PyLinter) -> str: """Get documentation for the main checker.""" result = get_rst_title("Pylint global options and switches", "-") result += """ Pylint provides global options and switches. """ for checker in linter.get_checkers(): if checker.name == MAIN_CHECKER_NAME and checker.options: with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) for section, options in checker.options_by_section(): if section is None: title = "General options" else: title = f"{section.capitalize()} options" result += get_rst_title(title, "~") assert isinstance(options, list) result += f"{get_rst_section(None, options)}\n" return result
def _get_checkers_infos(linter: PyLinter) -> dict[str, dict[str, Any]]: """Get info from a checker and handle KeyError.""" by_checker: dict[str, dict[str, Any]] = {} for checker in linter.get_checkers(): name = checker.name if name != MAIN_CHECKER_NAME: try: by_checker[name]["checker"] = checker with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) by_checker[name]["options"] += checker.options_and_values() by_checker[name]["msgs"].update(checker.msgs) by_checker[name]["reports"] += checker.reports except KeyError: with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) by_checker[name] = { "checker": checker, "options": list(checker.options_and_values()), "msgs": dict(checker.msgs), "reports": list(checker.reports), } return by_checker
def test_check_deprecation(linter: PyLinter, recwarn): linter.check("myfile.py") msg = recwarn.pop() assert "check function will only accept sequence" in str(msg)
def register(linter: PyLinter) -> None: linter.register_checker(DummyPlugin1(linter)) linter.register_checker(DummyPlugin2(linter))
def __init__(self) -> None: super().__init__(PyLinter())
def test_crash(finalize_linter: PyLinter, file_names: list[str]) -> None: finalize_linter.check(file_names)
def test_descriptor_crash(fname: str, finalize_linter: PyLinter) -> None: finalize_linter.check([join(REGR_DATA, fname)]) finalize_linter.reporter = cast( # Due to fixture testutils.GenericTestReporter, finalize_linter.reporter) finalize_linter.reporter.finalize().strip()
def register(linter: PyLinter): linter.register_checker(ServableHotDogChecker(linter))
def register(linter: PyLinter) -> None: linter.register_checker(NoSelfUseChecker(linter))
def test_load_text_repoter_if_not_provided() -> None: """Test if PyLinter.reporter is a TextReporter if no reporter is provided""" linter = PyLinter() assert isinstance(linter.reporter, TextReporter)
def register(linter: PyLinter) -> None: linter.register_checker(ConsiderUsingAnyOrAllChecker(linter))
def register(linter: PyLinter) -> None: linter.register_checker(PrivateImportChecker(linter))
def test_max_mccabe_rate(linter: PyLinter, fname_mccabe_example: str, complexity: int, expected: List[str]) -> None: linter.global_set_option("max-complexity", complexity) linter.check([fname_mccabe_example]) real_msgs = [message.msg for message in linter.reporter.messages] assert sorted(expected) == sorted(real_msgs)
def test_hang(finalize_linter: PyLinter, file_names: List[str], timeout_s: float) -> None: with timeout(timeout_s): finalize_linter.check(file_names)
def test_descriptor_crash(fname: str, finalize_linter: PyLinter) -> None: finalize_linter.check([join(REGR_DATA, fname)]) finalize_linter.reporter.finalize().strip()
from pylint.lint.pylinter import PyLinter from pylint.message._deleted_message_ids import DELETED_MSGID_PREFIXES def register_all_checkers_and_plugins(linter: PyLinter) -> None: """Registers all checkers and plugins.""" linter.cmdline_parser.set_conflict_handler("resolve") initialize_checkers(linter) initialize_extensions(linter) def get_next_code_category(message_ids: list[str]) -> int: categories = sorted({int(i[:2]) for i in message_ids}) # We add the prefixes for deleted checkers categories += DELETED_MSGID_PREFIXES for i in categories: if i + 1 not in categories: return i + 1 return categories[-1] + 1 if __name__ == "__main__": pylinter = PyLinter() register_all_checkers_and_plugins(pylinter) messages = sorted(i.msgid[1:] for i in pylinter.msgs_store.messages) next_category = get_next_code_category(messages) print(f"Next free message id category is {next_category:02}") print( f"Please use {next_category:02}01 for the first message of the new checker" )