conftest.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import contextlib
  2. import os
  3. import pytest
  4. pytest_plugins = ["sentry.utils.pytest"]
  5. # XXX: The below code is vendored code from https://github.com/utgwkk/pytest-github-actions-annotate-failures
  6. # so that we can add support for pytest_rerunfailures
  7. # retried tests will no longer be annotated in GHA
  8. #
  9. # Reference:
  10. # https://docs.pytest.org/en/latest/writing_plugins.html#hookwrapper-executing-around-other-hooks
  11. # https://docs.pytest.org/en/latest/writing_plugins.html#hook-function-ordering-call-example
  12. # https://docs.pytest.org/en/stable/reference.html#pytest.hookspec.pytest_runtest_makereport
  13. #
  14. # Inspired by:
  15. # https://github.com/pytest-dev/pytest/blob/master/src/_pytest/terminal.py
  16. @pytest.hookimpl(tryfirst=True, hookwrapper=True)
  17. def pytest_runtest_makereport(item, call):
  18. # execute all other hooks to obtain the report object
  19. outcome = yield
  20. report = outcome.get_result()
  21. # enable only in a workflow of GitHub Actions
  22. # ref: https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables
  23. if os.environ.get("GITHUB_ACTIONS") != "true":
  24. return
  25. # If we have the pytest_rerunfailures plugin,
  26. # and there are still retries to be run,
  27. # then do not return the error
  28. if hasattr(item, "execution_count"):
  29. import pytest_rerunfailures
  30. if item.execution_count <= pytest_rerunfailures.get_reruns_count(item):
  31. return
  32. if report.when == "call" and report.failed:
  33. # collect information to be annotated
  34. filesystempath, lineno, _ = report.location
  35. # try to convert to absolute path in GitHub Actions
  36. workspace = os.environ.get("GITHUB_WORKSPACE")
  37. if workspace:
  38. full_path = os.path.abspath(filesystempath)
  39. try:
  40. rel_path = os.path.relpath(full_path, workspace)
  41. except ValueError:
  42. # os.path.relpath() will raise ValueError on Windows
  43. # when full_path and workspace have different mount points.
  44. # https://github.com/utgwkk/pytest-github-actions-annotate-failures/issues/20
  45. rel_path = filesystempath
  46. if not rel_path.startswith(".."):
  47. filesystempath = rel_path
  48. if lineno is not None:
  49. # 0-index to 1-index
  50. lineno += 1
  51. # get the name of the current failed test, with parametrize info
  52. longrepr = report.head_line or item.name
  53. # get the error message and line number from the actual error
  54. try:
  55. longrepr += "\n\n" + report.longrepr.reprcrash.message
  56. lineno = report.longrepr.reprcrash.lineno
  57. except AttributeError:
  58. pass
  59. print(_error_workflow_command(filesystempath, lineno, longrepr)) # noqa: S002
  60. def _error_workflow_command(filesystempath, lineno, longrepr):
  61. # Build collection of arguments. Ordering is strict for easy testing
  62. details_dict = {"file": filesystempath}
  63. if lineno is not None:
  64. details_dict["line"] = lineno
  65. details = ",".join(f"{k}={v}" for k, v in details_dict.items())
  66. if longrepr is None:
  67. return f"\n::error {details}"
  68. else:
  69. longrepr = _escape(longrepr)
  70. return f"\n::error {details}::{longrepr}"
  71. def _escape(s):
  72. return s.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
  73. _MODEL_MANIFEST_FILE_PATH = os.getenv("SENTRY_MODEL_MANIFEST_FILE_PATH")
  74. _model_manifest = None
  75. @pytest.fixture(scope="session", autouse=True)
  76. def create_model_manifest_file():
  77. """Audit which models are touched by each test case and write it to file."""
  78. # We have to construct the ModelManifest lazily, because importing
  79. # sentry.testutils.modelmanifest too early causes a dependency cycle.
  80. from sentry.testutils.modelmanifest import ModelManifest
  81. if _MODEL_MANIFEST_FILE_PATH:
  82. global _model_manifest
  83. _model_manifest = ModelManifest.open(_MODEL_MANIFEST_FILE_PATH)
  84. with _model_manifest.write():
  85. yield
  86. else:
  87. yield
  88. @pytest.fixture(scope="class", autouse=True)
  89. def register_class_in_model_manifest(request: pytest.FixtureRequest):
  90. if _model_manifest:
  91. with _model_manifest.register(request.node.nodeid):
  92. yield
  93. else:
  94. yield
  95. @pytest.fixture(autouse=True)
  96. def setup_default_hybrid_cloud_stubs():
  97. from sentry.region_to_control.producer import (
  98. MockRegionToControlMessageService,
  99. region_to_control_message_service,
  100. )
  101. from sentry.services.hybrid_cloud import service_stubbed
  102. from sentry.services.hybrid_cloud.organization import (
  103. StubOrganizationService,
  104. organization_service,
  105. )
  106. from sentry.services.hybrid_cloud.project_key import StubProjectKeyService, project_key_service
  107. from sentry.silo import SiloMode
  108. stubs = [
  109. service_stubbed(project_key_service, StubProjectKeyService(), SiloMode.CONTROL),
  110. service_stubbed(organization_service, StubOrganizationService(), SiloMode.CONTROL),
  111. service_stubbed(
  112. region_to_control_message_service, MockRegionToControlMessageService(), SiloMode.REGION
  113. ),
  114. ]
  115. with contextlib.ExitStack() as stack:
  116. for stub in stubs:
  117. stack.enter_context(stub)
  118. yield