Debian Codegraph @

tests/lint/unittest_lint.py

raw symbols SCIP
1 # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
2 # For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
3 # Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt
4
5 # pylint: disable=redefined-outer-name
6
7 from __future__ import annotations
8
9 import argparse
10 import os
11 import re
12 import sys
13 import tempfile
14 from collections.abc import Iterator
15 from contextlib import contextmanager
16 from io import StringIO
17 from os import chdir, getcwd
18 from os.path import abspath, dirname, join, sep
19 from pathlib import Path
20 from shutil import copy, rmtree
21 from unittest import mock
22
23 import astroid
24 import platformdirs
25 import pytest
26 from astroid import nodes
27 from pytest import CaptureFixture
28
29 from pylint import checkers, constants, exceptions, interfaces, lint, testutils
30 from pylint.checkers.utils import only_required_for_messages
31 from pylint.constants import (
32 MSG_STATE_CONFIDENCE,
33 MSG_STATE_SCOPE_CONFIG,
34 MSG_STATE_SCOPE_MODULE,
35 PYLINT_HOME,
36 _get_pylint_home,
37 )
38 from pylint.exceptions import InvalidMessageError
39 from pylint.lint import PyLinter, expand_modules
40 from pylint.message import Message
41 from pylint.reporters import text
42 from pylint.testutils import create_files
43 from pylint.testutils._run import _Run as Run
44 from pylint.typing import MessageLocationTuple
45 from pylint.utils import (
46 FileState,
47 LinterStats,
48 print_full_documentation,
49 tokenize_module,
50 )
51
52 if os.name == "java":
53 if os.name == "nt":
54 HOME = "USERPROFILE"
55 else:
56 HOME = "HOME"
57 elif sys.platform == "win32":
58 HOME = "USERPROFILE"
59 else:
60 HOME = "HOME"
61
62
63 @contextmanager
64 def fake_home() -> Iterator[str]:
65 folder = tempfile.mkdtemp("fake-home")
66 old_home = os.environ.get(HOME)
67 try:
68 os.environ[HOME] = folder
69 yield folder
70 finally:
71 os.environ.pop("PYLINTRC", "")
72 if old_home is None:
73 del os.environ[HOME]
74 else:
75 os.environ[HOME] = old_home
76 rmtree(folder, ignore_errors=True)
77
78
79 def remove(file: str) -> None:
80 try:
81 os.remove(file)
82 except OSError:
83 pass
84
85
86 HERE = abspath(dirname(__file__))
87 INPUT_DIR = join(HERE, "..", "input")
88 REGRTEST_DATA_DIR = join(HERE, "..", "regrtest_data")
89 DATA_DIR = join(HERE, "..", "data")
90
91
92 @contextmanager
93 def tempdir() -> Iterator[str]:
94 """Create a temp directory and change the current location to it.
95
96 This is supposed to be used with a *with* statement.
97 """
98 tmp = tempfile.mkdtemp()
99
100 # Get real path of tempfile, otherwise test fail on mac os x
101 current_dir = getcwd()
102 chdir(tmp)
103 abs_tmp = abspath(".")
104
105 try:
106 yield abs_tmp
107 finally:
108 chdir(current_dir)
109 rmtree(abs_tmp)
110
111
112 @pytest.fixture
113 def fake_path() -> Iterator[list[str]]:
114 orig = list(sys.path)
115 fake = ["1", "2", "3"]
116 sys.path[:] = fake
117 yield fake
118 sys.path[:] = orig
119
120
121 def test_no_args(fake_path: list[str]) -> None:
122 with lint.augmented_sys_path([]):
123 assert sys.path == fake_path
124 assert sys.path == fake_path
125
126
127 @pytest.mark.parametrize(
128 "case", [["a/b/"], ["a/b"], ["a/b/__init__.py"], ["a/"], ["a"]]
129 )
130 def test_one_arg(fake_path: list[str], case: list[str]) -> None:
131 with tempdir() as chroot:
132 create_files(["a/b/__init__.py"])
133 expected = [join(chroot, "a"), *fake_path]
134
135 extra_sys_paths = [
136 expand_modules.discover_package_path(arg, []) for arg in case
137 ]
138
139 assert sys.path == fake_path
140 with lint.augmented_sys_path(extra_sys_paths):
141 assert sys.path == expected
142 assert sys.path == fake_path
143
144
145 @pytest.mark.parametrize(
146 "case",
147 [
148 ["a/b", "a/c"],
149 ["a/c/", "a/b/"],
150 ["a/b/__init__.py", "a/c/__init__.py"],
151 ["a", "a/c/__init__.py"],
152 ],
153 )
154 def test_two_similar_args(fake_path: list[str], case: list[str]) -> None:
155 with tempdir() as chroot:
156 create_files(["a/b/__init__.py", "a/c/__init__.py"])
157 expected = [join(chroot, "a"), *fake_path]
158
159 extra_sys_paths = [
160 expand_modules.discover_package_path(arg, []) for arg in case
161 ]
162
163 assert sys.path == fake_path
164 with lint.augmented_sys_path(extra_sys_paths):
165 assert sys.path == expected
166 assert sys.path == fake_path
167
168
169 @pytest.mark.parametrize(
170 "case",
171 [
172 ["a/b/c/__init__.py", "a/d/__init__.py", "a/e/f.py"],
173 ["a/b/c", "a", "a/e"],
174 ["a/b/c", "a", "a/b/c", "a/e", "a"],
175 ],
176 )
177 def test_more_args(fake_path: list[str], case: list[str]) -> None:
178 with tempdir() as chroot:
179 create_files(["a/b/c/__init__.py", "a/d/__init__.py", "a/e/f.py"])
180 expected = [
181 join(chroot, suffix)
182 for suffix in (sep.join(("a", "b")), "a", sep.join(("a", "e")))
183 ] + fake_path
184
185 extra_sys_paths = [
186 expand_modules.discover_package_path(arg, []) for arg in case
187 ]
188
189 assert sys.path == fake_path
190 with lint.augmented_sys_path(extra_sys_paths):
191 assert sys.path == expected
192 assert sys.path == fake_path
193
194
195 @pytest.fixture(scope="module")
196 def disable() -> list[str]:
197 return ["I"]
198
199
200 @pytest.fixture(scope="module")
201 def reporter() -> type[testutils.GenericTestReporter]:
202 return testutils.GenericTestReporter
203
204
205 @pytest.fixture
206 def initialized_linter(linter: PyLinter) -> PyLinter:
207 linter.open()
208 linter.set_current_module("long_test_file", "long_test_file")
209 linter.file_state = FileState(
210 "long_test_file",
211 linter.msgs_store,
212 linter.get_ast(
213 str(join(REGRTEST_DATA_DIR, "long_test_file.py")), "long_test_file"
214 ),
215 )
216 return linter
217
218
219 def test_pylint_visit_method_taken_in_account(linter: PyLinter) -> None:
220 class CustomChecker(checkers.BaseChecker):
221 name = "custom"
222 msgs = {"W9999": ("", "custom", "")}
223
224 @only_required_for_messages("custom")
225 def visit_class(self, _: nodes.ClassDef) -> None:
226 pass
227
228 linter.register_checker(CustomChecker(linter))
229 linter.open()
230 out = StringIO()
231 linter.set_reporter(text.TextReporter(out))
232 linter.check(["abc"])
233
234
235 def test_enable_message(initialized_linter: PyLinter) -> None:
236 linter = initialized_linter
237 assert linter.is_message_enabled("W0101")
238 assert linter.is_message_enabled("W0102")
239 linter.disable("W0101", scope="package")
240 linter.disable("W0102", scope="module", line=1)
241 assert not linter.is_message_enabled("W0101")
242 assert not linter.is_message_enabled("W0102", 1)
243 linter.set_current_module("tutu")
244 assert not linter.is_message_enabled("W0101")
245 assert linter.is_message_enabled("W0102")
246 linter.enable("W0101", scope="package")
247 linter.enable("W0102", scope="module", line=1)
248 assert linter.is_message_enabled("W0101")
249 assert linter.is_message_enabled("W0102", 1)
250
251
252 def test_enable_message_category(initialized_linter: PyLinter) -> None:
253 linter = initialized_linter
254 assert linter.is_message_enabled("W0101")
255 assert linter.is_message_enabled("C0202")
256 linter.disable("W", scope="package")
257 linter.disable("C", scope="module", line=1)
258 assert not linter.is_message_enabled("W0101")
259 assert linter.is_message_enabled("C0202")
260 assert not linter.is_message_enabled("C0202", line=1)
261 linter.set_current_module("tutu")
262 assert not linter.is_message_enabled("W0101")
263 assert linter.is_message_enabled("C0202")
264 linter.enable("W", scope="package")
265 linter.enable("C", scope="module", line=1)
266 assert linter.is_message_enabled("W0101")
267 assert linter.is_message_enabled("C0202")
268 assert linter.is_message_enabled("C0202", line=1)
269
270
271 def test_message_state_scope(initialized_linter: PyLinter) -> None:
272 class FakeConfig(argparse.Namespace):
273 confidence = ["HIGH"]
274
275 linter = initialized_linter
276 linter.disable("C0202")
277 assert MSG_STATE_SCOPE_CONFIG == linter._get_message_state_scope("C0202")
278 linter.disable("W0101", scope="module", line=3)
279 assert MSG_STATE_SCOPE_CONFIG == linter._get_message_state_scope("C0202")
280 assert MSG_STATE_SCOPE_MODULE == linter._get_message_state_scope("W0101", 3)
281 linter.enable("W0102", scope="module", line=3)
282 assert MSG_STATE_SCOPE_MODULE == linter._get_message_state_scope("W0102", 3)
283 linter.config = FakeConfig()
284 assert MSG_STATE_CONFIDENCE == linter._get_message_state_scope(
285 "this-is-bad", confidence=interfaces.INFERENCE
286 )
287
288
289 def test_enable_message_block(initialized_linter: PyLinter) -> None:
290 linter = initialized_linter
291 linter.open()
292 filepath = join(REGRTEST_DATA_DIR, "func_block_disable_msg.py")
293 linter.set_current_module("func_block_disable_msg")
294 astroid = linter.get_ast(filepath, "func_block_disable_msg")
295 linter.file_state = FileState("func_block_disable_msg", linter.msgs_store, astroid)
296 linter.process_tokens(tokenize_module(astroid))
297 fs = linter.file_state
298 # global (module level)
299 assert linter.is_message_enabled("W0613")
300 assert linter.is_message_enabled("E1101")
301 # meth1
302 assert linter.is_message_enabled("W0613", 13)
303 # meth2
304 assert not linter.is_message_enabled("W0613", 18)
305 # meth3
306 assert not linter.is_message_enabled("E1101", 24)
307 assert linter.is_message_enabled("E1101", 26)
308 # meth4
309 assert not linter.is_message_enabled("E1101", 32)
310 assert linter.is_message_enabled("E1101", 36)
311 # meth5
312 assert not linter.is_message_enabled("E1101", 42)
313 assert not linter.is_message_enabled("E1101", 43)
314 assert linter.is_message_enabled("E1101", 46)
315 assert not linter.is_message_enabled("E1101", 49)
316 assert not linter.is_message_enabled("E1101", 51)
317 # meth6
318 assert not linter.is_message_enabled("E1101", 57)
319 assert linter.is_message_enabled("E1101", 61)
320 assert linter.is_message_enabled("E1101", 64)
321 assert not linter.is_message_enabled("E1101", 66)
322
323 assert linter.is_message_enabled("E0602", 57)
324 assert linter.is_message_enabled("E0602", 61)
325 assert not linter.is_message_enabled("E0602", 62)
326 assert linter.is_message_enabled("E0602", 64)
327 assert linter.is_message_enabled("E0602", 66)
328 # meth7
329 assert not linter.is_message_enabled("E1101", 70)
330 assert linter.is_message_enabled("E1101", 72)
331 assert linter.is_message_enabled("E1101", 75)
332 assert linter.is_message_enabled("E1101", 77)
333
334 assert fs._suppression_mapping["W0613", 18] == 17
335 assert fs._suppression_mapping["E1101", 33] == 30
336 assert ("E1101", 46) not in fs._suppression_mapping
337 assert fs._suppression_mapping["C0302", 18] == 1
338 assert fs._suppression_mapping["C0302", 50] == 1
339 # This is tricky. While the disable in line 106 is disabling
340 # both 108 and 110, this is usually not what the user wanted.
341 # Therefore, we report the closest previous disable comment.
342 assert fs._suppression_mapping["E1101", 108] == 106
343 assert fs._suppression_mapping["E1101", 110] == 109
344
345
346 def test_enable_by_symbol(initialized_linter: PyLinter) -> None:
347 """Messages can be controlled by symbolic names.
348
349 The state is consistent across symbols and numbers.
350 """
351 linter = initialized_linter
352 assert linter.is_message_enabled("W0101")
353 assert linter.is_message_enabled("unreachable")
354 assert linter.is_message_enabled("W0102")
355 assert linter.is_message_enabled("dangerous-default-value")
356 linter.disable("unreachable", scope="package")
357 linter.disable("dangerous-default-value", scope="module", line=1)
358 assert not linter.is_message_enabled("W0101")
359 assert not linter.is_message_enabled("unreachable")
360 assert not linter.is_message_enabled("W0102", 1)
361 assert not linter.is_message_enabled("dangerous-default-value", 1)
362 linter.set_current_module("tutu")
363 assert not linter.is_message_enabled("W0101")
364 assert not linter.is_message_enabled("unreachable")
365 assert linter.is_message_enabled("W0102")
366 assert linter.is_message_enabled("dangerous-default-value")
367 linter.enable("unreachable", scope="package")
368 linter.enable("dangerous-default-value", scope="module", line=1)
369 assert linter.is_message_enabled("W0101")
370 assert linter.is_message_enabled("unreachable")
371 assert linter.is_message_enabled("W0102", 1)
372 assert linter.is_message_enabled("dangerous-default-value", 1)
373
374
375 def test_enable_report(linter: PyLinter) -> None:
376 assert linter.report_is_enabled("RP0001")
377 linter.disable("RP0001")
378 assert not linter.report_is_enabled("RP0001")
379 linter.enable("RP0001")
380 assert linter.report_is_enabled("RP0001")
381
382
383 def test_report_output_format_aliased(linter: PyLinter) -> None:
384 text.register(linter)
385 linter.set_option("output-format", "text")
386 assert linter.reporter.__class__.__name__ == "TextReporter"
387
388
389 def test_set_unsupported_reporter(linter: PyLinter) -> None:
390 text.register(linter)
391 # ImportError
392 with pytest.raises(exceptions.InvalidReporterError):
393 linter.set_option("output-format", "missing.module.Class")
394
395 # AssertionError
396 with pytest.raises(exceptions.InvalidReporterError):
397 linter.set_option("output-format", "lint.unittest_lint._CustomPyLinter")
398
399 # AttributeError
400 with pytest.raises(exceptions.InvalidReporterError):
401 linter.set_option("output-format", "lint.unittest_lint.MyReporter")
402
403
404 def test_set_option_1(initialized_linter: PyLinter) -> None:
405 linter = initialized_linter
406 linter.set_option("disable", "C0111,W0234")
407 assert not linter.is_message_enabled("C0111")
408 assert not linter.is_message_enabled("W0234")
409 assert linter.is_message_enabled("W0113")
410 assert not linter.is_message_enabled("missing-docstring")
411 assert not linter.is_message_enabled("non-iterator-returned")
412
413
414 def test_set_option_2(initialized_linter: PyLinter) -> None:
415 linter = initialized_linter
416 linter.set_option("disable", ("C0111", "W0234"))
417 assert not linter.is_message_enabled("C0111")
418 assert not linter.is_message_enabled("W0234")
419 assert linter.is_message_enabled("W0113")
420 assert not linter.is_message_enabled("missing-docstring")
421 assert not linter.is_message_enabled("non-iterator-returned")
422
423
424 def test_enable_checkers(linter: PyLinter) -> None:
425 linter.disable("design")
426 assert "design" not in [c.name for c in linter.prepare_checkers()]
427 linter.enable("design")
428 assert "design" in [c.name for c in linter.prepare_checkers()]
429
430
431 def test_errors_only(initialized_linter: PyLinter) -> None:
432 linter = initialized_linter
433 linter._error_mode = True
434 linter._parse_error_mode()
435 checkers = linter.prepare_checkers()
436 checker_names = {c.name for c in checkers}
437 should_not = {"design", "format", "metrics", "miscellaneous", "similarities"}
438 assert set() == should_not & checker_names
439
440
441 def test_disable_similar(initialized_linter: PyLinter) -> None:
442 linter = initialized_linter
443 linter.set_option("disable", "RP0801")
444 linter.set_option("disable", "R0801")
445 assert "similarities" not in [c.name for c in linter.prepare_checkers()]
446
447
448 def test_disable_similar_with_reports(initialized_linter: PyLinter) -> None:
449 """Disabling R0801 should exclude the similarities checker even with reports enabled.
450
451 Regression test for https://github.com/pylint-dev/pylint/issues/3443
452 """
453 linter = initialized_linter
454 linter.set_option("reports", True)
455 linter.set_option("disable", "R0801")
456 checker_names = [c.name for c in linter.prepare_checkers()]
457 assert "similarities" not in checker_names
458 # Report-only checkers (no messages) should still be included
459 assert "metrics" in checker_names
460
461
462 def test_disable_alot(linter: PyLinter) -> None:
463 """Check that we disabled a lot of checkers."""
464 linter.set_option("reports", False)
465 linter.set_option("disable", "R,C,W")
466 checker_names = [c.name for c in linter.prepare_checkers()]
467 for cname in ("design", "metrics", "similarities"):
468 assert cname not in checker_names, cname
469
470
471 def test_addmessage(linter: PyLinter) -> None:
472 linter.set_reporter(testutils.GenericTestReporter())
473 linter.open()
474 linter.set_current_module("0123")
475 linter.add_message("C0301", line=1, args=(1, 2))
476 linter.add_message("line-too-long", line=2, args=(3, 4))
477 assert len(linter.reporter.messages) == 2
478 assert linter.reporter.messages[0] == Message(
479 msg_id="C0301",
480 symbol="line-too-long",
481 msg="Line too long (1/2)",
482 confidence=interfaces.Confidence(
483 name="UNDEFINED",
484 description="Warning without any associated confidence level.",
485 ),
486 location=MessageLocationTuple(
487 abspath="0123",
488 path="0123",
489 module="0123",
490 obj="",
491 line=1,
492 column=0,
493 end_line=None,
494 end_column=None,
495 ),
496 )
497 assert linter.reporter.messages[1] == Message(
498 msg_id="C0301",
499 symbol="line-too-long",
500 msg="Line too long (3/4)",
501 confidence=interfaces.Confidence(
502 name="UNDEFINED",
503 description="Warning without any associated confidence level.",
504 ),
505 location=MessageLocationTuple(
506 abspath="0123",
507 path="0123",
508 module="0123",
509 obj="",
510 line=2,
511 column=0,
512 end_line=None,
513 end_column=None,
514 ),
515 )
516
517
518 def test_addmessage_preserves_explicit_zero_col_offset(linter: PyLinter) -> None:
519 """An explicit ``col_offset=0`` from the caller must not be overwritten
520 by the node's value (``not 0`` is True so the old falsey check was buggy).
521 """
522 linter.set_reporter(testutils.GenericTestReporter())
523 linter.open()
524 linter.set_current_module("m")
525 module_node = astroid.parse("\n\nfunc(arg)", module_name="m")
526 arg_node = module_node.body[0].value.args[0] # ``arg`` — col_offset == 5
527 assert arg_node.col_offset != 0 # sanity-check fixture
528 linter.add_message("C0321", node=arg_node, col_offset=0)
529 assert linter.reporter.messages[0].location.column == 0
530
531
532 def test_addmessage_invalid(linter: PyLinter) -> None:
533 linter.set_reporter(testutils.GenericTestReporter())
534 linter.open()
535 linter.set_current_module("0123")
536
537 with pytest.raises(InvalidMessageError) as cm:
538 linter.add_message("line-too-long", args=(1, 2))
539 assert str(cm.value) == "Message C0301 must provide line, got None"
540
541 with pytest.raises(InvalidMessageError) as cm:
542 linter.add_message("line-too-long", line=2, node="fake_node", args=(1, 2))
543 assert (
544 str(cm.value)
545 == "Message C0301 must only provide line, got line=2, node=fake_node"
546 )
547
548 with pytest.raises(InvalidMessageError) as cm:
549 linter.add_message("C0321")
550 assert str(cm.value) == "Message C0321 must provide Node, got None"
551
552
553 def test_load_plugin_command_line() -> None:
554 dummy_plugin_path = join(REGRTEST_DATA_DIR, "dummy_plugin")
555 sys.path.append(dummy_plugin_path)
556
557 run = Run(
558 ["--load-plugins", "dummy_plugin", join(REGRTEST_DATA_DIR, "empty.py")],
559 exit=False,
560 )
561 assert (
562 len([ch.name for ch in run.linter.get_checkers() if ch.name == "dummy_plugin"])
563 == 2
564 )
565
566 sys.path.remove(dummy_plugin_path)
567
568
569 @pytest.mark.usefixtures("pop_pylintrc")
570 def test_load_plugin_path_manipulation_case_6() -> None:
571 """Case 6 refers to GitHub issue #7264.
572
573 This is where we supply a plugin we want to load on both the CLI and
574 config file, but that plugin is only loadable after the ``init-hook`` in
575 the config file has run. This is not supported, and was previously a silent
576 failure. This test ensures a ``bad-plugin-value`` message is emitted.
577 """
578 dummy_plugin_path = abspath(
579 join(REGRTEST_DATA_DIR, "dummy_plugin", "dummy_plugin.py")
580 )
581 with fake_home() as home_path:
582 # construct a basic rc file that just modifies the path
583 pylintrc_file = join(home_path, "pylintrc")
584 with open(pylintrc_file, "w", encoding="utf8") as out:
585 out.writelines(
586 [
587 "[MASTER]\n",
588 f"init-hook=\"import sys; sys.path.append(r'{home_path}')\"\n",
589 "load-plugins=copy_dummy\n",
590 ]
591 )
592
593 copy(dummy_plugin_path, join(home_path, "copy_dummy.py"))
594
595 # To confirm we won't load this module _without_ the init hook running.
596 assert home_path not in sys.path
597
598 run = Run(
599 [
600 "--rcfile",
601 pylintrc_file,
602 "--load-plugins",
603 "copy_dummy",
604 join(REGRTEST_DATA_DIR, "empty.py"),
605 ],
606 reporter=testutils.GenericTestReporter(),
607 exit=False,
608 )
609 assert run._rcfile == pylintrc_file
610 assert home_path in sys.path
611 # The module should not be loaded
612 assert not any(ch.name == "dummy_plugin" for ch in run.linter.get_checkers())
613
614 # There should be a bad-plugin-message for this module
615 assert len(run.linter.reporter.messages) == 1
616 assert run.linter.reporter.messages[0] == Message(
617 msg_id="E0013",
618 symbol="bad-plugin-value",
619 msg="Plugin 'copy_dummy' is impossible to load, is it installed ? ('No module named 'copy_dummy'')",
620 confidence=interfaces.Confidence(
621 name="UNDEFINED",
622 description="Warning without any associated confidence level.",
623 ),
624 location=MessageLocationTuple(
625 abspath="Command line or configuration file",
626 path="Command line or configuration file",
627 module="Command line or configuration file",
628 obj="",
629 line=1,
630 column=0,
631 end_line=None,
632 end_column=None,
633 ),
634 )
635
636 # Necessary as the executed init-hook modifies sys.path
637 sys.path.remove(home_path)
638
639
640 @pytest.mark.usefixtures("pop_pylintrc")
641 def test_load_plugin_path_manipulation_case_3() -> None:
642 """Case 3 refers to GitHub issue #7264.
643
644 This is where we supply a plugin we want to load on the CLI only,
645 but that plugin is only loadable after the ``init-hook`` in
646 the config file has run. This is not supported, and was previously a silent
647 failure. This test ensures a ``bad-plugin-value`` message is emitted.
648 """
649 dummy_plugin_path = abspath(
650 join(REGRTEST_DATA_DIR, "dummy_plugin", "dummy_plugin.py")
651 )
652 with fake_home() as home_path:
653 # construct a basic rc file that just modifies the path
654 pylintrc_file = join(home_path, "pylintrc")
655 with open(pylintrc_file, "w", encoding="utf8") as out:
656 out.writelines(
657 [
658 "[MASTER]\n",
659 f"init-hook=\"import sys; sys.path.append(r'{home_path}')\"\n",
660 ]
661 )
662
663 copy(dummy_plugin_path, join(home_path, "copy_dummy.py"))
664
665 # To confirm we won't load this module _without_ the init hook running.
666 assert home_path not in sys.path
667
668 run = Run(
669 [
670 "--rcfile",
671 pylintrc_file,
672 "--load-plugins",
673 "copy_dummy",
674 join(REGRTEST_DATA_DIR, "empty.py"),
675 ],
676 reporter=testutils.GenericTestReporter(),
677 exit=False,
678 )
679 assert run._rcfile == pylintrc_file
680 assert home_path in sys.path
681 # The module should not be loaded
682 assert not any(ch.name == "dummy_plugin" for ch in run.linter.get_checkers())
683
684 # There should be a bad-plugin-message for this module
685 assert len(run.linter.reporter.messages) == 1
686 assert run.linter.reporter.messages[0] == Message(
687 msg_id="E0013",
688 symbol="bad-plugin-value",
689 msg="Plugin 'copy_dummy' is impossible to load, is it installed ? ('No module named 'copy_dummy'')",
690 confidence=interfaces.Confidence(
691 name="UNDEFINED",
692 description="Warning without any associated confidence level.",
693 ),
694 location=MessageLocationTuple(
695 abspath="Command line or configuration file",
696 path="Command line or configuration file",
697 module="Command line or configuration file",
698 obj="",
699 line=1,
700 column=0,
701 end_line=None,
702 end_column=None,
703 ),
704 )
705
706 # Necessary as the executed init-hook modifies sys.path
707 sys.path.remove(home_path)
708
709
710 @pytest.mark.usefixtures("pop_pylintrc")
711 def test_load_plugin_pylintrc_order_independent() -> None:
712 """Test that the init-hook is called independent of the order in a config file.
713
714 We want to ensure that any path manipulation in init hook
715 that means a plugin can load (as per GitHub Issue #7264 Cases 4+7)
716 runs before the load call, regardless of the order of lines in the
717 pylintrc file.
718 """
719 dummy_plugin_path = abspath(
720 join(REGRTEST_DATA_DIR, "dummy_plugin", "dummy_plugin.py")
721 )
722
723 with fake_home() as home_path:
724 copy(dummy_plugin_path, join(home_path, "copy_dummy.py"))
725 # construct a basic rc file that just modifies the path
726 pylintrc_file_before = join(home_path, "pylintrc_before")
727 with open(pylintrc_file_before, "w", encoding="utf8") as out:
728 out.writelines(
729 [
730 "[MASTER]\n",
731 f"init-hook=\"import sys; sys.path.append(r'{home_path}')\"\n",
732 "load-plugins=copy_dummy\n",
733 ]
734 )
735 pylintrc_file_after = join(home_path, "pylintrc_after")
736 with open(pylintrc_file_after, "w", encoding="utf8") as out:
737 out.writelines(
738 [
739 "[MASTER]\n",
740 "load-plugins=copy_dummy\n"
741 f"init-hook=\"import sys; sys.path.append(r'{home_path}')\"\n",
742 ]
743 )
744 for rcfile in (pylintrc_file_before, pylintrc_file_after):
745 # To confirm we won't load this module _without_ the init hook running.
746 assert home_path not in sys.path
747 run = Run(
748 [
749 "--rcfile",
750 rcfile,
751 join(REGRTEST_DATA_DIR, "empty.py"),
752 ],
753 exit=False,
754 )
755 assert (
756 len(
757 [
758 ch.name
759 for ch in run.linter.get_checkers()
760 if ch.name == "dummy_plugin"
761 ]
762 )
763 == 2
764 )
765 assert run._rcfile == rcfile
766 assert home_path in sys.path
767
768 # Necessary as the executed init-hook modifies sys.path
769 sys.path.remove(home_path)
770
771
772 def test_load_plugin_command_line_before_init_hook() -> None:
773 """Check that the order of 'load-plugins' and 'init-hook' doesn't affect execution."""
774 dummy_plugin_path = abspath(
775 join(REGRTEST_DATA_DIR, "dummy_plugin", "dummy_plugin.py")
776 )
777
778 with fake_home() as home_path:
779 copy(dummy_plugin_path, join(home_path, "copy_dummy.py"))
780 # construct a basic rc file that just modifies the path
781 assert home_path not in sys.path
782 run = Run(
783 [
784 "--load-plugins",
785 "copy_dummy",
786 "--init-hook",
787 f'import sys; sys.path.append(r"{home_path}")',
788 join(REGRTEST_DATA_DIR, "empty.py"),
789 ],
790 exit=False,
791 )
792 assert home_path in sys.path
793 assert (
794 len(
795 [
796 ch.name
797 for ch in run.linter.get_checkers()
798 if ch.name == "dummy_plugin"
799 ]
800 )
801 == 2
802 )
803
804 # Necessary as the executed init-hook modifies sys.path
805 sys.path.remove(home_path)
806
807
808 def test_load_plugin_command_line_with_init_hook_command_line() -> None:
809 dummy_plugin_path = abspath(
810 join(REGRTEST_DATA_DIR, "dummy_plugin", "dummy_plugin.py")
811 )
812
813 with fake_home() as home_path:
814 copy(dummy_plugin_path, join(home_path, "copy_dummy.py"))
815 # construct a basic rc file that just modifies the path
816 assert home_path not in sys.path
817 run = Run(
818 [
819 "--init-hook",
820 f'import sys; sys.path.append(r"{home_path}")',
821 "--load-plugins",
822 "copy_dummy",
823 join(REGRTEST_DATA_DIR, "empty.py"),
824 ],
825 exit=False,
826 )
827 assert (
828 len(
829 [
830 ch.name
831 for ch in run.linter.get_checkers()
832 if ch.name == "dummy_plugin"
833 ]
834 )
835 == 2
836 )
837 assert home_path in sys.path
838
839 # Necessary as the executed init-hook modifies sys.path
840 sys.path.remove(home_path)
841
842
843 def test_load_plugin_config_file() -> None:
844 dummy_plugin_path = join(REGRTEST_DATA_DIR, "dummy_plugin")
845 sys.path.append(dummy_plugin_path)
846 config_path = join(REGRTEST_DATA_DIR, "dummy_plugin.rc")
847
848 run = Run(
849 ["--rcfile", config_path, join(REGRTEST_DATA_DIR, "empty.py")],
850 exit=False,
851 )
852 assert (
853 len([ch.name for ch in run.linter.get_checkers() if ch.name == "dummy_plugin"])
854 == 2
855 )
856
857 sys.path.remove(dummy_plugin_path)
858
859
860 def test_load_plugin_configuration() -> None:
861 dummy_plugin_path = join(REGRTEST_DATA_DIR, "dummy_plugin")
862 sys.path.append(dummy_plugin_path)
863
864 run = Run(
865 [
866 "--load-plugins",
867 "dummy_conf_plugin",
868 "--ignore",
869 "foo,bar",
870 join(REGRTEST_DATA_DIR, "empty.py"),
871 ],
872 exit=False,
873 )
874
875 sys.path.remove(dummy_plugin_path)
876 assert run.linter.config.ignore == ["foo", "bar", "bin"]
877
878
879 def test_init_hooks_called_before_load_plugins() -> None:
880 with pytest.raises(RuntimeError):
881 Run(["--load-plugins", "unexistant", "--init-hook", "raise RuntimeError"])
882 with pytest.raises(RuntimeError):
883 Run(["--init-hook", "raise RuntimeError", "--load-plugins", "unexistant"])
884 with pytest.raises(SystemExit):
885 Run(["--init-hook"])
886
887
888 def test_analyze_explicit_script(linter: PyLinter) -> None:
889 linter.set_reporter(testutils.GenericTestReporter())
890 linter.check([os.path.join(DATA_DIR, "a_script")])
891 assert len(linter.reporter.messages) == 1
892 assert linter.reporter.messages[0] == Message(
893 msg_id="C0301",
894 symbol="line-too-long",
895 msg="Line too long (175/100)",
896 confidence=interfaces.Confidence(
897 name="UNDEFINED",
898 description="Warning without any associated confidence level.",
899 ),
900 location=MessageLocationTuple(
901 abspath=os.path.join(abspath(dirname(__file__)), "a_script").replace(
902 f"lint{os.path.sep}a_script", f"data{os.path.sep}a_script"
903 ),
904 path=f"tests{os.path.sep}data{os.path.sep}a_script",
905 module="data.a_script",
906 obj="",
907 line=2,
908 column=0,
909 end_line=None,
910 end_column=None,
911 ),
912 )
913
914
915 def test_full_documentation(linter: PyLinter) -> None:
916 out = StringIO()
917 print_full_documentation(linter, out)
918 output = out.getvalue()
919 # A few spot checks only
920 for re_str in (
921 # auto-generated text
922 "^Pylint global options and switches$",
923 "Verbatim name of the checker is ``variables``",
924 # messages
925 "^:undefined-loop-variable \\(W0631\\): *",
926 # options
927 "^:dummy-variables-rgx:",
928 ):
929 regexp = re.compile(re_str, re.MULTILINE)
930 assert re.search(regexp, output)
931
932
933 def test_list_msgs_enabled(
934 initialized_linter: PyLinter, capsys: CaptureFixture[str]
935 ) -> None:
936 linter = initialized_linter
937 linter.enable("W0101", scope="package")
938 linter.disable("W0102", scope="package")
939 linter.list_messages_enabled()
940
941 lines = capsys.readouterr().out.splitlines()
942
943 assert "Enabled messages:" in lines
944 assert " unreachable (W0101)" in lines
945
946 assert "Disabled messages:" in lines
947 disabled_ix = lines.index("Disabled messages:")
948
949 # W0101 should be in the enabled section
950 assert lines.index(" unreachable (W0101)") < disabled_ix
951
952 assert " dangerous-default-value (W0102)" in lines
953 # W0102 should be in the disabled section
954 assert lines.index(" dangerous-default-value (W0102)") > disabled_ix
955
956
957 @pytest.fixture
958 def pop_pylintrc() -> None:
959 os.environ.pop("PYLINTRC", None)
960
961
962 @pytest.mark.usefixtures("pop_pylintrc")
963 def test_pylint_home() -> None:
964 expected = platformdirs.user_cache_dir("pylint")
965 assert constants.PYLINT_HOME == expected
966 assert PYLINT_HOME == expected
967
968
969 @mock.patch.dict(os.environ, {"PYLINTHOME": "whatever.d"})
970 def test_pylint_home_from_environ() -> None:
971 assert _get_pylint_home() == "whatever.d"
972
973
974 class _CustomPyLinter(PyLinter):
975 @staticmethod
976 def should_analyze_file(modname: str, path: str, is_argument: bool = False) -> bool:
977 if os.path.basename(path) == "wrong.py":
978 return False
979
980 return super(_CustomPyLinter, _CustomPyLinter).should_analyze_file(
981 modname, path, is_argument=is_argument
982 )
983
984
985 @pytest.mark.needs_two_cores
986 def test_custom_should_analyze_file() -> None:
987 """Check that we can write custom should_analyze_file that work
988 even for arguments.
989 """
990 package_dir = os.path.join(REGRTEST_DATA_DIR, "bad_package")
991 wrong_file = os.path.join(package_dir, "wrong.py")
992
993 for jobs in (1, 2):
994 reporter = testutils.GenericTestReporter()
995 linter = _CustomPyLinter()
996 linter.config.jobs = jobs
997 linter.config.persistent = 0
998 linter.open()
999 linter.set_reporter(reporter)
1000
1001 try:
1002 sys.path.append(os.path.dirname(package_dir))
1003 linter.check([package_dir, wrong_file])
1004 finally:
1005 sys.path.pop()
1006
1007 messages = reporter.messages
1008 assert len(messages) == 1
1009 assert "invalid syntax" in messages[0].msg
1010
1011
1012 # we do the check with jobs=1 as well, so that we are sure that the duplicates
1013 # are created by the multiprocessing problem.
1014 @pytest.mark.needs_two_cores
1015 @pytest.mark.parametrize("jobs", [1, 2])
1016 def test_multiprocessing(jobs: int) -> None:
1017 """Check that multiprocessing does not create duplicates."""
1018 # For the bug (#3584) to show up we need more than one file with issues
1019 # per process
1020 filenames = [
1021 "special_attr_scope_lookup_crash.py",
1022 "syntax_error.py",
1023 "unused_variable.py",
1024 "wildcard.py",
1025 "wrong_import_position.py",
1026 ]
1027
1028 reporter = testutils.GenericTestReporter()
1029 linter = PyLinter()
1030 linter.config.jobs = jobs
1031 linter.config.persistent = 0
1032 linter.open()
1033 linter.set_reporter(reporter)
1034
1035 try:
1036 sys.path.append(os.path.dirname(REGRTEST_DATA_DIR))
1037 linter.check([os.path.join(REGRTEST_DATA_DIR, fname) for fname in filenames])
1038 finally:
1039 sys.path.pop()
1040
1041 messages = reporter.messages
1042 assert len(messages) == len(set(messages))
1043
1044
1045 def test_filename_with__init__(initialized_linter: PyLinter) -> None:
1046 # This tracks a regression where a file whose name ends in __init__.py,
1047 # such as flycheck__init__.py, would accidentally lead to linting the
1048 # entire containing directory.
1049 reporter = testutils.GenericTestReporter()
1050 linter = initialized_linter
1051 linter.open()
1052 linter.set_reporter(reporter)
1053 filepath = join(INPUT_DIR, "not__init__.py")
1054 linter.check([filepath])
1055 messages = reporter.messages
1056 assert len(messages) == 0
1057
1058
1059 def test_by_module_statement_value(initialized_linter: PyLinter) -> None:
1060 """Test "statement" for each module analyzed of computed correctly."""
1061 linter = initialized_linter
1062 linter.check([os.path.join(os.path.dirname(__file__), "data")])
1063
1064 by_module_stats = linter.stats.by_module
1065 for module, module_stats in by_module_stats.items():
1066 linter2 = initialized_linter
1067 linter2.stats = LinterStats()
1068
1069 if module == "data":
1070 linter2.check([os.path.join(os.path.dirname(__file__), "data/__init__.py")])
1071 else:
1072 linter2.check([os.path.join(os.path.dirname(__file__), module)])
1073
1074 # Check that the by_module "statement" is equal to the global "statement"
1075 # computed for that module
1076 assert module_stats["statement"] == linter2.stats.statement
1077
1078
1079 def test_finds_pyi_file() -> None:
1080 run = Run(
1081 ["--prefer-stubs=y", join(REGRTEST_DATA_DIR, "pyi")],
1082 exit=False,
1083 )
1084 assert run.linter.current_file is not None
1085 assert run.linter.current_file.endswith(
1086 "a_module_that_we_definitely_dont_use_in_the_functional_tests.pyi"
1087 )
1088
1089
1090 def test_recursive_finds_pyi_file() -> None:
1091 run = Run(
1092 [
1093 "--recursive",
1094 "y",
1095 "--prefer-stubs",
1096 "y",
1097 join(REGRTEST_DATA_DIR, "pyi"),
1098 ],
1099 exit=False,
1100 )
1101 assert run.linter.current_file is not None
1102 assert run.linter.current_file.endswith(
1103 "a_module_that_we_definitely_dont_use_in_the_functional_tests.pyi"
1104 )
1105
1106
1107 def test_no_false_positive_from_pyi_stub() -> None:
1108 run = Run(
1109 [
1110 "--recursive",
1111 "y",
1112 "--prefer-stubs",
1113 "n",
1114 join(REGRTEST_DATA_DIR, "uses_module_with_stub.py"),
1115 ],
1116 exit=False,
1117 )
1118 assert not run.linter.stats.by_msg
1119
1120
1121 @pytest.mark.parametrize(
1122 "ignore_parameter,ignore_parameter_value",
1123 [
1124 ("--ignore", "failing.py"),
1125 ("--ignore", "ignored_subdirectory"),
1126 ("--ignore-patterns", "failing.*"),
1127 ("--ignore-patterns", "ignored_*"),
1128 ("--ignore-paths", ".*directory/ignored.*"),
1129 ("--ignore-paths", ".*ignored.*/failing.*"),
1130 ],
1131 )
1132 def test_recursive_ignore(ignore_parameter: str, ignore_parameter_value: str) -> None:
1133 run = Run(
1134 [
1135 "--recursive",
1136 "y",
1137 ignore_parameter,
1138 ignore_parameter_value,
1139 join(REGRTEST_DATA_DIR, "directory"),
1140 ],
1141 exit=False,
1142 )
1143
1144 linted_files = run.linter._iterate_file_descrs(
1145 tuple(run.linter._discover_files([join(REGRTEST_DATA_DIR, "directory")]))
1146 )
1147 linted_file_paths = [file_item.filepath for file_item in linted_files]
1148
1149 ignored_file = os.path.abspath(
1150 join(REGRTEST_DATA_DIR, "directory", "ignored_subdirectory", "failing.py")
1151 )
1152 assert ignored_file not in linted_file_paths
1153
1154 for regrtest_data_module in (
1155 ("directory", "subdirectory", "subsubdirectory", "module.py"),
1156 ("directory", "subdirectory", "module.py"),
1157 ("directory", "package", "module.py"),
1158 ("directory", "package", "subpackage", "module.py"),
1159 ):
1160 module = os.path.abspath(join(REGRTEST_DATA_DIR, *regrtest_data_module))
1161 assert module in linted_file_paths
1162 # We lint the modules in `regrtest` in other tests as well. Prevent test pollution by
1163 # explicitly clearing the astroid caches.
1164 astroid.MANAGER.clear_cache()
1165
1166
1167 def test_source_roots_globbing() -> None:
1168 run = Run(
1169 [
1170 "--source-roots",
1171 join(REGRTEST_DATA_DIR, "pep420", "basic", "*"),
1172 join(REGRTEST_DATA_DIR, "pep420", "basic", "project"),
1173 ],
1174 exit=False,
1175 )
1176 assert run.linter.config.source_roots == [
1177 join(REGRTEST_DATA_DIR, "pep420", "basic", "project")
1178 ]
1179
1180
1181 def test_recursive_implicit_namespace() -> None:
1182 run = Run(
1183 [
1184 "--verbose",
1185 "--recursive",
1186 "y",
1187 "--source-roots",
1188 join(REGRTEST_DATA_DIR, "pep420", "basic", "project"),
1189 join(REGRTEST_DATA_DIR, "pep420", "basic"),
1190 ],
1191 exit=False,
1192 )
1193 assert run.linter.file_state.base_name == "namespace.package"
1194
1195
1196 def test_recursive_implicit_namespace_wrapper() -> None:
1197 run = Run(
1198 [
1199 "--recursive",
1200 "y",
1201 "--source-roots",
1202 join(REGRTEST_DATA_DIR, "pep420", "wrapper", "project"),
1203 join(REGRTEST_DATA_DIR, "pep420", "wrapper"),
1204 ],
1205 exit=False,
1206 )
1207 run.linter.set_reporter(testutils.GenericTestReporter())
1208 run.linter.check([join(REGRTEST_DATA_DIR, "pep420", "wrapper")])
1209 assert run.linter.reporter.messages == []
1210
1211
1212 def test_globbing() -> None:
1213 run = Run(
1214 [
1215 "--verbose",
1216 "--source-roots",
1217 join(REGRTEST_DATA_DIR, "pep420", "basic", "project"),
1218 join(REGRTEST_DATA_DIR, "pep420", "basic", "project", "**", "__init__.py"),
1219 ],
1220 exit=False,
1221 )
1222 assert run.linter.file_state.base_name == "namespace.package.__init__"
1223
1224
1225 def test_relative_imports(initialized_linter: PyLinter) -> None:
1226 """Regression test for https://github.com/pylint-dev/pylint/issues/3651."""
1227 linter = initialized_linter
1228 with tempdir() as tmpdir:
1229 create_files(["x/y/__init__.py", "x/y/one.py", "x/y/two.py"], tmpdir)
1230 with open("x/y/__init__.py", "w", encoding="utf-8") as f:
1231 f.write(
1232 """
1233 \"\"\"Module x.y\"\"\"
1234 from .one import ONE
1235 from .two import TWO
1236 """
1237 )
1238 with open("x/y/one.py", "w", encoding="utf-8") as f:
1239 f.write(
1240 """
1241 \"\"\"Module x.y.one\"\"\"
1242 ONE = 1
1243 """
1244 )
1245 with open("x/y/two.py", "w", encoding="utf-8") as f:
1246 f.write(
1247 """
1248 \"\"\"Module x.y.two\"\"\"
1249 from .one import ONE
1250 TWO = ONE + ONE
1251 """
1252 )
1253 linter.check(["x/y"])
1254 assert not linter.stats.by_msg
1255
1256
1257 def test_import_sibling_module_from_namespace(initialized_linter: PyLinter) -> None:
1258 """If the parent directory above `namespace` is on sys.path, ensure that
1259 modules under `namespace` can import each other without raising `import-error`.
1260 """
1261 linter = initialized_linter
1262 with tempdir() as tmpdir:
1263 create_files(["namespace/submodule1.py", "namespace/submodule2.py"])
1264 second_path = Path("namespace/submodule2.py")
1265 with open(second_path, "w", encoding="utf-8") as f:
1266 f.write(
1267 """\"\"\"This module imports submodule1.\"\"\"
1268 import submodule1
1269 print(submodule1)
1270 """
1271 )
1272 os.chdir("namespace")
1273 extra_sys_paths = [expand_modules.discover_package_path(tmpdir, [])]
1274
1275 # Add the parent directory to sys.path
1276 with lint.augmented_sys_path(extra_sys_paths):
1277 linter.check(["submodule2.py"])
1278 assert not linter.stats.by_msg
1279
1280
1281 def test_lint_namespace_package_under_dir(initialized_linter: PyLinter) -> None:
1282 """Regression test for https://github.com/pylint-dev/pylint/issues/1667."""
1283 linter = initialized_linter
1284 with tempdir():
1285 create_files(["outer/namespace/__init__.py", "outer/namespace/module.py"])
1286 linter.check(["outer.namespace"])
1287 assert not linter.stats.by_msg
1288
1289
1290 def test_lint_namespace_package_under_dir_on_path(initialized_linter: PyLinter) -> None:
1291 """If the directory above a namespace package is on sys.path,
1292 the namespace module under it is linted.
1293 """
1294 linter = initialized_linter
1295 with tempdir() as tmpdir:
1296 create_files(["namespace_on_path/submodule1.py"])
1297 os.chdir(tmpdir)
1298 extra_sys_paths = [expand_modules.discover_package_path(tmpdir, [])]
1299 with lint.augmented_sys_path(extra_sys_paths):
1300 linter.check(["namespace_on_path"])
1301 assert linter.file_state.base_name == "namespace_on_path"