-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_sds_stub_contract.py
More file actions
564 lines (462 loc) · 22 KB
/
test_sds_stub_contract.py
File metadata and controls
564 lines (462 loc) · 22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
"""Contract tests for the SDS FHIR API stub.
These tests verify that the :class:`~stubs.sds.stub.SdsFhirApiStub` honours the
``GET /Device`` and ``GET /Endpoint`` contracts described in the SDS OpenAPI
specification:
https://github.com/NHSDigital/spine-directory-service-api
The stub does not expose an HTTP server, so the tests call its methods directly
and validate the returned :class:`requests.Response` objects against the
contract requirements.
"""
from __future__ import annotations
from typing import Any
import pytest
from fhir.constants import FHIRSystem
from gateway_api.get_structured_record import ACCESS_RECORD_STRUCTURED_INTERACTION_ID
from stubs.sds.stub import SdsFhirApiStub
# ---------------------------------------------------------------------------
# Helpers / constants
# ---------------------------------------------------------------------------
# FHIR-formatted query parameter values used across all tests
_ORG_PROVIDER = f"{FHIRSystem.ODS_CODE}|PROVIDER"
_ORG_UNKNOWN = f"{FHIRSystem.ODS_CODE}|UNKNOWN_ORG_XYZ"
_INTERACTION_ID_PARAM = (
f"{FHIRSystem.NHS_SERVICE_INTERACTION_ID}|{ACCESS_RECORD_STRUCTURED_INTERACTION_ID}"
)
_VALID_CORRELATION_ID = "test-correlation-id-12345"
_BASE_DEVICE_URL = "https://sandbox.api.service.nhs.uk/spine-directory/FHIR/R4/Device"
_BASE_ENDPOINT_URL = (
"https://sandbox.api.service.nhs.uk/spine-directory/FHIR/R4/Endpoint"
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def stub() -> SdsFhirApiStub:
"""Return a fresh stub instance pre-seeded with default data."""
return SdsFhirApiStub()
# ---------------------------------------------------------------------------
# GET /Device – 200 success
# ---------------------------------------------------------------------------
class TestGetDeviceBundleSuccess:
"""Contract tests for the happy-path GET /Device → 200 response."""
def test_response_matches_expected(self, stub: SdsFhirApiStub) -> None:
response = stub.get_device_bundle(
headers={"apikey": "test-key"},
params={"organization": _ORG_PROVIDER, "identifier": _INTERACTION_ID_PARAM},
)
assert response.status_code == 200
assert "application/fhir+json" in response.headers["Content-Type"]
body = response.json()
assert body["resourceType"] == "Bundle"
assert body["type"] == "searchset"
assert body["total"] == 1
assert len(body["entry"]) == 1
entry = body["entry"][0]
assert entry["resource"]["id"] == "F0F0E921-92CA-4A88-A550-2DBB36F703AF"
assert (
entry["fullUrl"]
== "https://sandbox.api.service.nhs.uk/spine-directory/FHIR/R4/Device/F0F0E921-92CA-4A88-A550-2DBB36F703AF"
)
assert entry["search"]["mode"] == "match"
def test_x_correlation_id_echoed_back_when_provided(
self, stub: SdsFhirApiStub
) -> None:
"""The spec states ``X-Correlation-Id`` is mirrored back in the response."""
response = stub.get_device_bundle(
headers={"apikey": "test-key", "X-Correlation-Id": _VALID_CORRELATION_ID},
params={"organization": _ORG_PROVIDER, "identifier": _INTERACTION_ID_PARAM},
)
assert response.headers.get("X-Correlation-Id") == _VALID_CORRELATION_ID
def test_x_correlation_id_absent_when_not_provided(
self, stub: SdsFhirApiStub
) -> None:
"""``X-Correlation-Id`` must not appear in the response when not supplied."""
response = stub.get_device_bundle(
headers={"apikey": "test-key"},
params={"organization": _ORG_PROVIDER, "identifier": _INTERACTION_ID_PARAM},
)
assert "X-Correlation-Id" not in response.headers
def test_empty_bundle_returned_for_unknown_org(self, stub: SdsFhirApiStub) -> None:
"""An unknown organisation must return a 200 with an empty Bundle."""
response = stub.get_device_bundle(
headers={"apikey": "test-key"},
params={
"organization": _ORG_UNKNOWN,
"identifier": _INTERACTION_ID_PARAM,
},
)
assert response.status_code == 200
body = response.json()
assert body["resourceType"] == "Bundle"
assert body["total"] == 0
assert body["entry"] == []
# ---------------------------------------------------------------------------
# GET /Device – Device resource structure
# ---------------------------------------------------------------------------
class TestGetDeviceResourceStructure:
"""Contract tests verifying the shape of returned Device resources."""
def test_device_resource_type_is_device(self, stub: SdsFhirApiStub) -> None:
"""Each resource inside the Bundle must have ``resourceType: "Device"``."""
response = stub.get_device_bundle(
headers={"apikey": "test-key"},
params={"organization": _ORG_PROVIDER, "identifier": _INTERACTION_ID_PARAM},
)
body = response.json()
assert len(body["entry"]) == 1
entry = body["entry"][0]
resource = entry["resource"]
assert resource["resourceType"] == "Device"
assert resource["id"] == "F0F0E921-92CA-4A88-A550-2DBB36F703AF"
assert resource["owner"]["identifier"]["system"] == FHIRSystem.ODS_CODE
assert len(resource["identifier"]) == 1
identifiers = resource["identifier"]
assert identifiers[0]["system"] == FHIRSystem.NHS_SPINE_ASID
assert identifiers[0]["value"] == "asid_PROV"
# ---------------------------------------------------------------------------
# GET /Device – 400 validation errors
# ---------------------------------------------------------------------------
class TestGetDeviceBundleValidationErrors:
"""Contract tests for GET /Device → 400 when required inputs are missing."""
def test_missing_apikey_returns_400(self, stub: SdsFhirApiStub) -> None:
"""The spec requires the ``apikey`` header; its absence must yield 400."""
response = stub.get_device_bundle(
headers={},
params={"organization": _ORG_PROVIDER, "identifier": _INTERACTION_ID_PARAM},
)
assert response.status_code == 400
self.verify_error_response_body(response, "Missing required header: apikey")
def test_missing_organization_returns_400(self, stub: SdsFhirApiStub) -> None:
"""``organization`` is a required query parameter for /Device."""
response = stub.get_device_bundle(
headers={"apikey": "test-key"},
params={"identifier": _INTERACTION_ID_PARAM},
)
assert response.status_code == 400
self.verify_error_response_body(
response, "Missing required query parameter: organization"
)
def test_missing_identifier_returns_400(self, stub: SdsFhirApiStub) -> None:
"""``identifier`` is a required query parameter for /Device."""
response = stub.get_device_bundle(
headers={"apikey": "test-key"},
params={"organization": _ORG_PROVIDER},
)
assert response.status_code == 400
self.verify_error_response_body(
response, "Missing required query parameter: identifier"
)
def test_missing_apikey_echoes_correlation_id(self, stub: SdsFhirApiStub) -> None:
"""``X-Correlation-Id`` must be echoed even in error responses."""
response = stub.get_device_bundle(
headers={"X-Correlation-Id": _VALID_CORRELATION_ID}, # no apikey
params={"organization": _ORG_PROVIDER, "identifier": _INTERACTION_ID_PARAM},
)
assert response.status_code == 400
assert response.headers.get("X-Correlation-Id") == _VALID_CORRELATION_ID
self.verify_error_response_body(response, "Missing required header: apikey")
def verify_error_response_body(
self, response: Any, expected_diagnostics: str
) -> None:
body = response.json()
assert body["resourceType"] == "OperationOutcome"
assert isinstance(body.get("issue"), list)
assert len(body["issue"]) == 1
issue = body["issue"][0]
assert issue["severity"] == "error"
assert issue["code"] == "invalid"
assert "diagnostics" in body["issue"][0]
assert body["issue"][0]["diagnostics"] == expected_diagnostics
# ---------------------------------------------------------------------------
# GET /Endpoint – 200 successful retrieval
# ---------------------------------------------------------------------------
class TestGetEndpointBundleSuccess:
"""Contract tests for the happy-path GET /Endpoint → 200 response."""
def test_endpoint_bundle_matches_expected_response(
self, stub: SdsFhirApiStub
) -> None:
response = stub.get_endpoint_bundle(
headers={"apikey": "test-key"},
params={"identifier": _INTERACTION_ID_PARAM},
)
assert response.status_code == 200
assert "application/fhir+json" in response.headers["Content-Type"]
body = response.json()
assert body["resourceType"] == "Bundle"
assert body["type"] == "searchset"
assert body["total"] == len(body["entry"])
for entry in body["entry"]:
endpoint_id = entry["resource"]["id"]
assert (
entry["fullUrl"]
== f"https://sandbox.api.service.nhs.uk/spine-directory/FHIR/R4/Endpoint/{endpoint_id}"
)
assert entry["search"]["mode"] == "match"
def test_x_correlation_id_echoed_back_when_provided(
self, stub: SdsFhirApiStub
) -> None:
"""The spec states ``X-Correlation-Id`` is mirrored back in the response."""
response = stub.get_endpoint_bundle(
headers={"apikey": "test-key", "X-Correlation-Id": _VALID_CORRELATION_ID},
params={"identifier": _INTERACTION_ID_PARAM},
)
assert response.headers.get("X-Correlation-Id") == _VALID_CORRELATION_ID
def test_x_correlation_id_absent_when_not_provided(
self, stub: SdsFhirApiStub
) -> None:
"""``X-Correlation-Id`` must not appear in the response when not supplied."""
response = stub.get_endpoint_bundle(
headers={"apikey": "test-key"},
params={"identifier": _INTERACTION_ID_PARAM},
)
assert "X-Correlation-Id" not in response.headers
def test_empty_bundle_returned_for_unknown_org(self, stub: SdsFhirApiStub) -> None:
"""An organisation not present in the stub must yield an empty Bundle."""
response = stub.get_endpoint_bundle(
headers={"apikey": "test-key"},
params={
"organization": _ORG_UNKNOWN,
"identifier": _INTERACTION_ID_PARAM,
},
)
assert response.status_code == 200
body = response.json()
assert body["resourceType"] == "Bundle"
assert body["total"] == 0
assert body["entry"] == []
# ---------------------------------------------------------------------------
# GET /Endpoint – Endpoint resource structure
# ---------------------------------------------------------------------------
class TestGetEndpointResourceStructure:
"""Contract tests verifying the shape of returned Endpoint resources."""
def test_endpoint_resource_type_is_endpoint(self, stub: SdsFhirApiStub) -> None:
"""Each resource inside the Bundle must have ``resourceType: "Endpoint"``."""
response = stub.get_endpoint_bundle(
headers={"apikey": "test-key"},
params={
"organization": _ORG_PROVIDER,
"identifier": _INTERACTION_ID_PARAM,
},
)
body = response.json()
assert len(body["entry"]) == 1
entry = body["entry"][0]
resource = entry["resource"]
assert resource["resourceType"] == "Endpoint"
assert resource["id"] == "E0E0E921-92CA-4A88-A550-2DBB36F703AF"
assert resource["status"] == "active"
ct = resource["connectionType"]
assert (
ct["system"]
== "https://terminology.hl7.org/CodeSystem/endpoint-connection-type"
)
assert ct["code"] == "hl7-fhir-rest"
assert len(resource["payloadType"]) == 1
assert resource["address"] == "https://provider.example.com/fhir"
assert (
resource["managingOrganization"]["identifier"]["system"]
== FHIRSystem.ODS_CODE
)
managing_org = resource["managingOrganization"]
assert managing_org["identifier"]["system"] == FHIRSystem.ODS_CODE
assert isinstance(resource["identifier"], list)
assert len(resource["identifier"]) == 1
identifiers = resource["identifier"]
assert identifiers[0]["system"] == FHIRSystem.NHS_SPINE_ASID
# ---------------------------------------------------------------------------
# GET /Endpoint – 400 validation errors
# ---------------------------------------------------------------------------
class TestGetEndpointBundleValidationErrors:
"""Contract tests for GET /Endpoint → 400 when required inputs are missing."""
def test_missing_apikey_returns_400(self, stub: SdsFhirApiStub) -> None:
"""The spec requires the ``apikey`` header; its absence must yield 400."""
response = stub.get_endpoint_bundle(
headers={},
params={"identifier": _INTERACTION_ID_PARAM},
)
assert response.status_code == 400
self.verify_error_response_body(response, "Missing required header: apikey")
def test_missing_identifier_returns_400(self, stub: SdsFhirApiStub) -> None:
"""``identifier`` is a required query parameter for /Endpoint."""
response = stub.get_endpoint_bundle(
headers={"apikey": "test-key"},
params={},
)
assert response.status_code == 400
self.verify_error_response_body(
response, "Missing required query parameter: identifier"
)
def test_missing_apikey_echoes_correlation_id(self, stub: SdsFhirApiStub) -> None:
"""``X-Correlation-Id`` must be echoed even in error responses."""
response = stub.get_endpoint_bundle(
headers={"X-Correlation-Id": _VALID_CORRELATION_ID}, # no apikey
params={"identifier": _INTERACTION_ID_PARAM},
)
assert response.status_code == 400
assert response.headers.get("X-Correlation-Id") == _VALID_CORRELATION_ID
self.verify_error_response_body(response, "Missing required header: apikey")
def verify_error_response_body(
self, response: Any, expected_diagnostics: str
) -> None:
body = response.json()
assert body["resourceType"] == "OperationOutcome"
assert isinstance(body.get("issue"), list)
assert len(body["issue"]) == 1
assert body["issue"][0]["severity"] == "error"
assert body["issue"][0]["code"] == "invalid"
assert "diagnostics" in body["issue"][0]
assert body["issue"][0]["diagnostics"] == expected_diagnostics
# ---------------------------------------------------------------------------
# get() convenience wrapper – routes by URL path
# ---------------------------------------------------------------------------
class TestGetConvenienceMethod:
"""Verify the ``get()`` wrapper routes correctly based on the URL path."""
def test_device_url_returns_device_bundle(self, stub: SdsFhirApiStub) -> None:
"""A URL containing ``/Device`` must be routed to get_device_bundle."""
response = stub.get(
url=_BASE_DEVICE_URL,
headers={"apikey": "test-key"},
params={"organization": _ORG_PROVIDER, "identifier": _INTERACTION_ID_PARAM},
)
assert response.status_code == 200
body = response.json()
assert body["resourceType"] == "Bundle"
# Verify Device resources were returned
assert len(body["entry"]) == 1
assert body["entry"][0]["resource"]["resourceType"] == "Device"
def test_endpoint_url_returns_endpoint_bundle(self, stub: SdsFhirApiStub) -> None:
"""A URL containing ``/Endpoint`` must be routed to get_endpoint_bundle."""
response = stub.get(
url=_BASE_ENDPOINT_URL,
headers={"apikey": "test-key"},
params={"identifier": _INTERACTION_ID_PARAM},
)
assert response.status_code == 200
body = response.json()
assert body["resourceType"] == "Bundle"
# Verify Endpoint resources returned
for entry in body["entry"]:
assert entry["resource"]["resourceType"] == "Endpoint"
def test_get_records_last_url(self, stub: SdsFhirApiStub) -> None:
"""The stub must record the last URL it was called with."""
stub.get(
url=_BASE_DEVICE_URL,
headers={"apikey": "test-key"},
params={"organization": _ORG_PROVIDER, "identifier": _INTERACTION_ID_PARAM},
)
assert stub.get_url == _BASE_DEVICE_URL
def test_get_records_last_headers(self, stub: SdsFhirApiStub) -> None:
"""The stub must record the last headers it was called with."""
headers = {"apikey": "test-key", "X-Correlation-Id": _VALID_CORRELATION_ID}
stub.get(
url=_BASE_DEVICE_URL,
headers=headers,
params={"organization": _ORG_PROVIDER, "identifier": _INTERACTION_ID_PARAM},
)
assert stub.get_headers == headers
def test_get_records_last_params(self, stub: SdsFhirApiStub) -> None:
"""The stub must record the last query params it was called with."""
params = {"organization": _ORG_PROVIDER, "identifier": _INTERACTION_ID_PARAM}
stub.get(
url=_BASE_DEVICE_URL,
headers={"apikey": "test-key"},
params=params,
)
assert stub.get_params == params
def test_get_records_last_timeout(self, stub: SdsFhirApiStub) -> None:
"""The stub must record the last timeout value it was called with."""
stub.get(
url=_BASE_DEVICE_URL,
headers={"apikey": "test-key"},
params={"organization": _ORG_PROVIDER, "identifier": _INTERACTION_ID_PARAM},
timeout=30,
)
assert stub.get_timeout == 30
# ---------------------------------------------------------------------------
# upsert_device / upsert_endpoint – dynamic data management
# ---------------------------------------------------------------------------
class TestUpsertOperations:
"""Verify that devices and endpoints can be dynamically added to the stub."""
def test_upsert_device_is_returned_by_get_device_bundle(
self, stub: SdsFhirApiStub
) -> None:
"""A device added via upsert_device must be returned in subsequent queries."""
stub.clear_devices()
new_device: dict[str, object] = {
"resourceType": "Device",
"id": "new-device-123",
"identifier": [],
"owner": {
"identifier": {"system": FHIRSystem.ODS_CODE, "value": "NEW_ORG"}
},
}
stub.upsert_device(
organization_ods="NEW_ORG",
service_interaction_id=ACCESS_RECORD_STRUCTURED_INTERACTION_ID,
device=new_device,
)
response = stub.get_device_bundle(
headers={"apikey": "test-key"},
params={
"organization": f"{FHIRSystem.ODS_CODE}|NEW_ORG",
"identifier": _INTERACTION_ID_PARAM,
},
)
body = response.json()
assert body["total"] == 1
assert body["entry"][0]["resource"]["id"] == "new-device-123"
def test_clear_devices_removes_all_devices(self, stub: SdsFhirApiStub) -> None:
"""After clear_devices, all Device queries must return an empty Bundle."""
stub.clear_devices()
response = stub.get_device_bundle(
headers={"apikey": "test-key"},
params={"organization": _ORG_PROVIDER, "identifier": _INTERACTION_ID_PARAM},
)
body = response.json()
assert body["total"] == 0
def test_upsert_endpoint_is_returned_by_get_endpoint_bundle(
self, stub: SdsFhirApiStub
) -> None:
"""An endpoint added via upsert_endpoint must be returned in subsequent
queries."""
stub.clear_endpoints()
new_asid = "999000000001"
new_endpoint: dict[str, object] = {
"resourceType": "Endpoint",
"id": "new-endpoint-456",
"status": "active",
"connectionType": {
"system": SdsFhirApiStub.CONNECTION_SYSTEM,
"code": "hl7-fhir-rest",
"display": SdsFhirApiStub.CONNECTION_DISPLAY,
},
"payloadType": [{"coding": [{"system": SdsFhirApiStub.CODING_SYSTEM}]}],
"address": "https://new.example.com/fhir",
"managingOrganization": {
"identifier": {"system": FHIRSystem.ODS_CODE, "value": "NEW_ORG"}
},
"identifier": [{"system": FHIRSystem.NHS_SPINE_ASID, "value": new_asid}],
}
stub.upsert_endpoint(
organization_ods="NEW_ORG",
service_interaction_id=ACCESS_RECORD_STRUCTURED_INTERACTION_ID,
endpoint=new_endpoint,
)
response = stub.get_endpoint_bundle(
headers={"apikey": "test-key"},
params={
"organization": f"{FHIRSystem.ODS_CODE}|NEW_ORG",
"identifier": _INTERACTION_ID_PARAM,
},
)
body = response.json()
assert body["total"] == 1
assert body["entry"][0]["resource"]["id"] == "new-endpoint-456"
def test_clear_endpoints_removes_all_endpoints(self, stub: SdsFhirApiStub) -> None:
"""After clear_endpoints, all Endpoint queries must return an empty Bundle."""
stub.clear_endpoints()
response = stub.get_endpoint_bundle(
headers={"apikey": "test-key"},
params={"identifier": _INTERACTION_ID_PARAM},
)
body = response.json()
assert body["total"] == 0