flake8_plugin.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. class SentryVisitor(ast.NodeVisitor):
  16. def __init__(self) -> None:
  17. self.errors: list[tuple[int, int, str]] = []
  18. def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
  19. if node.module and not node.level and node.module.split(".")[0] in S003_modules:
  20. self.errors.append((node.lineno, node.col_offset, S003_msg))
  21. self.generic_visit(node)
  22. def visit_Import(self, node: ast.Import) -> None:
  23. for alias in node.names:
  24. if alias.name.split(".")[0] in S003_modules:
  25. self.errors.append((node.lineno, node.col_offset, S003_msg))
  26. self.generic_visit(node)
  27. def visit_Attribute(self, node: ast.Attribute) -> None:
  28. if node.attr in S001_methods:
  29. self.errors.append((node.lineno, node.col_offset, S001_fmt.format(node.attr)))
  30. elif node.attr in S004_methods:
  31. self.errors.append((node.lineno, node.col_offset, S004_msg))
  32. self.generic_visit(node)
  33. def visit_Name(self, node: ast.Name) -> None:
  34. if node.id == "print":
  35. self.errors.append((node.lineno, node.col_offset, S002_msg))
  36. self.generic_visit(node)
  37. class SentryCheck:
  38. name = "sentry-flake8"
  39. version = "0"
  40. def __init__(self, tree: ast.AST) -> None:
  41. self.tree = tree
  42. def run(self) -> Generator[tuple[int, int, str, type[Any]], None, None]:
  43. visitor = SentryVisitor()
  44. visitor.visit(self.tree)
  45. for e in visitor.errors:
  46. yield (*e, type(self))