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" ]) with pytest.raises(SystemExit): Run(["--init-hook"])
def test_old_names() -> None: """Check that we correctly double assign old name options.""" run = Run([EMPTY_MODULE, "--ignore=test,test_two"], exit=False) assert run.linter.config.ignore == ["test", "test_two"] assert run.linter.config.ignore == run.linter.config.black_list assert run.linter.config.ignore_patterns == (re.compile("^\\.#"), ) assert run.linter.config.ignore_patterns == run.linter.config.black_list_re
def test_recursive_ignore(ignore_parameter, ignore_parameter_value) -> None: run = Run( [ "--recursive", "y", ignore_parameter, ignore_parameter_value, join(REGRTEST_DATA_DIR, "directory"), ], exit=False, ) linted_files = run.linter._iterate_file_descrs( tuple( run.linter._discover_files([join(REGRTEST_DATA_DIR, "directory")]))) linted_file_paths = [file_item.filepath for file_item in linted_files] ignored_file = os.path.abspath( join(REGRTEST_DATA_DIR, "directory", "ignored_subdirectory", "failing.py")) assert ignored_file not in linted_file_paths for regrtest_data_module in ( ("directory", "subdirectory", "subsubdirectory", "module.py"), ("directory", "subdirectory", "module.py"), ("directory", "package", "module.py"), ("directory", "package", "subpackage", "module.py"), ): module = os.path.abspath(join(REGRTEST_DATA_DIR, *regrtest_data_module)) assert module in linted_file_paths
def test_process_tokens() -> None: with pytest.raises(SystemExit) as cm: Run( [os.path.join(REGR_DATA, "very_long_line.py"), "--disable=C"], reporter=TextReporter(), ) assert cm.value.code == 0
def test_logger_rcfile() -> None: """Check that we parse the rcfile for the logging checker correctly.""" with pytest.raises(SystemExit) as ex: Run([ LOGGING_TEST, f"--rcfile={LOGGING_TEST.replace('.py', '.rc')}" ]) assert ex.value.code == 0
def test_unknown_short_option_name(capsys: CaptureFixture) -> None: """Check that we correctly raise a message on an unknown short option.""" with pytest.raises(SystemExit): Run([str(EMPTY_MODULE), "-Q"], exit=False) output = capsys.readouterr() assert "usage: pylint" in output.err assert "Unrecognized option" in output.err
def test_new_names() -> None: """Check that we correctly emit DeprecationWarnings for deprecated options.""" with pytest.raises(SystemExit) as ex: with pytest.warns(DeprecationWarning) as records: Run([EMPTY_MODULE, "--ignore-mixin-members=yes"]) assert len(records) == 1 assert "--ignore-mixin-members has been deprecated" in records[0] assert ex.value.code == 0
def test_issue_template_on_fatal_errors(capsys: pytest.CaptureFixture) -> None: """Test that we also create an issue template if the offending exception isn't from astroid.""" with pytest.raises(SystemExit): with unittest.mock.patch("astroid.MANAGER.ast_from_file", side_effect=RecursionError()): Run([__file__]) captured = capsys.readouterr() assert "Fatal error while checking" in captured.out assert "Please open an issue" in captured.out assert "Traceback" in captured.err
def test_issue_5724() -> None: """Regression test for parsing of pylint disable pragma's.""" with pytest.raises(SystemExit) as cm: Run( [ os.path.join(REGR_DATA, "issue_5724.py"), "--enable=missing-final-newline", "--disable=C", ], reporter=TextReporter(), ) assert cm.value.code == 0
def test_run(tmp_path, name, git_repo): """Runs pylint against external sources.""" checkoutdir = tmp_path / name checkoutdir.mkdir() os.system(f"git clone --depth=1 {git_repo} {checkoutdir}") filepaths = _get_py_files(scanpath=str(checkoutdir)) print(f"Have {len(filepaths)} files") runner = Run(filepaths, reporter=Reporter(), exit=False) print( f"Had {len(filepaths)} files with {len(runner.linter.reporter.messages)} messages" ) pprint.pprint(runner.linter.reporter.messages)
def _run_pylint(args: list[str], out: TextIO) -> int: """Runs pylint with a patched output.""" args = args + [ "--persistent=no", "--enable=astroid-error", # Enable functionality that will build another ast "--ignore-imports=y", "--ignore-signatures=y", ] with _patch_streams(out): with pytest.raises(SystemExit) as cm: with warnings.catch_warnings(): warnings.simplefilter("ignore") Run(args) return cm.value.code
def test_load_plugin_configuration() -> None: dummy_plugin_path = join(REGRTEST_DATA_DIR, "dummy_plugin") sys.path.append(dummy_plugin_path) run = Run( [ "--load-plugins", "dummy_conf_plugin", "--ignore", "foo,bar", join(REGRTEST_DATA_DIR, "empty.py"), ], exit=False, ) assert run.linter.config.ignore == ["foo", "bar", "bin"]
def test_useless_suppression() -> None: """Tests that duplicate code and useless-suppression work well together.""" path = join(DATA, "useless_suppression") pylint_output = StringIO() reporter = TextReporter(pylint_output) runner = Run( [ path, "-e=duplicate-code, useless-suppression", "-d=missing-module-docstring, unused-import", ], reporter=reporter, exit=False, ) assert not runner.linter.stats.by_msg
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") run = Run( ["--rcfile", config_path, join(REGRTEST_DATA_DIR, "empty.py")], exit=False, ) assert (len([ ch.name for ch in run.linter.get_checkers() if ch.name == "dummy_plugin" ]) == 2) sys.path.remove(dummy_plugin_path)
def test_load_plugin_command_line() -> None: dummy_plugin_path = join(REGRTEST_DATA_DIR, "dummy_plugin") sys.path.append(dummy_plugin_path) run = Run( [ "--load-plugins", "dummy_plugin", join(REGRTEST_DATA_DIR, "empty.py") ], exit=False, ) assert (len([ ch.name for ch in run.linter.get_checkers() if ch.name == "dummy_plugin" ]) == 2) sys.path.remove(dummy_plugin_path)
def test_primer_stdlib_no_crash( test_module_location: str, test_module_name: str, capsys: CaptureFixture ) -> None: """Test that pylint does not produce any crashes or fatal errors on stdlib modules.""" __tracebackhide__ = True # pylint: disable=unused-variable os.chdir(test_module_location) with _patch_stdout(io.StringIO()): try: # We want to test all the code we can enables = ["--enable-all-extensions", "--enable=all"] # Duplicate code takes too long and is relatively safe # We don't want to lint the test directory which are repetitive disables = ["--disable=duplicate-code", "--ignore=test"] Run([test_module_name] + enables + disables) except SystemExit as ex: out, err = capsys.readouterr() assert not err, err assert not out msg = f"Encountered {{}} during primer stlib test for {test_module_name}" assert ex.code != 32, msg.format("a crash") assert ex.code % 2 == 0, msg.format("a message of category 'fatal'")
def test_exclusivity_of_msgids() -> None: """Test to see if all checkers have an exclusive message id prefix.""" err_msg = ( "{} has the same prefix ('{}') as the '{}' checker. Please make sure the prefix " "is unique for each checker. You can use 'script/get_unused_message_id_category.py' " "to get a unique id.") runner = Run(["--enable-all-extensions", EMPTY_FILE], exit=False) # Some pairs are hard-coded as they are pre-existing and non-exclusive, # and we don't want to rename them for backwards compatibility checker_id_pairs = { "00": ("main", "miscellaneous"), "01": ( "basic", "refactoring", "consider_ternary_expression", "while_used", "docstyle", "deprecated_builtins", ), "02": ("classes", "refactoring", "multiple_types"), "03": ("classes", "format"), "04": ("imports", "spelling"), "05": ("consider-using-any-or-all", "miscellaneous"), "07": ("exceptions", "broad_try_clause", "overlap-except"), "12": ("design", "logging"), "17": ("async", "refactoring"), "20": ("compare-to-zero", "refactoring"), } for msgid, definition in runner.linter.msgs_store._messages_definitions.items( ): if definition.shared: continue if msgid[1:3] in checker_id_pairs: assert (definition.checker_name in checker_id_pairs[msgid[1:3]]), err_msg.format( msgid, msgid[1:3], checker_id_pairs[msgid[1:3]][0]) else: checker_id_pairs[msgid[1:3]] = (definition.checker_name, )
def test_unknown_yes_no(capsys: CaptureFixture) -> None: """Check that we correctly error on an unknown yes/no value.""" with pytest.raises(SystemExit): Run([str(EMPTY_MODULE), "--reports=maybe"], exit=False) output = capsys.readouterr() assert "Invalid yn value 'maybe', should be in " in output.err
def test_empty_confidence() -> None: """An empty confidence value indicates all errors should be emitted.""" r = Run([str(EMPTY_MODULE), "--confidence="], exit=False) assert r.linter.config.confidence == CONFIDENCE_LEVEL_NAMES
def test_unknown_confidence(capsys: CaptureFixture) -> None: """Check that we correctly error an unknown confidence value.""" with pytest.raises(SystemExit): Run([str(EMPTY_MODULE), "--confidence=UNKNOWN_CONFIG"], exit=False) output = capsys.readouterr() assert "argument --confidence: UNKNOWN_CONFIG should be in" in output.err
def test_logger_commandline() -> None: """Check that we parse command-line options for the logging checker correctly.""" with pytest.raises(SystemExit) as ex: Run([LOGGING_TEST, "--logging-format-style=new"]) assert ex.value.code == 0
def test_unknown_message_id(capsys: CaptureFixture) -> None: """Check that we correctly raise a message on an unknown id.""" Run([str(EMPTY_MODULE), "--disable=12345"], exit=False) output = capsys.readouterr() assert "Command line:1:0: W0012: Unknown option value for '--disable'" in output.out
def test_short_verbose(capsys: CaptureFixture) -> None: """Check that we correctly handle the -v flag.""" Run([str(EMPTY_MODULE), "-v"], exit=False) output = capsys.readouterr() assert "Using config file" in output.err
def test_unknown_py_version(capsys: CaptureFixture) -> None: """Check that we correctly error on an unknown python-version.""" with pytest.raises(SystemExit): Run([str(EMPTY_MODULE), "--py-version=the-newest"], exit=False) output = capsys.readouterr() assert "the-newest has an invalid format, should be a version string." in output.err
def test_logger_without_options() -> None: """Check that we raise messages when we do not supply any options.""" with pytest.raises(SystemExit) as ex: Run([LOGGING_TEST]) assert ex.value.code == 2