diff --git a/swh/core/pytest_plugin.py b/swh/core/pytest_plugin.py --- a/swh/core/pytest_plugin.py +++ b/swh/core/pytest_plugin.py @@ -16,6 +16,7 @@ from requests.adapters import BaseAdapter from requests.structures import CaseInsensitiveDict from requests.utils import get_encoding_from_headers +import sentry_sdk logger = logging.getLogger(__name__) @@ -367,3 +368,40 @@ statsd = Statsd() statsd._socket = FakeSocket() yield statsd + + +@pytest.fixture +def sentry_init(): + # Inspired by + # https://github.com/getsentry/sentry-python/blob/1.5.9/tests/conftest.py#L168-L184 + + initialized = False + + def inner(*a, **kw): + nonlocal initialized + assert not initialized, "already initialized" + initialized = True + hub = sentry_sdk.Hub.current + client = sentry_sdk.Client(*a, **kw) + hub.bind_client(client) + client.transport = TestTransport() + + class TestTransport: + def __init__(self): + self.events = [] + self.envelopes = [] + + def capture_event(self, event): + self.events.append(event) + + def capture_envelope(self, envelope): + self.envelopes.append(envelope) + + with sentry_sdk.Hub(None): + yield inner + + +@pytest.fixture +def sentry_events(monkeypatch, sentry_init): + sentry_init() + return sentry_sdk.Hub.current.client.transport.events diff --git a/swh/core/tests/test_sentry.py b/swh/core/tests/test_sentry.py --- a/swh/core/tests/test_sentry.py +++ b/swh/core/tests/test_sentry.py @@ -6,7 +6,7 @@ import logging import pytest -from sentry_sdk import capture_message +from sentry_sdk import capture_exception, capture_message, set_tag from swh.core.sentry import init_sentry, override_with_bool_envvar @@ -101,3 +101,35 @@ logging.error("Stupid error") assert len(reports) == 2 + + +def test_sentry_events_fixture_capture_message(sentry_events): + message = "Something went wrong" + capture_message(message) + assert sentry_events + assert "message" in sentry_events[0] + assert sentry_events[0]["message"] == message + + +def test_sentry_events_fixture_capture_exception(sentry_events): + message = "Invalid value" + exception = ValueError(message) + capture_exception(exception) + assert sentry_events + assert "exception" in sentry_events[0] + assert "values" in sentry_events[0]["exception"] + exception_data = sentry_events[0]["exception"]["values"] + assert exception_data + assert exception_data[0].get("type") == type(exception).__name__ + assert exception_data[0].get("value") == message + + +def test_sentry_events_fixture_set_tag(sentry_events): + tag_name = "swh.test" + tag_value = "test" + set_tag(tag_name, tag_value) + message = "Something went wrong" + capture_message(message) + assert sentry_events + assert "tags" in sentry_events[0] + sentry_events[0]["tags"] == {tag_name: tag_value}