test_flake8_plugin.py 1.7 KB

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