|
| 1 | +import contextlib |
| 2 | +from dataclasses import fields |
| 3 | +from unittest.mock import MagicMock, patch |
| 4 | + |
| 5 | +from sentry.analytics.event import Event |
| 6 | + |
| 7 | + |
| 8 | +def assert_event_equal( |
| 9 | + expected_event: Event, |
| 10 | + recorded_event: Event, |
| 11 | + check_uuid: bool = False, |
| 12 | + check_datetime: bool = False, |
| 13 | +): |
| 14 | + assert expected_event.type == recorded_event.type |
| 15 | + for field in fields(expected_event): |
| 16 | + if field.name == "uuid_" and not check_uuid: |
| 17 | + continue |
| 18 | + if field.name == "datetime_" and not check_datetime: |
| 19 | + continue |
| 20 | + assert getattr(expected_event, field.name) == getattr(recorded_event, field.name) |
| 21 | + |
| 22 | + |
| 23 | +def assert_analytics_events_recorded( |
| 24 | + mock_record: MagicMock, |
| 25 | + expected_events: list[Event], |
| 26 | + check_uuid: bool = False, |
| 27 | + check_datetime: bool = False, |
| 28 | +): |
| 29 | + recorded_events = [call.args[0] for call in mock_record.call_args_list] |
| 30 | + assert len(expected_events) == len(recorded_events) |
| 31 | + for expected_event, recorded_event in zip(expected_events, recorded_events): |
| 32 | + assert_event_equal(expected_event, recorded_event, check_uuid, check_datetime) |
| 33 | + |
| 34 | + |
| 35 | +@contextlib.contextmanager |
| 36 | +def assert_analytics_events( |
| 37 | + expected_events: list[Event], |
| 38 | + check_uuid: bool = False, |
| 39 | + check_datetime: bool = False, |
| 40 | +): |
| 41 | + """ |
| 42 | + Context manager that allows you to track analytics events recorded during the context. |
| 43 | +
|
| 44 | + with assert_analytics_events([SomeEvent(...)]): |
| 45 | + ... |
| 46 | +
|
| 47 | + # analytics events must have been recorded in the context |
| 48 | + """ |
| 49 | + with patch("sentry.analytics.record") as mock_record: |
| 50 | + yield |
| 51 | + assert_analytics_events_recorded(mock_record, expected_events, check_uuid, check_datetime) |
0 commit comments