conftest.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import os
  2. from typing import MutableMapping
  3. import psutil
  4. import pytest
  5. import responses
  6. from django.db import connections
  7. from sentry.silo import SiloMode
  8. pytest_plugins = ["sentry.testutils.pytest"]
  9. # XXX: The below code is vendored code from https://github.com/utgwkk/pytest-github-actions-annotate-failures
  10. # so that we can add support for pytest_rerunfailures
  11. # retried tests will no longer be annotated in GHA
  12. #
  13. # Reference:
  14. # https://docs.pytest.org/en/latest/writing_plugins.html#hookwrapper-executing-around-other-hooks
  15. # https://docs.pytest.org/en/latest/writing_plugins.html#hook-function-ordering-call-example
  16. # https://docs.pytest.org/en/stable/reference.html#pytest.hookspec.pytest_runtest_makereport
  17. #
  18. # Inspired by:
  19. # https://github.com/pytest-dev/pytest/blob/master/src/_pytest/terminal.py
  20. @pytest.fixture(autouse=True)
  21. def unclosed_files():
  22. fds = frozenset(psutil.Process().open_files())
  23. yield
  24. assert frozenset(psutil.Process().open_files()) == fds
  25. @pytest.hookimpl(tryfirst=True, hookwrapper=True)
  26. def pytest_runtest_makereport(item, call):
  27. # execute all other hooks to obtain the report object
  28. outcome = yield
  29. report = outcome.get_result()
  30. # enable only in a workflow of GitHub Actions
  31. # ref: https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables
  32. if os.environ.get("GITHUB_ACTIONS") != "true":
  33. return
  34. # If we have the pytest_rerunfailures plugin,
  35. # and there are still retries to be run,
  36. # then do not return the error
  37. if hasattr(item, "execution_count"):
  38. import pytest_rerunfailures
  39. if item.execution_count <= pytest_rerunfailures.get_reruns_count(item):
  40. return
  41. if report.when == "call" and report.failed:
  42. # collect information to be annotated
  43. filesystempath, lineno, _ = report.location
  44. # try to convert to absolute path in GitHub Actions
  45. workspace = os.environ.get("GITHUB_WORKSPACE")
  46. if workspace:
  47. full_path = os.path.abspath(filesystempath)
  48. try:
  49. rel_path = os.path.relpath(full_path, workspace)
  50. except ValueError:
  51. # os.path.relpath() will raise ValueError on Windows
  52. # when full_path and workspace have different mount points.
  53. # https://github.com/utgwkk/pytest-github-actions-annotate-failures/issues/20
  54. rel_path = filesystempath
  55. if not rel_path.startswith(".."):
  56. filesystempath = rel_path
  57. if lineno is not None:
  58. # 0-index to 1-index
  59. lineno += 1
  60. # get the name of the current failed test, with parametrize info
  61. longrepr = report.head_line or item.name
  62. # get the error message and line number from the actual error
  63. try:
  64. longrepr += "\n\n" + report.longrepr.reprcrash.message
  65. lineno = report.longrepr.reprcrash.lineno
  66. except AttributeError:
  67. pass
  68. print(_error_workflow_command(filesystempath, lineno, longrepr)) # noqa: S002
  69. def _error_workflow_command(filesystempath, lineno, longrepr):
  70. # Build collection of arguments. Ordering is strict for easy testing
  71. details_dict = {"file": filesystempath}
  72. if lineno is not None:
  73. details_dict["line"] = lineno
  74. details = ",".join(f"{k}={v}" for k, v in details_dict.items())
  75. if longrepr is None:
  76. return f"\n::error {details}"
  77. else:
  78. longrepr = _escape(longrepr)
  79. return f"\n::error {details}::{longrepr}"
  80. def _escape(s):
  81. return s.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
  82. @pytest.fixture(autouse=True)
  83. def validate_silo_mode():
  84. # NOTE! Hybrid cloud uses many mechanisms to simulate multiple different configurations of the application
  85. # during tests. It depends upon `override_settings` using the correct contextmanager behaviors and correct
  86. # thread handling in acceptance tests. If you hit one of these, it's possible either that cleanup logic has
  87. # a bug, or you may be using a contextmanager incorrectly. Let us know and we can help!
  88. if SiloMode.get_current_mode() != SiloMode.MONOLITH:
  89. raise Exception(
  90. "Possible test leak bug! SiloMode was not reset to Monolith between tests. Please read the comment for validate_silo_mode() in tests/conftest.py."
  91. )
  92. yield
  93. if SiloMode.get_current_mode() != SiloMode.MONOLITH:
  94. raise Exception(
  95. "Possible test leak bug! SiloMode was not reset to Monolith between tests. Please read the comment for validate_silo_mode() in tests/conftest.py."
  96. )
  97. @pytest.fixture(autouse=True)
  98. def setup_simulate_on_commit(request):
  99. from sentry.testutils.hybrid_cloud import simulate_on_commit
  100. with simulate_on_commit(request):
  101. yield
  102. @pytest.fixture(autouse=True)
  103. def setup_enforce_monotonic_transactions(request):
  104. from sentry.testutils.hybrid_cloud import enforce_no_cross_transaction_interactions
  105. with enforce_no_cross_transaction_interactions():
  106. yield
  107. @pytest.fixture(autouse=True)
  108. def audit_hybrid_cloud_writes_and_deletes(request):
  109. """
  110. Ensure that write operations on hybrid cloud foreign keys are recorded
  111. alongside outboxes or use a context manager to indicate that the
  112. caller has considered outbox and didn't accidentally forget.
  113. Generally you can avoid assertion errors from these checks by:
  114. 1. Running deletion/write logic within an `outbox_context`.
  115. 2. Using Model.delete()/save methods that create outbox messages in the
  116. same transaction as a delete operation.
  117. Scenarios that are generally always unsafe are using
  118. `QuerySet.delete()`, `QuerySet.update()` or raw SQL to perform
  119. writes.
  120. The User.delete() method is a good example of how to safely
  121. delete records and generate outbox messages.
  122. """
  123. from sentry.testutils.silo import validate_protected_queries
  124. debug_cursor_state: MutableMapping[str, bool] = {}
  125. for conn in connections.all():
  126. debug_cursor_state[conn.alias] = conn.force_debug_cursor
  127. conn.queries_log.clear()
  128. conn.force_debug_cursor = True
  129. try:
  130. yield
  131. finally:
  132. for conn in connections.all():
  133. conn.force_debug_cursor = debug_cursor_state[conn.alias]
  134. validate_protected_queries(conn.queries)
  135. @pytest.fixture(autouse=True)
  136. def check_leaked_responses_mocks():
  137. yield
  138. leaked = responses.registered()
  139. if leaked:
  140. responses.reset()
  141. leaked_s = "".join(f"- {item}\n" for item in leaked)
  142. raise AssertionError(
  143. f"`responses` were leaked outside of the test context:\n{leaked_s}"
  144. f"(make sure to use `@responses.activate` or `with responses.mock:`)"
  145. )