lint_module_test.py 13 KB

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