sightbox/backend/tests/test_sentry_config.py

52 lines
2.0 KiB
Python

"""
tests/test_sentry_config.py — verifies Sentry wiring in app.py's create_app():
init is skipped with no SENTRY_DSN, initialized with the right kwargs (PII
excluded, environment tagged) when one is set, and every request tags its
trace_id onto the Sentry scope. sentry_sdk itself is mocked throughout — no
test ever talks to a real Sentry project.
"""
from unittest.mock import patch
import app as app_module
def test_create_app_skips_sentry_init_when_dsn_unset(monkeypatch):
monkeypatch.delenv("SENTRY_DSN", raising=False)
with patch.object(app_module.sentry_sdk, "init") as mock_init:
app_module.create_app()
mock_init.assert_not_called()
def test_create_app_initializes_sentry_with_dsn_set(monkeypatch):
monkeypatch.setenv("SENTRY_DSN", "https://example@o0.ingest.sentry.io/0")
monkeypatch.setenv("ENVIRONMENT", "staging")
with patch.object(app_module.sentry_sdk, "init") as mock_init:
app_module.create_app()
mock_init.assert_called_once()
_, kwargs = mock_init.call_args
assert kwargs["dsn"] == "https://example@o0.ingest.sentry.io/0"
assert kwargs["environment"] == "staging"
assert kwargs["send_default_pii"] is False
def test_create_app_defaults_environment_to_production(monkeypatch):
monkeypatch.setenv("SENTRY_DSN", "https://example@o0.ingest.sentry.io/0")
monkeypatch.delenv("ENVIRONMENT", raising=False)
with patch.object(app_module.sentry_sdk, "init") as mock_init:
app_module.create_app()
assert mock_init.call_args.kwargs["environment"] == "production"
def test_request_tags_trace_id_on_sentry_scope(monkeypatch):
monkeypatch.delenv("SENTRY_DSN", raising=False)
flask_app = app_module.create_app()
flask_app.config["TESTING"] = True
with patch.object(app_module.sentry_sdk, "set_tag") as mock_set_tag:
with flask_app.test_client() as client:
client.get("/health")
mock_set_tag.assert_called_once()
tag_name, tag_value = mock_set_tag.call_args.args
assert tag_name == "trace_id"
assert len(tag_value) == 36 # uuid4 string form