unittest_linter.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
  4. # pylint: disable=duplicate-code
  5. from __future__ import annotations
  6. import sys
  7. from typing import Any
  8. from astroid import nodes
  9. from pylint.interfaces import UNDEFINED, Confidence
  10. from pylint.lint import PyLinter
  11. from pylint.testutils.output_line import MessageTest
  12. if sys.version_info >= (3, 8):
  13. from typing import Literal
  14. else:
  15. from typing_extensions import Literal
  16. class UnittestLinter(PyLinter):
  17. """A fake linter class to capture checker messages."""
  18. def __init__(self) -> None:
  19. self._messages: list[MessageTest] = []
  20. super().__init__()
  21. def release_messages(self) -> list[MessageTest]:
  22. try:
  23. return self._messages
  24. finally:
  25. self._messages = []
  26. def add_message(
  27. self,
  28. msgid: str,
  29. line: int | None = None,
  30. # TODO: Make node non optional
  31. node: nodes.NodeNG | None = None,
  32. args: Any = None,
  33. confidence: Confidence | None = None,
  34. col_offset: int | None = None,
  35. end_lineno: int | None = None,
  36. end_col_offset: int | None = None,
  37. ) -> None:
  38. """Add a MessageTest to the _messages attribute of the linter class."""
  39. # If confidence is None we set it to UNDEFINED as well in PyLinter
  40. if confidence is None:
  41. confidence = UNDEFINED
  42. # Look up "location" data of node if not yet supplied
  43. if node:
  44. if node.position:
  45. if not line:
  46. line = node.position.lineno
  47. if not col_offset:
  48. col_offset = node.position.col_offset
  49. if not end_lineno:
  50. end_lineno = node.position.end_lineno
  51. if not end_col_offset:
  52. end_col_offset = node.position.end_col_offset
  53. else:
  54. if not line:
  55. line = node.fromlineno
  56. if not col_offset:
  57. col_offset = node.col_offset
  58. if not end_lineno:
  59. end_lineno = node.end_lineno
  60. if not end_col_offset:
  61. end_col_offset = node.end_col_offset
  62. self._messages.append(
  63. MessageTest(
  64. msgid,
  65. line,
  66. node,
  67. args,
  68. confidence,
  69. col_offset,
  70. end_lineno,
  71. end_col_offset,
  72. )
  73. )
  74. @staticmethod
  75. def is_message_enabled(*unused_args: Any, **unused_kwargs: Any) -> Literal[True]:
  76. return True