lint_module_test.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  3. import csv
  4. import operator
  5. import platform
  6. import sys
  7. from collections import Counter
  8. from io import StringIO
  9. from typing import Counter as CounterType
  10. from typing import Dict, List, Optional, TextIO, Tuple
  11. import pytest
  12. from _pytest.config import Config
  13. from pylint import checkers
  14. from pylint.lint import PyLinter
  15. from pylint.message.message import Message
  16. from pylint.testutils.constants import _EXPECTED_RE, _OPERATORS, UPDATE_OPTION
  17. from pylint.testutils.functional_test_file import (
  18. FunctionalTestFile,
  19. NoFileError,
  20. parse_python_version,
  21. )
  22. from pylint.testutils.output_line import OutputLine
  23. from pylint.testutils.reporter_for_tests import FunctionalTestReporter
  24. from pylint.utils import utils
  25. MessageCounter = CounterType[Tuple[int, str]]
  26. class LintModuleTest:
  27. maxDiff = None
  28. def __init__(
  29. self, test_file: FunctionalTestFile, config: Optional[Config] = None
  30. ) -> None:
  31. _test_reporter = FunctionalTestReporter()
  32. self._linter = PyLinter()
  33. self._linter.set_reporter(_test_reporter)
  34. self._linter.config.persistent = 0
  35. checkers.initialize(self._linter)
  36. self._linter.disable("suppressed-message")
  37. self._linter.disable("locally-disabled")
  38. self._linter.disable("useless-suppression")
  39. try:
  40. self._linter.read_config_file(test_file.option_file)
  41. if self._linter.cfgfile_parser.has_option("MASTER", "load-plugins"):
  42. plugins = utils._splitstrip(
  43. self._linter.cfgfile_parser.get("MASTER", "load-plugins")
  44. )
  45. self._linter.load_plugin_modules(plugins)
  46. self._linter.load_config_file()
  47. except NoFileError:
  48. pass
  49. self._test_file = test_file
  50. self._config = config
  51. self._check_end_position = (
  52. sys.version_info >= self._test_file.options["min_pyver_end_position"]
  53. )
  54. def setUp(self) -> None:
  55. if self._should_be_skipped_due_to_version():
  56. pytest.skip(
  57. f"Test cannot run with Python {sys.version.split(' ', maxsplit=1)[0]}."
  58. )
  59. missing = []
  60. for requirement in self._test_file.options["requires"]:
  61. try:
  62. __import__(requirement)
  63. except ImportError:
  64. missing.append(requirement)
  65. if missing:
  66. pytest.skip(f"Requires {','.join(missing)} to be present.")
  67. except_implementations = self._test_file.options["except_implementations"]
  68. if except_implementations:
  69. implementations = [i.strip() for i in except_implementations.split(",")]
  70. if platform.python_implementation() in implementations:
  71. msg = "Test cannot run with Python implementation %r"
  72. pytest.skip(msg % platform.python_implementation())
  73. excluded_platforms = self._test_file.options["exclude_platforms"]
  74. if excluded_platforms:
  75. platforms = [p.strip() for p in excluded_platforms.split(",")]
  76. if sys.platform.lower() in platforms:
  77. pytest.skip(f"Test cannot run on platform {sys.platform!r}")
  78. def runTest(self) -> None:
  79. self._runTest()
  80. def _should_be_skipped_due_to_version(self) -> bool:
  81. return (
  82. sys.version_info < self._test_file.options["min_pyver"]
  83. or sys.version_info > self._test_file.options["max_pyver"]
  84. )
  85. def __str__(self) -> str:
  86. return f"{self._test_file.base} ({self.__class__.__module__}.{self.__class__.__name__})"
  87. @staticmethod
  88. def get_expected_messages(stream: TextIO) -> MessageCounter:
  89. """Parses a file and get expected messages.
  90. :param stream: File-like input stream.
  91. :type stream: enumerable
  92. :returns: A dict mapping line,msg-symbol tuples to the count on this line.
  93. :rtype: dict
  94. """
  95. messages: MessageCounter = Counter()
  96. for i, line in enumerate(stream):
  97. match = _EXPECTED_RE.search(line)
  98. if match is None:
  99. continue
  100. line = match.group("line")
  101. if line is None:
  102. lineno = i + 1
  103. elif line.startswith("+") or line.startswith("-"):
  104. lineno = i + 1 + int(line)
  105. else:
  106. lineno = int(line)
  107. version = match.group("version")
  108. op = match.group("op")
  109. if version:
  110. required = parse_python_version(version)
  111. if not _OPERATORS[op](sys.version_info, required):
  112. continue
  113. for msg_id in match.group("msgs").split(","):
  114. messages[lineno, msg_id.strip()] += 1
  115. return messages
  116. @staticmethod
  117. def multiset_difference(
  118. expected_entries: MessageCounter,
  119. actual_entries: MessageCounter,
  120. ) -> Tuple[MessageCounter, Dict[Tuple[int, str], int]]:
  121. """Takes two multisets and compares them.
  122. A multiset is a dict with the cardinality of the key as the value."""
  123. missing = expected_entries.copy()
  124. missing.subtract(actual_entries)
  125. unexpected = {}
  126. for key, value in list(missing.items()):
  127. if value <= 0:
  128. missing.pop(key)
  129. if value < 0:
  130. unexpected[key] = -value
  131. return missing, unexpected
  132. def _open_expected_file(self) -> TextIO:
  133. try:
  134. return open(self._test_file.expected_output, encoding="utf-8")
  135. except FileNotFoundError:
  136. return StringIO("")
  137. def _open_source_file(self) -> TextIO:
  138. if self._test_file.base == "invalid_encoded_data":
  139. return open(self._test_file.source, encoding="utf-8")
  140. if "latin1" in self._test_file.base:
  141. return open(self._test_file.source, encoding="latin1")
  142. return open(self._test_file.source, encoding="utf8")
  143. def _get_expected(self) -> Tuple[MessageCounter, List[OutputLine]]:
  144. with self._open_source_file() as f:
  145. expected_msgs = self.get_expected_messages(f)
  146. if not expected_msgs:
  147. expected_msgs = Counter()
  148. with self._open_expected_file() as f:
  149. expected_output_lines = [
  150. OutputLine.from_csv(row, self._check_end_position)
  151. for row in csv.reader(f, "test")
  152. ]
  153. return expected_msgs, expected_output_lines
  154. def _get_actual(self) -> Tuple[MessageCounter, List[OutputLine]]:
  155. messages: List[Message] = self._linter.reporter.messages
  156. messages.sort(key=lambda m: (m.line, m.symbol, m.msg))
  157. received_msgs: MessageCounter = Counter()
  158. received_output_lines = []
  159. for msg in messages:
  160. assert (
  161. msg.symbol != "fatal"
  162. ), f"Pylint analysis failed because of '{msg.msg}'"
  163. received_msgs[msg.line, msg.symbol] += 1
  164. received_output_lines.append(
  165. OutputLine.from_msg(msg, self._check_end_position)
  166. )
  167. return received_msgs, received_output_lines
  168. def _runTest(self) -> None:
  169. __tracebackhide__ = True # pylint: disable=unused-variable
  170. modules_to_check = [self._test_file.source]
  171. self._linter.check(modules_to_check)
  172. expected_messages, expected_output = self._get_expected()
  173. actual_messages, actual_output = self._get_actual()
  174. assert (
  175. expected_messages == actual_messages
  176. ), self.error_msg_for_unequal_messages(
  177. actual_messages, expected_messages, actual_output
  178. )
  179. self._check_output_text(expected_messages, expected_output, actual_output)
  180. def error_msg_for_unequal_messages(
  181. self,
  182. actual_messages: MessageCounter,
  183. expected_messages: MessageCounter,
  184. actual_output: List[OutputLine],
  185. ) -> str:
  186. msg = [f'Wrong results for file "{self._test_file.base}":']
  187. missing, unexpected = self.multiset_difference(
  188. expected_messages, actual_messages
  189. )
  190. if missing:
  191. msg.append("\nExpected in testdata:")
  192. msg.extend(f" {msg[0]:3}: {msg[1]}" for msg in sorted(missing))
  193. if unexpected:
  194. msg.append("\nUnexpected in testdata:")
  195. msg.extend(f" {msg[0]:3}: {msg[1]}" for msg in sorted(unexpected))
  196. error_msg = "\n".join(msg)
  197. if self._config and self._config.getoption("verbose") > 0:
  198. error_msg += "\n\nActual pylint output for this file:\n"
  199. error_msg += "\n".join(str(o) for o in actual_output)
  200. return error_msg
  201. def error_msg_for_unequal_output(
  202. self,
  203. expected_lines: List[OutputLine],
  204. received_lines: List[OutputLine],
  205. ) -> str:
  206. missing = set(expected_lines) - set(received_lines)
  207. unexpected = set(received_lines) - set(expected_lines)
  208. error_msg = (
  209. f"Wrong output for '{self._test_file.base}.txt':\n"
  210. "You can update the expected output automatically with: '"
  211. f"python tests/test_functional.py {UPDATE_OPTION} -k "
  212. f'"test_functional[{self._test_file.base}]"\'\n\n'
  213. )
  214. sort_by_line_number = operator.attrgetter("lineno")
  215. if missing:
  216. error_msg += "\n- Missing lines:\n"
  217. for line in sorted(missing, key=sort_by_line_number):
  218. error_msg += f"{line}\n"
  219. if unexpected:
  220. error_msg += "\n- Unexpected lines:\n"
  221. for line in sorted(unexpected, key=sort_by_line_number):
  222. error_msg += f"{line}\n"
  223. return error_msg
  224. def _check_output_text(
  225. self,
  226. _: MessageCounter,
  227. expected_output: List[OutputLine],
  228. actual_output: List[OutputLine],
  229. ) -> None:
  230. """This is a function because we want to be able to update the text in LintModuleOutputUpdate"""
  231. assert expected_output == actual_output, self.error_msg_for_unequal_output(
  232. expected_output, actual_output
  233. )