checker_test_case.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 contextlib
  4. from typing import Dict, Optional, Type
  5. from pylint.testutils.global_test_linter import linter
  6. from pylint.testutils.unittest_linter import UnittestLinter
  7. from pylint.utils import ASTWalker
  8. class CheckerTestCase:
  9. """A base testcase class for unit testing individual checker classes."""
  10. CHECKER_CLASS: Optional[Type] = None
  11. CONFIG: Dict = {}
  12. def setup_method(self):
  13. self.linter = UnittestLinter()
  14. self.checker = self.CHECKER_CLASS(self.linter) # pylint: disable=not-callable
  15. for key, value in self.CONFIG.items():
  16. setattr(self.checker.config, key, value)
  17. self.checker.open()
  18. @contextlib.contextmanager
  19. def assertNoMessages(self):
  20. """Assert that no messages are added by the given method."""
  21. with self.assertAddsMessages():
  22. yield
  23. @contextlib.contextmanager
  24. def assertAddsMessages(self, *messages):
  25. """Assert that exactly the given method adds the given messages.
  26. The list of messages must exactly match *all* the messages added by the
  27. method. Additionally, we check to see whether the args in each message can
  28. actually be substituted into the message string.
  29. """
  30. yield
  31. got = self.linter.release_messages()
  32. no_msg = "No message."
  33. expected = "\n".join(repr(m) for m in messages) or no_msg
  34. got_str = "\n".join(repr(m) for m in got) or no_msg
  35. msg = (
  36. "Expected messages did not match actual.\n"
  37. f"\nExpected:\n{expected}\n\nGot:\n{got_str}\n"
  38. )
  39. assert got == list(messages), msg
  40. def walk(self, node):
  41. """recursive walk on the given node"""
  42. walker = ASTWalker(linter)
  43. walker.add_checker(self.checker)
  44. walker.walk(node)