configuration_test.py 5.5 KB

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