configuration_test.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. """Utility functions for configuration testing."""
  5. from __future__ import annotations
  6. import copy
  7. import json
  8. import logging
  9. import re
  10. import unittest
  11. from pathlib import Path
  12. from typing import Any, Dict
  13. from unittest.mock import Mock
  14. from pylint.constants import PY38_PLUS
  15. from pylint.lint import Run
  16. # We use Any in this typing because the configuration contains real objects and constants
  17. # that could be a lot of things.
  18. ConfigurationValue = Any
  19. PylintConfiguration = Dict[str, ConfigurationValue]
  20. if not PY38_PLUS:
  21. # We need to deepcopy a compiled regex pattern
  22. # In python 3.6 and 3.7 this requires a hack
  23. # See https://stackoverflow.com/a/56935186
  24. copy._deepcopy_dispatch[type(re.compile(""))] = lambda r, _: r # type: ignore[attr-defined]
  25. def get_expected_or_default(
  26. tested_configuration_file: str | Path,
  27. suffix: str,
  28. default: str,
  29. ) -> str:
  30. """Return the expected value from the file if it exists, or the given default."""
  31. expected = default
  32. path = Path(tested_configuration_file)
  33. expected_result_path = path.parent / f"{path.stem}.{suffix}"
  34. if expected_result_path.exists():
  35. with open(expected_result_path, encoding="utf8") as f:
  36. expected = f.read()
  37. # logging is helpful to realize your file is not taken into
  38. # account after a misspelling of the file name. The output of the
  39. # program is checked during the test so printing messes with the result.
  40. logging.info("%s exists.", expected_result_path)
  41. else:
  42. logging.info("%s not found, using '%s'.", expected_result_path, default)
  43. return expected
  44. EXPECTED_CONF_APPEND_KEY = "functional_append"
  45. EXPECTED_CONF_REMOVE_KEY = "functional_remove"
  46. def get_expected_configuration(
  47. configuration_path: str, default_configuration: PylintConfiguration
  48. ) -> PylintConfiguration:
  49. """Get the expected parsed configuration of a configuration functional test."""
  50. result = copy.deepcopy(default_configuration)
  51. config_as_json = get_expected_or_default(
  52. configuration_path, suffix="result.json", default="{}"
  53. )
  54. to_override = json.loads(config_as_json)
  55. for key, value in to_override.items():
  56. if key == EXPECTED_CONF_APPEND_KEY:
  57. for fkey, fvalue in value.items():
  58. result[fkey] += fvalue
  59. elif key == EXPECTED_CONF_REMOVE_KEY:
  60. for fkey, fvalue in value.items():
  61. new_value = []
  62. for old_value in result[fkey]:
  63. if old_value not in fvalue:
  64. new_value.append(old_value)
  65. result[fkey] = new_value
  66. else:
  67. result[key] = value
  68. return result
  69. def get_related_files(
  70. tested_configuration_file: str | Path, suffix_filter: str
  71. ) -> list[Path]:
  72. """Return all the file related to a test conf file ending with a suffix."""
  73. conf_path = Path(tested_configuration_file)
  74. return [
  75. p
  76. for p in conf_path.parent.iterdir()
  77. if str(p.stem).startswith(conf_path.stem) and str(p).endswith(suffix_filter)
  78. ]
  79. def get_expected_output(
  80. configuration_path: str | Path, user_specific_path: Path
  81. ) -> tuple[int, str]:
  82. """Get the expected output of a functional test."""
  83. exit_code = 0
  84. msg = (
  85. "we expect a single file of the form 'filename.32.out' where 'filename' represents "
  86. "the name of the configuration file, and '32' the expected error code."
  87. )
  88. possible_out_files = get_related_files(configuration_path, suffix_filter="out")
  89. if len(possible_out_files) > 1:
  90. logging.error(
  91. "Too much .out files for %s %s.",
  92. configuration_path,
  93. msg,
  94. )
  95. return -1, "out file is broken"
  96. if not possible_out_files:
  97. # logging is helpful to see what the expected exit code is and why.
  98. # The output of the program is checked during the test so printing
  99. # messes with the result.
  100. logging.info(".out file does not exists, so the expected exit code is 0")
  101. return 0, ""
  102. path = possible_out_files[0]
  103. try:
  104. exit_code = int(str(path.stem).rsplit(".", maxsplit=1)[-1])
  105. except Exception as e: # pylint: disable=broad-except
  106. logging.error(
  107. "Wrong format for .out file name for %s %s: %s",
  108. configuration_path,
  109. msg,
  110. e,
  111. )
  112. return -1, "out file is broken"
  113. output = get_expected_or_default(
  114. configuration_path, suffix=f"{exit_code}.out", default=""
  115. )
  116. logging.info(
  117. "Output exists for %s so the expected exit code is %s",
  118. configuration_path,
  119. exit_code,
  120. )
  121. return exit_code, output.format(
  122. abspath=configuration_path,
  123. relpath=Path(configuration_path).relative_to(user_specific_path),
  124. )
  125. def run_using_a_configuration_file(
  126. configuration_path: Path | str, file_to_lint: str = __file__
  127. ) -> tuple[Mock, Mock, Run]:
  128. """Simulate a run with a configuration without really launching the checks."""
  129. configuration_path = str(configuration_path)
  130. args = ["--rcfile", configuration_path, file_to_lint]
  131. # We do not capture the `SystemExit` as then the `runner` variable
  132. # would not be accessible outside the `with` block.
  133. with unittest.mock.patch("sys.exit") as mocked_exit:
  134. # Do not actually run checks, that could be slow. We don't mock
  135. # `PyLinter.check`: it calls `PyLinter.initialize` which is
  136. # needed to properly set up messages inclusion/exclusion
  137. # in `_msg_states`, used by `is_message_enabled`.
  138. check = "pylint.lint.pylinter.check_parallel"
  139. with unittest.mock.patch(check) as mocked_check_parallel:
  140. runner = Run(args)
  141. return mocked_exit, mocked_check_parallel, runner