|
| 1 | +""" |
| 2 | +Tests for event parsing and publishing in mesh_acknowledge.events |
| 3 | +""" |
| 4 | +import json |
| 5 | +from datetime import datetime, timezone |
| 6 | +from typing import Dict |
| 7 | +from uuid import uuid4 |
| 8 | + |
| 9 | +from unittest.mock import Mock, patch |
| 10 | +import pytest |
| 11 | +from digital_letters_events import MESHInboxMessageAcknowledged, MESHInboxMessageDownloaded |
| 12 | +from mesh_acknowledge.events import ( |
| 13 | + parse_downloaded_event, |
| 14 | + publish_acknowledged_event |
| 15 | +) |
| 16 | + |
| 17 | +from .fixtures import create_downloaded_event_dict |
| 18 | + |
| 19 | + |
| 20 | +@pytest.fixture(name='mock_logger') |
| 21 | +def create_mock_logger(): |
| 22 | + """Create a mock logger for testing""" |
| 23 | + logger = Mock() |
| 24 | + logger.info = Mock() |
| 25 | + logger.error = Mock() |
| 26 | + return logger |
| 27 | + |
| 28 | + |
| 29 | +@pytest.fixture(name='mock_event_publisher') |
| 30 | +def create_mock_event_publisher(): |
| 31 | + """Create a mock EventPublisher for testing""" |
| 32 | + publisher = Mock() |
| 33 | + publisher.send_events = Mock(return_value=[]) |
| 34 | + return publisher |
| 35 | + |
| 36 | + |
| 37 | +@pytest.fixture(name='event_id') |
| 38 | +def generate_event_id() -> str: |
| 39 | + """Generate a unique event ID""" |
| 40 | + return str(uuid4()) |
| 41 | + |
| 42 | + |
| 43 | +@pytest.fixture(name='downloaded_event') |
| 44 | +def downloaded_event_fixture(event_id: str) -> MESHInboxMessageDownloaded: |
| 45 | + """Create a MESHInboxMessageDownloaded event""" |
| 46 | + return MESHInboxMessageDownloaded(**create_downloaded_event_dict(event_id)) |
| 47 | + |
| 48 | + |
| 49 | +@pytest.fixture(name='valid_sqs_record') |
| 50 | +def create_valid_sqs_record(event_id: str) -> Dict[str, str | int]: |
| 51 | + """Create a valid SQS record with MESHInboxMessageDownloaded event""" |
| 52 | + return { |
| 53 | + 'body': json.dumps({ |
| 54 | + 'detail': { |
| 55 | + **create_downloaded_event_dict(event_id), |
| 56 | + } |
| 57 | + }) |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | +@pytest.fixture(name='invalid_sqs_record') |
| 62 | +def create_invalid_sqs_record(event_id: str) -> Dict[str, str]: |
| 63 | + """Create a valid SQS record with MESHInboxMessageDownloaded event""" |
| 64 | + return { |
| 65 | + 'body': json.dumps({ |
| 66 | + 'detail': { |
| 67 | + 'id': event_id, |
| 68 | + 'specversion': '1.0', |
| 69 | + 'source': '/nhs/england/notify/production/primary/data-plane/digitalletters/mesh', |
| 70 | + 'subject': ( |
| 71 | + 'customer/920fca11-596a-4eca-9c47-99f624614658/recipient/' |
| 72 | + '769acdd4-6a47-496f-999f-76a6fd2c3959' |
| 73 | + ), |
| 74 | + 'type': 'uk.nhs.notify.digital.letters.mesh.inbox.message.downloaded.v1', |
| 75 | + 'time': '2026-01-08T10:00:00Z', |
| 76 | + 'recordedtime': '2026-01-08T10:00:00Z', |
| 77 | + 'severitynumber': 2, |
| 78 | + 'traceparent': '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01', |
| 79 | + 'datacontenttype': 'application/json', |
| 80 | + 'dataschema': ( |
| 81 | + 'https://notify.nhs.uk/cloudevents/schemas/digital-letters/2025-10-draft/data/' |
| 82 | + 'digital-letters-mesh-inbox-message-downloaded-data.schema.json' |
| 83 | + ), |
| 84 | + 'data': { |
| 85 | + 'meshMessageId': 'MSG123456', |
| 86 | + 'messageUri': f"https://example.com/ttl/resource/{event_id}", |
| 87 | + 'messageReference': 'REF123', |
| 88 | + 'senderId': 'SENDER001', |
| 89 | + 'extraField': 'INVALID' # Invalid extra field |
| 90 | + } |
| 91 | + } |
| 92 | + }) |
| 93 | + } |
| 94 | + |
| 95 | + |
| 96 | +class TestParseDownloadedEvent: |
| 97 | + """Test suite for parse_downloaded_event function""" |
| 98 | + |
| 99 | + def test_parse_valid_event( |
| 100 | + self, valid_sqs_record: Dict[str, str | int], |
| 101 | + downloaded_event: MESHInboxMessageDownloaded, |
| 102 | + mock_logger): |
| 103 | + """Test parsing a valid SQS record""" |
| 104 | + result = parse_downloaded_event(valid_sqs_record, mock_logger, ) |
| 105 | + |
| 106 | + assert result == downloaded_event |
| 107 | + |
| 108 | + def test_parse_event_with_missing_detail(self, mock_logger): |
| 109 | + """Test parsing SQS record with missing 'detail' field""" |
| 110 | + sqs_record = {'body': json.dumps({})} |
| 111 | + |
| 112 | + with pytest.raises(ValueError): |
| 113 | + parse_downloaded_event(sqs_record, mock_logger) |
| 114 | + |
| 115 | + def test_parse_event_validation_error( |
| 116 | + self, invalid_sqs_record: Dict[str, str | int], |
| 117 | + mock_logger): |
| 118 | + """Test handling validation errors from Pydantic model""" |
| 119 | + with pytest.raises(ValueError, match="Error processing MESHInboxMessageDownloaded event"): |
| 120 | + parse_downloaded_event(invalid_sqs_record, mock_logger) |
| 121 | + |
| 122 | + def test_parse_event_json_decode_error(self, mock_logger): |
| 123 | + """Test handling JSON decode errors""" |
| 124 | + sqs_record = {'body': 'invalid json'} |
| 125 | + |
| 126 | + with pytest.raises(ValueError, match="Error parsing SQS record"): |
| 127 | + parse_downloaded_event(sqs_record, mock_logger) |
| 128 | + |
| 129 | + |
| 130 | +class TestPublishAcknowledgedEvent: |
| 131 | + """Test suite for publish_acknowledged_event function""" |
| 132 | + |
| 133 | + @patch('mesh_acknowledge.events.uuid4') |
| 134 | + @patch('mesh_acknowledge.events.datetime') |
| 135 | + def test_publish_success( |
| 136 | + self, |
| 137 | + mock_datetime, |
| 138 | + mock_uuid, |
| 139 | + mock_logger, |
| 140 | + mock_event_publisher, |
| 141 | + downloaded_event: MESHInboxMessageDownloaded |
| 142 | + ): |
| 143 | + """Test successful event publishing""" |
| 144 | + new_event_id = str(uuid4()) |
| 145 | + mock_uuid.return_value = new_event_id |
| 146 | + fixed_time = datetime(2026, 1, 8, 10, 30, 0, tzinfo=timezone.utc) |
| 147 | + mock_datetime.now.return_value = fixed_time |
| 148 | + |
| 149 | + mock_event_publisher.send_events.return_value = [] |
| 150 | + |
| 151 | + mesh_mailbox_id = 'MAILBOX001' |
| 152 | + expected_ack_event = { |
| 153 | + **downloaded_event.model_dump(), |
| 154 | + 'id': new_event_id, |
| 155 | + 'time': fixed_time.isoformat(), |
| 156 | + 'recordedtime': fixed_time.isoformat(), |
| 157 | + 'type': 'uk.nhs.notify.digital.letters.mesh.inbox.message.acknowledged.v1', |
| 158 | + 'dataschema': ( |
| 159 | + 'https://notify.nhs.uk/cloudevents/schemas/digital-letters/2025-10-draft/data/' |
| 160 | + 'digital-letters-mesh-inbox-message-acknowledged-data.schema.json' |
| 161 | + ), |
| 162 | + 'data': { |
| 163 | + 'messageReference': downloaded_event.data.messageReference, |
| 164 | + 'senderId': downloaded_event.data.senderId, |
| 165 | + 'meshMailboxId': mesh_mailbox_id, |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + publish_acknowledged_event( |
| 170 | + mock_logger, |
| 171 | + mock_event_publisher, |
| 172 | + downloaded_event, |
| 173 | + mesh_mailbox_id |
| 174 | + ) |
| 175 | + |
| 176 | + # Verify event was sent |
| 177 | + mock_event_publisher.send_events.assert_called_once_with( |
| 178 | + [expected_ack_event], MESHInboxMessageAcknowledged) |
| 179 | + |
| 180 | + @patch('mesh_acknowledge.events.uuid4') |
| 181 | + @patch('mesh_acknowledge.events.datetime') |
| 182 | + def test_publish_failure_raises_error( |
| 183 | + self, |
| 184 | + mock_datetime, |
| 185 | + mock_uuid, |
| 186 | + mock_logger, |
| 187 | + mock_event_publisher, |
| 188 | + downloaded_event |
| 189 | + ): |
| 190 | + """Test that publishing failures raise RuntimeError""" |
| 191 | + mock_uuid.return_value = str(uuid4()) |
| 192 | + fixed_time = datetime(2026, 1, 8, 12, 0, 0, tzinfo=timezone.utc) |
| 193 | + mock_datetime.now.return_value = fixed_time |
| 194 | + |
| 195 | + failed_events = [{'error': 'send failed'}] |
| 196 | + mock_event_publisher.send_events.return_value = failed_events |
| 197 | + |
| 198 | + with pytest.raises( |
| 199 | + RuntimeError, match="Failed to publish MESHInboxMessageAcknowledged event"): |
| 200 | + publish_acknowledged_event( |
| 201 | + mock_logger, |
| 202 | + mock_event_publisher, |
| 203 | + downloaded_event, |
| 204 | + 'MAILBOX001' |
| 205 | + ) |
| 206 | + |
| 207 | + @patch('mesh_acknowledge.events.uuid4') |
| 208 | + @patch('mesh_acknowledge.events.datetime') |
| 209 | + def test_publish_error_event_raises_error( |
| 210 | + self, |
| 211 | + mock_datetime, |
| 212 | + mock_uuid, |
| 213 | + mock_logger, |
| 214 | + mock_event_publisher, |
| 215 | + downloaded_event |
| 216 | + ): |
| 217 | + """Test that if the event publisher raises an error, an error is raised""" |
| 218 | + mock_uuid.return_value = str(uuid4()) |
| 219 | + fixed_time = datetime(2026, 1, 8, 13, 0, 0, tzinfo=timezone.utc) |
| 220 | + mock_datetime.now.return_value = fixed_time |
| 221 | + |
| 222 | + mock_event_publisher.send_events.side_effect = Exception("Publisher error") |
| 223 | + |
| 224 | + |
| 225 | + with pytest.raises(Exception, match="Publisher error"): |
| 226 | + publish_acknowledged_event( |
| 227 | + mock_logger, |
| 228 | + mock_event_publisher, |
| 229 | + downloaded_event, |
| 230 | + 'MAILBOX001' |
| 231 | + ) |
0 commit comments