flake8_plugin.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. class SentryVisitor(ast.NodeVisitor):
  17. def __init__(self, filename: str) -> None:
  18. self.errors: list[tuple[int, int, str]] = []
  19. self.filename = filename
  20. def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
  21. if node.module and not node.level:
  22. if node.module.split(".")[0] in S003_modules:
  23. self.errors.append((node.lineno, node.col_offset, S003_msg))
  24. # for now only enforce this in getsentry
  25. elif (
  26. "getsentry/" in self.filename
  27. and node.module == "sentry.models"
  28. and any(x.name.isupper() or x.name.istitle() for x in node.names)
  29. ):
  30. self.errors.append((node.lineno, node.col_offset, S005_msg))
  31. self.generic_visit(node)
  32. def visit_Import(self, node: ast.Import) -> None:
  33. for alias in node.names:
  34. if alias.name.split(".")[0] in S003_modules:
  35. self.errors.append((node.lineno, node.col_offset, S003_msg))
  36. self.generic_visit(node)
  37. def visit_Attribute(self, node: ast.Attribute) -> None:
  38. if node.attr in S001_methods:
  39. self.errors.append((node.lineno, node.col_offset, S001_fmt.format(node.attr)))
  40. elif node.attr in S004_methods:
  41. self.errors.append((node.lineno, node.col_offset, S004_msg))
  42. self.generic_visit(node)
  43. def visit_Name(self, node: ast.Name) -> None:
  44. if node.id == "print":
  45. self.errors.append((node.lineno, node.col_offset, S002_msg))
  46. self.generic_visit(node)
  47. class SentryCheck:
  48. name = "sentry-flake8"
  49. version = "0"
  50. def __init__(self, tree: ast.AST, filename: str) -> None:
  51. self.tree = tree
  52. self.filename = filename
  53. def run(self) -> Generator[tuple[int, int, str, type[Any]], None, None]:
  54. visitor = SentryVisitor(self.filename)
  55. visitor.visit(self.tree)
  56. for e in visitor.errors:
  57. yield (*e, type(self))