conftest.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. from collections.abc import MutableMapping
  2. import psutil
  3. import pytest
  4. import responses
  5. from django.core.cache import cache
  6. from django.db import connections
  7. from sentry.silo.base import SiloMode
  8. from sentry.testutils.pytest.sentry import get_default_silo_mode_for_test_cases
  9. pytest_plugins = ["sentry.testutils.pytest"]
  10. # XXX: The below code is vendored code from https://github.com/utgwkk/pytest-github-actions-annotate-failures
  11. # so that we can add support for pytest_rerunfailures
  12. # retried tests will no longer be annotated in GHA
  13. #
  14. # Reference:
  15. # https://docs.pytest.org/en/latest/writing_plugins.html#hookwrapper-executing-around-other-hooks
  16. # https://docs.pytest.org/en/latest/writing_plugins.html#hook-function-ordering-call-example
  17. # https://docs.pytest.org/en/stable/reference.html#pytest.hookspec.pytest_runtest_makereport
  18. #
  19. # Inspired by:
  20. # https://github.com/pytest-dev/pytest/blob/master/src/_pytest/terminal.py
  21. @pytest.fixture(autouse=True)
  22. def unclosed_files():
  23. fds = frozenset(psutil.Process().open_files())
  24. yield
  25. assert frozenset(psutil.Process().open_files()) == fds
  26. @pytest.fixture(autouse=True)
  27. def validate_silo_mode():
  28. # NOTE! Hybrid cloud uses many mechanisms to simulate multiple different configurations of the application
  29. # during tests. It depends upon `override_settings` using the correct contextmanager behaviors and correct
  30. # thread handling in acceptance tests. If you hit one of these, it's possible either that cleanup logic has
  31. # a bug, or you may be using a contextmanager incorrectly. Let us know and we can help!
  32. expected = get_default_silo_mode_for_test_cases()
  33. message = (
  34. f"Possible test leak bug! SiloMode was not reset to {expected} between tests. "
  35. "Please read the comment for validate_silo_mode() in tests/conftest.py."
  36. )
  37. if SiloMode.get_current_mode() != expected:
  38. raise Exception(message)
  39. yield
  40. if SiloMode.get_current_mode() != expected:
  41. raise Exception(message)
  42. @pytest.fixture(autouse=True)
  43. def setup_simulate_on_commit(request):
  44. from sentry.testutils.hybrid_cloud import simulate_on_commit
  45. with simulate_on_commit(request):
  46. yield
  47. @pytest.fixture(autouse=True)
  48. def setup_enforce_monotonic_transactions(request):
  49. from sentry.testutils.hybrid_cloud import enforce_no_cross_transaction_interactions
  50. with enforce_no_cross_transaction_interactions():
  51. yield
  52. @pytest.fixture(autouse=True)
  53. def audit_hybrid_cloud_writes_and_deletes(request):
  54. """
  55. Ensure that write operations on hybrid cloud foreign keys are recorded
  56. alongside outboxes or use a context manager to indicate that the
  57. caller has considered outbox and didn't accidentally forget.
  58. Generally you can avoid assertion errors from these checks by:
  59. 1. Running deletion/write logic within an `outbox_context`.
  60. 2. Using Model.delete()/save methods that create outbox messages in the
  61. same transaction as a delete operation.
  62. Scenarios that are generally always unsafe are using
  63. `QuerySet.delete()`, `QuerySet.update()` or raw SQL to perform
  64. writes.
  65. The User.delete() method is a good example of how to safely
  66. delete records and generate outbox messages.
  67. """
  68. from sentry.testutils.silo import validate_protected_queries
  69. debug_cursor_state: MutableMapping[str, bool] = {}
  70. for conn in connections.all():
  71. debug_cursor_state[conn.alias] = conn.force_debug_cursor
  72. conn.queries_log.clear()
  73. conn.force_debug_cursor = True
  74. try:
  75. yield
  76. finally:
  77. for conn in connections.all():
  78. conn.force_debug_cursor = debug_cursor_state[conn.alias]
  79. validate_protected_queries(conn.queries)
  80. @pytest.fixture(autouse=True)
  81. def clear_caches():
  82. yield
  83. cache.clear()
  84. @pytest.fixture(autouse=True)
  85. def check_leaked_responses_mocks():
  86. yield
  87. leaked = responses.registered()
  88. if leaked:
  89. responses.reset()
  90. leaked_s = "".join(f"- {item}\n" for item in leaked)
  91. raise AssertionError(
  92. f"`responses` were leaked outside of the test context:\n{leaked_s}"
  93. f"(make sure to use `@responses.activate` or `with responses.mock:`)"
  94. )