flake8_plugin.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. from __future__ import annotations
  2. import ast
  3. from typing import Any, Generator
  4. S001_fmt = (
  5. "S001 Avoid using the {} mock call as it is "
  6. "confusing and prone to causing invalid test "
  7. "behavior."
  8. )
  9. S001_methods = frozenset(("not_called", "called_once", "called_once_with"))
  10. S002_msg = "S002 print functions or statements are not allowed."
  11. S003_msg = "S003 Use ``from sentry.utils import json`` instead."
  12. S003_modules = frozenset(("json", "simplejson"))
  13. S004_msg = "S004 Use `pytest.raises` instead for better debuggability."
  14. S004_methods = frozenset(("assertRaises", "assertRaisesRegex"))
  15. S005_msg = "S005 Do not import models from sentry.models but the actual module"
  16. S006_msg = "S006 Do not use force_bytes / force_str -- test the types directly"
  17. S007_msg = "S007 Do not import sentry.testutils into production code."
  18. S008_msg = "S008 Use stdlib datetime.timezone.utc instead of pytz.utc / pytz.UTC"
  19. S009_msg = "S009 Use `raise` with no arguments to reraise exceptions"
  20. S010_msg = "S010 Except handler does nothing and should be removed"
  21. S011_msg = "S011 Use override_options(...) instead to ensure proper cleanup"
  22. class SentryVisitor(ast.NodeVisitor):
  23. def __init__(self, filename: str) -> None:
  24. self.errors: list[tuple[int, int, str]] = []
  25. self.filename = filename
  26. self._except_vars: list[str | None] = []
  27. def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
  28. if node.module and not node.level:
  29. if node.module.split(".")[0] in S003_modules:
  30. self.errors.append((node.lineno, node.col_offset, S003_msg))
  31. elif node.module == "sentry.models":
  32. self.errors.append((node.lineno, node.col_offset, S005_msg))
  33. elif (
  34. "tests/" in self.filename
  35. and node.module == "django.utils.encoding"
  36. and any(x.name in {"force_bytes", "force_str"} for x in node.names)
  37. ):
  38. self.errors.append((node.lineno, node.col_offset, S006_msg))
  39. elif (
  40. "tests/" not in self.filename
  41. and "fixtures/" not in self.filename
  42. and "sentry/testutils/" not in self.filename
  43. and "sentry.testutils" in node.module
  44. ):
  45. self.errors.append((node.lineno, node.col_offset, S007_msg))
  46. if node.module == "pytz" and any(x.name.lower() == "utc" for x in node.names):
  47. self.errors.append((node.lineno, node.col_offset, S008_msg))
  48. self.generic_visit(node)
  49. def visit_Import(self, node: ast.Import) -> None:
  50. for alias in node.names:
  51. if alias.name.split(".")[0] in S003_modules:
  52. self.errors.append((node.lineno, node.col_offset, S003_msg))
  53. elif (
  54. "tests/" not in self.filename
  55. and "fixtures/" not in self.filename
  56. and "sentry/testutils/" not in self.filename
  57. and "sentry.testutils" in alias.name
  58. ):
  59. self.errors.append((node.lineno, node.col_offset, S007_msg))
  60. self.generic_visit(node)
  61. def visit_Attribute(self, node: ast.Attribute) -> None:
  62. if node.attr in S001_methods:
  63. self.errors.append((node.lineno, node.col_offset, S001_fmt.format(node.attr)))
  64. elif node.attr in S004_methods:
  65. self.errors.append((node.lineno, node.col_offset, S004_msg))
  66. elif (
  67. isinstance(node.value, ast.Name)
  68. and node.value.id == "pytz"
  69. and node.attr.lower() == "utc"
  70. ):
  71. self.errors.append((node.lineno, node.col_offset, S008_msg))
  72. self.generic_visit(node)
  73. def visit_Name(self, node: ast.Name) -> None:
  74. if node.id == "print":
  75. self.errors.append((node.lineno, node.col_offset, S002_msg))
  76. self.generic_visit(node)
  77. def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
  78. self._except_vars.append(node.name)
  79. try:
  80. self.generic_visit(node)
  81. finally:
  82. self._except_vars.pop()
  83. def visit_Raise(self, node: ast.Raise) -> None:
  84. if (
  85. self._except_vars
  86. and isinstance(node.exc, ast.Name)
  87. and node.exc.id == self._except_vars[-1]
  88. ):
  89. self.errors.append((node.lineno, node.col_offset, S009_msg))
  90. self.generic_visit(node)
  91. def visit_Try(self, node: ast.Try) -> None:
  92. if (
  93. node.handlers
  94. and len(node.handlers[-1].body) == 1
  95. and isinstance(node.handlers[-1].body[0], ast.Raise)
  96. and node.handlers[-1].body[0].exc is None
  97. ):
  98. self.errors.append((node.handlers[-1].lineno, node.handlers[-1].col_offset, S010_msg))
  99. self.generic_visit(node)
  100. def visit_Call(self, node: ast.Call) -> None:
  101. if (
  102. # override_settings(...)
  103. (isinstance(node.func, ast.Name) and node.func.id == "override_settings")
  104. or
  105. # self.settings(...)
  106. (
  107. isinstance(node.func, ast.Attribute)
  108. and isinstance(node.func.value, ast.Name)
  109. and node.func.value.id == "self"
  110. and node.func.attr == "settings"
  111. )
  112. ):
  113. for keyword in node.keywords:
  114. if keyword.arg == "SENTRY_OPTIONS":
  115. self.errors.append((keyword.lineno, keyword.col_offset, S011_msg))
  116. self.generic_visit(node)
  117. class SentryCheck:
  118. def __init__(self, tree: ast.AST, filename: str) -> None:
  119. self.tree = tree
  120. self.filename = filename
  121. def run(self) -> Generator[tuple[int, int, str, type[Any]], None, None]:
  122. visitor = SentryVisitor(self.filename)
  123. visitor.visit(self.tree)
  124. for e in visitor.errors:
  125. yield (*e, type(self))