lint_module_test.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. from __future__ import annotations
  5. import csv
  6. import operator
  7. import platform
  8. import sys
  9. from collections import Counter
  10. from io import StringIO
  11. from pathlib import Path
  12. from typing import Counter as CounterType
  13. from typing import TextIO, Tuple
  14. import pytest
  15. from _pytest.config import Config
  16. from pylint import checkers
  17. from pylint.config.config_initialization import _config_initialization
  18. from pylint.constants import IS_PYPY
  19. from pylint.lint import PyLinter
  20. from pylint.message.message import Message
  21. from pylint.testutils.constants import _EXPECTED_RE, _OPERATORS, UPDATE_OPTION
  22. # need to import from functional.test_file to avoid cyclic import
  23. from pylint.testutils.functional.test_file import (
  24. FunctionalTestFile,
  25. NoFileError,
  26. parse_python_version,
  27. )
  28. from pylint.testutils.output_line import OutputLine
  29. from pylint.testutils.reporter_for_tests import FunctionalTestReporter
  30. MessageCounter = CounterType[Tuple[int, str]]
  31. PYLINTRC = Path(__file__).parent / "testing_pylintrc"
  32. class LintModuleTest:
  33. maxDiff = None
  34. def __init__(
  35. self, test_file: FunctionalTestFile, config: Config | None = None
  36. ) -> None:
  37. _test_reporter = FunctionalTestReporter()
  38. self._linter = PyLinter()
  39. self._linter.config.persistent = 0
  40. checkers.initialize(self._linter)
  41. # See if test has its own .rc file, if so we use that one
  42. rc_file: Path | str = PYLINTRC
  43. try:
  44. rc_file = test_file.option_file
  45. self._linter.disable("suppressed-message")
  46. self._linter.disable("locally-disabled")
  47. self._linter.disable("useless-suppression")
  48. except NoFileError:
  49. pass
  50. self._test_file = test_file
  51. try:
  52. args = [test_file.source]
  53. except NoFileError:
  54. # If we're still raising NoFileError the actual source file doesn't exist
  55. args = [""]
  56. if config and config.getoption("minimal_messages_config"):
  57. with self._open_source_file() as f:
  58. messages_to_enable = {msg[1] for msg in self.get_expected_messages(f)}
  59. # Always enable fatal errors
  60. messages_to_enable.add("astroid-error")
  61. messages_to_enable.add("fatal")
  62. messages_to_enable.add("syntax-error")
  63. args.extend(["--disable=all", f"--enable={','.join(messages_to_enable)}"])
  64. # Add testoptions
  65. self._linter._arg_parser.add_argument(
  66. "--min_pyver", type=parse_python_version, default=(2, 5)
  67. )
  68. self._linter._arg_parser.add_argument(
  69. "--max_pyver", type=parse_python_version, default=(4, 0)
  70. )
  71. self._linter._arg_parser.add_argument(
  72. "--min_pyver_end_position", type=parse_python_version, default=(3, 8)
  73. )
  74. self._linter._arg_parser.add_argument(
  75. "--requires", type=lambda s: [i.strip() for i in s.split(",")], default=[]
  76. )
  77. self._linter._arg_parser.add_argument(
  78. "--except_implementations",
  79. type=lambda s: [i.strip() for i in s.split(",")],
  80. default=[],
  81. )
  82. self._linter._arg_parser.add_argument(
  83. "--exclude_platforms",
  84. type=lambda s: [i.strip() for i in s.split(",")],
  85. default=[],
  86. )
  87. self._linter._arg_parser.add_argument(
  88. "--exclude_from_minimal_messages_config", default=False
  89. )
  90. _config_initialization(
  91. self._linter, args_list=args, config_file=rc_file, reporter=_test_reporter
  92. )
  93. self._check_end_position = (
  94. sys.version_info >= self._linter.config.min_pyver_end_position
  95. )
  96. # TODO: PY3.9: PyPy supports end_lineno from 3.9 and above
  97. if self._check_end_position and IS_PYPY:
  98. self._check_end_position = sys.version_info >= (3, 9) # pragma: no cover
  99. self._config = config
  100. def setUp(self) -> None:
  101. if self._should_be_skipped_due_to_version():
  102. pytest.skip(
  103. f"Test cannot run with Python {sys.version.split(' ', maxsplit=1)[0]}."
  104. )
  105. missing = []
  106. for requirement in self._linter.config.requires:
  107. try:
  108. __import__(requirement)
  109. except ImportError:
  110. missing.append(requirement)
  111. if missing:
  112. pytest.skip(f"Requires {','.join(missing)} to be present.")
  113. except_implementations = self._linter.config.except_implementations
  114. if except_implementations:
  115. if platform.python_implementation() in except_implementations:
  116. msg = "Test cannot run with Python implementation %r"
  117. pytest.skip(msg % platform.python_implementation())
  118. excluded_platforms = self._linter.config.exclude_platforms
  119. if excluded_platforms:
  120. if sys.platform.lower() in excluded_platforms:
  121. pytest.skip(f"Test cannot run on platform {sys.platform!r}")
  122. if (
  123. self._config
  124. and self._config.getoption("minimal_messages_config")
  125. and self._linter.config.exclude_from_minimal_messages_config
  126. ):
  127. pytest.skip("Test excluded from --minimal-messages-config")
  128. def runTest(self) -> None:
  129. self._runTest()
  130. def _should_be_skipped_due_to_version(self) -> bool:
  131. return ( # type: ignore[no-any-return]
  132. sys.version_info < self._linter.config.min_pyver
  133. or sys.version_info > self._linter.config.max_pyver
  134. )
  135. def __str__(self) -> str:
  136. return f"{self._test_file.base} ({self.__class__.__module__}.{self.__class__.__name__})"
  137. @staticmethod
  138. def get_expected_messages(stream: TextIO) -> MessageCounter:
  139. """Parses a file and get expected messages.
  140. :param stream: File-like input stream.
  141. :type stream: enumerable
  142. :returns: A dict mapping line,msg-symbol tuples to the count on this line.
  143. :rtype: dict
  144. """
  145. messages: MessageCounter = Counter()
  146. for i, line in enumerate(stream):
  147. match = _EXPECTED_RE.search(line)
  148. if match is None:
  149. continue
  150. line = match.group("line")
  151. if line is None:
  152. lineno = i + 1
  153. elif line.startswith("+") or line.startswith("-"):
  154. lineno = i + 1 + int(line)
  155. else:
  156. lineno = int(line)
  157. version = match.group("version")
  158. op = match.group("op")
  159. if version:
  160. required = parse_python_version(version)
  161. if not _OPERATORS[op](sys.version_info, required):
  162. continue
  163. for msg_id in match.group("msgs").split(","):
  164. messages[lineno, msg_id.strip()] += 1
  165. return messages
  166. @staticmethod
  167. def multiset_difference(
  168. expected_entries: MessageCounter,
  169. actual_entries: MessageCounter,
  170. ) -> tuple[MessageCounter, dict[tuple[int, str], int]]:
  171. """Takes two multisets and compares them.
  172. A multiset is a dict with the cardinality of the key as the value.
  173. """
  174. missing = expected_entries.copy()
  175. missing.subtract(actual_entries)
  176. unexpected = {}
  177. for key, value in list(missing.items()):
  178. if value <= 0:
  179. missing.pop(key)
  180. if value < 0:
  181. unexpected[key] = -value
  182. return missing, unexpected
  183. def _open_expected_file(self) -> TextIO:
  184. try:
  185. return open(self._test_file.expected_output, encoding="utf-8")
  186. except FileNotFoundError:
  187. return StringIO("")
  188. def _open_source_file(self) -> TextIO:
  189. if self._test_file.base == "invalid_encoded_data":
  190. return open(self._test_file.source, encoding="utf-8")
  191. if "latin1" in self._test_file.base:
  192. return open(self._test_file.source, encoding="latin1")
  193. return open(self._test_file.source, encoding="utf8")
  194. def _get_expected(self) -> tuple[MessageCounter, list[OutputLine]]:
  195. with self._open_source_file() as f:
  196. expected_msgs = self.get_expected_messages(f)
  197. if not expected_msgs:
  198. expected_msgs = Counter()
  199. with self._open_expected_file() as f:
  200. expected_output_lines = [
  201. OutputLine.from_csv(row, self._check_end_position)
  202. for row in csv.reader(f, "test")
  203. ]
  204. return expected_msgs, expected_output_lines
  205. def _get_actual(self) -> tuple[MessageCounter, list[OutputLine]]:
  206. messages: list[Message] = self._linter.reporter.messages
  207. messages.sort(key=lambda m: (m.line, m.symbol, m.msg))
  208. received_msgs: MessageCounter = Counter()
  209. received_output_lines = []
  210. for msg in messages:
  211. assert (
  212. msg.symbol != "fatal"
  213. ), f"Pylint analysis failed because of '{msg.msg}'"
  214. received_msgs[msg.line, msg.symbol] += 1
  215. received_output_lines.append(
  216. OutputLine.from_msg(msg, self._check_end_position)
  217. )
  218. return received_msgs, received_output_lines
  219. def _runTest(self) -> None:
  220. __tracebackhide__ = True # pylint: disable=unused-variable
  221. modules_to_check = [self._test_file.source]
  222. self._linter.check(modules_to_check)
  223. expected_messages, expected_output = self._get_expected()
  224. actual_messages, actual_output = self._get_actual()
  225. assert (
  226. expected_messages == actual_messages
  227. ), self.error_msg_for_unequal_messages(
  228. actual_messages, expected_messages, actual_output
  229. )
  230. self._check_output_text(expected_messages, expected_output, actual_output)
  231. def error_msg_for_unequal_messages(
  232. self,
  233. actual_messages: MessageCounter,
  234. expected_messages: MessageCounter,
  235. actual_output: list[OutputLine],
  236. ) -> str:
  237. msg = [f'Wrong results for file "{self._test_file.base}":']
  238. missing, unexpected = self.multiset_difference(
  239. expected_messages, actual_messages
  240. )
  241. if missing:
  242. msg.append("\nExpected in testdata:")
  243. msg.extend(f" {msg[0]:3}: {msg[1]}" for msg in sorted(missing))
  244. if unexpected:
  245. msg.append("\nUnexpected in testdata:")
  246. msg.extend(f" {msg[0]:3}: {msg[1]}" for msg in sorted(unexpected))
  247. error_msg = "\n".join(msg)
  248. if self._config and self._config.getoption("verbose") > 0:
  249. error_msg += "\n\nActual pylint output for this file:\n"
  250. error_msg += "\n".join(str(o) for o in actual_output)
  251. return error_msg
  252. def error_msg_for_unequal_output(
  253. self,
  254. expected_lines: list[OutputLine],
  255. received_lines: list[OutputLine],
  256. ) -> str:
  257. missing = set(expected_lines) - set(received_lines)
  258. unexpected = set(received_lines) - set(expected_lines)
  259. error_msg = f"Wrong output for '{self._test_file.base}.txt':"
  260. sort_by_line_number = operator.attrgetter("lineno")
  261. if missing:
  262. error_msg += "\n- Missing lines:\n"
  263. for line in sorted(missing, key=sort_by_line_number):
  264. error_msg += f"{line}\n"
  265. if unexpected:
  266. error_msg += "\n- Unexpected lines:\n"
  267. for line in sorted(unexpected, key=sort_by_line_number):
  268. error_msg += f"{line}\n"
  269. error_msg += (
  270. "\nYou can update the expected output automatically with:\n'"
  271. f"python tests/test_functional.py {UPDATE_OPTION} -k "
  272. f'"test_functional[{self._test_file.base}]"\'\n\n'
  273. "Here's the update text in case you can't:\n"
  274. )
  275. expected_csv = StringIO()
  276. writer = csv.writer(expected_csv, dialect="test")
  277. for line in sorted(received_lines, key=sort_by_line_number):
  278. writer.writerow(line.to_csv())
  279. error_msg += expected_csv.getvalue()
  280. return error_msg
  281. def _check_output_text(
  282. self,
  283. _: MessageCounter,
  284. expected_output: list[OutputLine],
  285. actual_output: list[OutputLine],
  286. ) -> None:
  287. """This is a function because we want to be able to update the text in
  288. LintModuleOutputUpdate.
  289. """
  290. assert expected_output == actual_output, self.error_msg_for_unequal_output(
  291. expected_output, actual_output
  292. )