test_flake8_plugin.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import ast
  2. from tools.flake8_plugin import SentryCheck
  3. def _run(src):
  4. tree = ast.parse(src)
  5. return sorted(
  6. "t.py:{}:{}: {}".format(*error)
  7. for error in SentryCheck(tree=tree, filename="getsentry/foo.py").run()
  8. )
  9. def test_S001():
  10. S001_py = """\
  11. class A:
  12. def called_once():
  13. pass
  14. A().called_once()
  15. """
  16. errors = _run(S001_py)
  17. assert errors == [
  18. "t.py:6:0: S001 Avoid using the called_once mock call as it is confusing and "
  19. "prone to causing invalid test behavior.",
  20. ]
  21. def test_S002():
  22. S002_py = """\
  23. print("print statements are not allowed")
  24. """
  25. errors = _run(S002_py)
  26. assert errors == ["t.py:1:0: S002 print functions or statements are not allowed."]
  27. def test_S003():
  28. S003_py = """\
  29. import json
  30. import simplejson
  31. from json import loads, load
  32. from simplejson import JSONDecoder, JSONDecodeError, _default_encoder
  33. import sentry.utils.json as good_json
  34. from sentry.utils.json import JSONDecoder, JSONDecodeError
  35. from .json import Validator
  36. def bad_code():
  37. a = json.loads("''")
  38. b = simplejson.loads("''")
  39. c = loads("''")
  40. d = load()
  41. """
  42. errors = _run(S003_py)
  43. assert errors == [
  44. "t.py:1:0: S003 Use ``from sentry.utils import json`` instead.",
  45. "t.py:2:0: S003 Use ``from sentry.utils import json`` instead.",
  46. "t.py:3:0: S003 Use ``from sentry.utils import json`` instead.",
  47. "t.py:4:0: S003 Use ``from sentry.utils import json`` instead.",
  48. ]
  49. def test_S004():
  50. S004_py = """\
  51. import unittest
  52. from something import func
  53. class Test(unittest.TestCase):
  54. def test(self):
  55. with self.assertRaises(ValueError):
  56. func()
  57. """
  58. errors = _run(S004_py)
  59. assert errors == [
  60. "t.py:7:13: S004 Use `pytest.raises` instead for better debuggability.",
  61. ]
  62. def test_S005():
  63. S005_py = """\
  64. from sentry.models import User
  65. """
  66. errors = _run(S005_py)
  67. assert errors == [
  68. "t.py:1:0: S005 Do not import models from sentry.models but the actual module",
  69. ]