-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_api.py
More file actions
264 lines (206 loc) · 7.99 KB
/
test_api.py
File metadata and controls
264 lines (206 loc) · 7.99 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
import io
import os
from unittest.mock import MagicMock, patch
import pydicom
import pytest
from django.core.files.uploadedfile import SimpleUploadedFile
from ninja.testing import TestClient
from pydicom.uid import generate_uid
from manage_breast_screening.core.api import api
from manage_breast_screening.gateway.models import GatewayActionStatus
from manage_breast_screening.gateway.tests.factories import GatewayActionFactory
from manage_breast_screening.participants.models.appointment import (
AppointmentStatusNames,
)
from manage_breast_screening.participants.tests.factories import AppointmentFactory
from ..authentication import Authentication
from ..dicom_recorder import DicomRecorder
from ..models import Study
os.environ["NINJA_SKIP_REGISTRY"] = "yes"
client = TestClient(api)
@pytest.fixture(autouse=True)
def setup(monkeypatch):
monkeypatch.setenv("API_ENABLED", "true")
monkeypatch.setenv("API_AUDIENCE", "test_audience")
monkeypatch.setenv("TENANT_ID", "test_tenant_id")
@pytest.fixture
def dicom_file(dataset) -> bytes:
with io.BytesIO() as buffer:
pydicom.dcmwrite(buffer, dataset, enforce_file_format=True)
buffer.seek(0)
return SimpleUploadedFile(
"temp.dcm", buffer.read(), content_type="application/dicom"
)
@pytest.fixture
def appointment_stub():
return AppointmentFactory.stub(
is_in_progress=MagicMock(return_value=True),
)
@pytest.fixture
def mock_authentication():
with patch.object(Authentication, "authenticate", return_value={"sub": "testuser"}):
yield
@pytest.mark.django_db
def test_upload_success(dataset, dicom_file, mock_authentication, appointment_stub):
appointment = AppointmentFactory(current_status=AppointmentStatusNames.IN_PROGRESS)
with patch(
"manage_breast_screening.dicom.dicom_recorder.lookup_appointment",
return_value=appointment,
):
response = client.put(
f"/dicom/{appointment.pk}",
FILES={"file": dicom_file},
headers={"Authorization": "Bearer testtoken"},
)
assert response.status_code == 201
json = response.json()
study = Study.objects.last()
assert json["study_instance_uid"] == dataset.StudyInstanceUID
assert json["series_instance_uid"] == dataset.SeriesInstanceUID
assert json["sop_instance_uid"] == dataset.SOPInstanceUID
assert json["instance_id"] == str(study.images().first().id)
assert study.source_message_id == str(appointment.pk)
def test_upload_no_file(mock_authentication):
response = client.put(
"/dicom/abc123",
FILES={"file": None},
headers={"Authorization": "Bearer testtoken"},
)
assert response.status_code == 422
def test_upload_invalid_file(mock_authentication, appointment_stub):
invalid_file = SimpleUploadedFile(
"invalid.dcm", b"not a dicom file", content_type="application/dicom"
)
with patch(
"manage_breast_screening.dicom.dicom_recorder.lookup_appointment",
return_value=appointment_stub,
):
response = client.put(
"/dicom/abc123",
FILES={"file": invalid_file},
headers={"Authorization": "Bearer testtoken"},
)
assert response.status_code == 400
assert response.json()["title"] == "Invalid DICOM file"
assert response.json()["status"] == 400
assert response.json()["detail"] == "The uploaded file is not a valid DICOM file."
def test_upload_file_thats_too_large(mock_authentication):
invalid_file = MagicMock(spec=SimpleUploadedFile, size=101 * 1024 * 1024)
response = client.put(
"/dicom/abc123",
FILES={"file": invalid_file},
headers={"Authorization": "Bearer testtoken"},
)
assert response.status_code == 400
assert response.json()["title"] == "File too large"
assert response.json()["status"] == 400
assert response.json()["detail"] == "The file cannot be larger than 100MB"
def test_upload_missing_uids(dataset, mock_authentication, appointment_stub):
del dataset.StudyInstanceUID
del dataset.SeriesInstanceUID
del dataset.SOPInstanceUID
with io.BytesIO() as buffer:
pydicom.dcmwrite(buffer, dataset, enforce_file_format=True)
buffer.seek(0)
dicom_file = SimpleUploadedFile(
"temp.dcm", buffer.read(), content_type="application/dicom"
)
with patch(
"manage_breast_screening.dicom.dicom_recorder.lookup_appointment",
return_value=appointment_stub,
):
response = client.put(
"/dicom/abc123",
FILES={"file": dicom_file},
headers={"Authorization": "Bearer testtoken"},
)
assert response.status_code == 400
assert response.json()["title"] == "Missing DICOM attributes"
assert response.json()["status"] == 400
assert (
response.json()["detail"]
== "The DICOM file is missing required UID attributes."
)
def test_upload_appointment_not_in_progress(
dicom_file, mock_authentication, appointment_stub
):
appointment_stub.is_in_progress.return_value = False
with patch(
"manage_breast_screening.dicom.dicom_recorder.lookup_appointment",
return_value=appointment_stub,
):
response = client.put(
"/dicom/abc123",
FILES={"file": dicom_file},
headers={"Authorization": "Bearer testtoken"},
)
assert response.status_code == 500
assert response.json()["title"] == "Internal Server Error"
def test_upload_when_api_disabled(dicom_file, mock_authentication, monkeypatch):
monkeypatch.setenv("API_ENABLED", "false")
response = client.put(
"/dicom/abc123",
FILES={"file": dicom_file},
headers={"Authorization": "Bearer testtoken"},
)
assert response.status_code == 403
assert response.json()["status"] == "API is not available"
def test_upload_no_auth(dicom_file):
response = client.put(
"/dicom/abc123",
FILES={"file": dicom_file},
)
assert response.status_code == 401
assert response.json() == {
"detail": "Unauthorized",
}
def test_upload_invalid_auth(dicom_file):
response = client.put(
"/dicom/abc123",
FILES={"file": dicom_file},
headers={"Authorization": "Bearer invalidtoken"},
)
assert response.status_code == 401
assert response.json() == {
"detail": "Unauthorized",
}
def test_upload_bypass_token_validation(dicom_file):
with patch.object(Authentication, "bypass_authentication", return_value=True):
with patch.object(
DicomRecorder,
"get_or_create_records",
return_value=(
MagicMock(study_instance_uid=generate_uid()),
MagicMock(series_instance_uid=generate_uid()),
MagicMock(sop_instance_uid=generate_uid(), id=1),
),
):
response = client.put(
"/dicom/abc123",
FILES={"file": dicom_file},
headers={"Authorization": "Bearer anytoken"},
)
assert response.status_code == 201
@pytest.mark.django_db
def test_report_failure(mock_authentication):
action = GatewayActionFactory()
response = client.patch(
f"/dicom/{action.id}/failure",
json={"error": "Missing PatientID"},
headers={"Authorization": "Bearer testtoken"},
)
assert response.status_code == 200
assert response.json()["status"] == "failure recorded"
action.refresh_from_db()
assert action.status == GatewayActionStatus.IMAGE_FAILED
assert action.last_error == "Missing PatientID"
assert action.failed_at is not None
@pytest.mark.django_db
def test_report_failure_action_not_found(mock_authentication):
response = client.patch(
"/dicom/00000000-0000-0000-0000-000000000000/failure",
json={"error": "Missing PatientID"},
headers={"Authorization": "Bearer testtoken"},
)
assert response.status_code == 404
assert response.json()["title"] == "Not Found"