flake8_plugin.py 5.8 KB

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