import io import time import zipfile from pathlib import Path import numpy as np import pytest from fastapi.testclient import TestClient from pydicom.dataset import FileDataset, FileMetaDataset from pydicom.uid import ExplicitVRLittleEndian, generate_uid from service.api import create_app from service.storage import Limits def dicom(uid=None, sop=None, frames=12): meta = FileMetaDataset() meta.TransferSyntaxUID = ExplicitVRLittleEndian meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.12.1' meta.MediaStorageSOPInstanceUID = sop or generate_uid() ds = FileDataset(None, {}, file_meta=meta, preamble=b'\0' * 128) ds.SOPClassUID = meta.MediaStorageSOPClassUID ds.SOPInstanceUID = meta.MediaStorageSOPInstanceUID ds.StudyInstanceUID = uid or generate_uid() ds.SeriesInstanceUID = generate_uid() ds.PatientName = 'PRIVATE^PERSON' ds.PatientID = 'PRIVATE_PATIENT_ID' ds.Rows = ds.Columns = 16 ds.NumberOfFrames = frames ds.BitsAllocated = ds.BitsStored = 8 ds.HighBit = 7 ds.PixelRepresentation = 0 ds.SamplesPerPixel = 1 ds.PhotometricInterpretation = 'MONOCHROME2' ds.PixelData = np.arange(frames * 256, dtype=np.uint8).tobytes() output = io.BytesIO() ds.save_as(output, enforce_file_format=True) return output.getvalue() class FakeEngine: def __init__(self): self.calls = [] self.fail = False def status(self): return {'device': 'cpu', 'model': {'status': 'not_loaded', 'loaded': 0, 'total': 10}} def classify(self, paths, progress): return [{'path': p, 'artery': 'left' if i % 2 == 0 else 'right', 'probability_right': i % 2} for i, p in enumerate(paths)] def infer(self, left, right, progress): self.calls.append((left, right)) if self.fail: raise RuntimeError('/private/upload/SECRET invalid') complete = bool(left and right) return {'raw': 8. if complete else None, 'calibrated': 10. if complete else None, 'complete': complete, 'per_fold': [], 'provenance': {'test_fixture': True}} @pytest.fixture def workspace(tmp_path): engine = FakeEngine() app = create_app(data_root=tmp_path / 'data', engine=engine) with TestClient(app) as client: yield client, app, engine def upload(client, payloads): return client.post('/api/studies', files=[('files', (f'projection{i}.dcm', p, 'application/dicom')) for i, p in enumerate(payloads)]) def wait(client, job): for _ in range(200): status = client.get('/api/jobs/' + job['id']).json() if status['status'] in {'completed', 'failed'}: return status time.sleep(.01) pytest.fail('job did not complete') def test_upload_groups_by_study_and_rejects_duplicate(workspace): client, app, _ = workspace uid = generate_uid() a = dicom(uid) response = upload(client, [a, dicom(uid), dicom(), a]) assert response.status_code == 200 result = response.json() assert len(result['studies']) == 2 assert len(result['studies'][0]['projections']) == 2 assert len(result['rejected']) == 1 assert 'PRIVATE' not in response.text image = client.get(result['studies'][0]['projections'][0]['preview_url']) assert image.status_code == 200 and image.content.startswith(b'\x89PNG') assert image.headers['cache-control'] == 'no-store' def test_classification_inference_and_delete(workspace): client, app, engine = workspace uid = generate_uid() study = upload(client, [dicom(uid), dicom(uid)]).json()['studies'][0] job = client.post(f"/api/studies/{study['id']}/classify").json() classification = wait(client, job) assert classification['status'] == 'completed' assert [p['artery'] for p in classification['result']['study']['projections']] == ['left', 'right'] job = client.post(f"/api/studies/{study['id']}/run", json={}).json() result = wait(client, job) assert result['result']['calibrated'] == 10. assert client.delete('/api/studies/' + study['id']).status_code == 200 assert client.get('/api/studies/' + study['id']).status_code == 404 assert client.get('/api/jobs/' + job['id']).status_code == 404 assert not any(app.state.store.root.iterdir()) def test_manual_assignment_and_order_overrides_are_rejected(workspace): client, _, engine = workspace uid = generate_uid() study = upload(client, [dicom(uid), dicom(uid), dicom(uid)]).json()['studies'][0] ids = [p['id'] for p in study['projections']] path = f"/api/studies/{study['id']}/run" assert study['classification_complete'] is False assert client.post(path, json={}).status_code == 409 assignments = [{'id': ids[2], 'artery': 'left'}, {'id': ids[0], 'artery': 'left'}, {'id': ids[1], 'artery': 'right'}] for override in ({'assignments': assignments}, {'assignments': None}, {'order': list(reversed(ids))}, {'classification_complete': True}): assert client.post(path, json=override).status_code == 422 classified = wait(client, client.post(f"/api/studies/{study['id']}/classify").json()) assert classified['result']['study']['classification_complete'] is True assert client.post(path, json={'assignments': assignments}).status_code == 422 assert wait(client, client.post(path, json={}).json())['status'] == 'completed' assert [Path(p).name for p in engine.calls[-1][0]] == [ids[0], ids[2]] assert [p['id'] for p in client.get('/api/studies/' + study['id']).json()['projections']] == ids def test_short_and_unassigned_projections_cannot_be_scored(workspace): client, _, _ = workspace uid = generate_uid() study = upload(client, [dicom(uid, frames=5), dicom(uid)]).json()['studies'][0] assert study['projections'][0]['artery'] == 'exclude' path = f"/api/studies/{study['id']}/run" assert client.post(path, json={}).status_code == 409 assert client.post(path, json={'assignments': [{'id': p['id'], 'artery': 'left'} for p in study['projections']]}).status_code == 422 def test_missing_side_remains_partial_and_failure_has_no_score(workspace): client, _, engine = workspace study = upload(client, [dicom()]).json()['studies'][0] assert wait(client, client.post('/api/studies/' + study['id'] + '/classify').json())['status'] == 'completed' body = {} path = f"/api/studies/{study['id']}/run" result = wait(client, client.post(path, json=body).json()) assert result['result']['complete'] is False assert result['result']['total']['calibrated'] is None engine.fail = True result = wait(client, client.post(path, json=body).json()) assert result['status'] == 'failed' and result['result'] is None assert 'SECRET' not in result['error'] def test_unsafe_zip_and_unreadable_files_rejected(workspace): client, app, _ = workspace output = io.BytesIO() with zipfile.ZipFile(output, 'w') as z: z.writestr('../../escape.dcm', dicom()) response = client.post('/api/studies', files=[('files', ('bad.zip', output.getvalue(), 'application/zip'))]) assert response.status_code == 422 assert response.json()['studies'] == [] assert 'unsafe' in response.json()['rejected'][0]['reason'] assert not any(app.state.store.root.iterdir()) assert upload(client, [b'not DICOM']).status_code == 422 def test_safe_zip_and_size_limit(workspace, tmp_path): client, _, _ = workspace output = io.BytesIO() with zipfile.ZipFile(output, 'w') as z: z.writestr('study/image.dcm', dicom()) response = client.post('/api/studies', files=[('files', ('study.zip', output.getvalue(), 'application/zip'))]) assert response.status_code == 200 app = create_app(data_root=tmp_path / 'limited', engine=FakeEngine(), limits=Limits(max_request_bytes=10)) with TestClient(app) as limited: assert limited.post('/api/studies', content=b'x' * 11).status_code == 413 def test_expiry_and_unknown_ids(workspace): client, app, _ = workspace study = upload(client, [dicom()]).json()['studies'][0] app.state.store.studies[study['id']].touched_at = 0 app.state.store.cleanup() assert client.get('/api/studies/' + study['id']).status_code == 404 assert client.get('/api/jobs/not-a-capability').status_code == 404 assert client.get('/api/status').json()['model']['loaded'] == 0 def test_animated_preview_and_fixed_example_loading(tmp_path, monkeypatch): import json import huggingface_hub examples = json.loads((Path(__file__).parents[1] / 'service' / 'examples.json').read_text()) example = examples[0] # This test exercises source download/GIF generation independently of bundled real caches. example.pop('cache_file', None) for entry in example['files']: entry.pop('preview', None) examples_path = tmp_path / 'examples.json' examples_path.write_text(json.dumps([example])) paths = {} for entry in example['files']: path = tmp_path / entry['sop_uid'] path.write_bytes(dicom(example['study_uid'], entry['sop_uid'])) paths[entry['path']] = str(path) def fake_download(**kwargs): assert kwargs['revision'] == example['revision'] assert kwargs['repo_id'] == example['repository'] return paths[kwargs['filename']] monkeypatch.setattr(huggingface_hub, 'hf_hub_download', fake_download) engine = FakeEngine() app = create_app(data_root=tmp_path / 'data', engine=engine, examples_path=examples_path) with TestClient(app) as client: assert client.get('/api/examples').json()['examples'][0]['id'] == example['id'] assert client.post('/api/examples/arbitrary-url/load').status_code == 404 job = client.post('/api/examples/' + example['id'] + '/load').json() result = wait(client, job) assert result['status'] == 'completed' study = result['result']['studies'][0] assert study['classification_complete'] is False assert all(p['artery'] == 'unassigned' for p in study['projections']) gif = client.get(study['projections'][0]['animation_url']) assert gif.status_code == 200 and gif.content.startswith(b'GIF') assert engine.calls == [] def test_disk_capacity_is_enforced(tmp_path): payload = dicom() app = create_app(data_root=tmp_path / 'quota', engine=FakeEngine(), limits=Limits(max_stored_bytes=len(payload))) with TestClient(app) as client: assert upload(client, [payload]).status_code == 200 assert upload(client, [dicom()]).status_code == 507 assert len(app.state.store.studies) == 1 def test_full_video_keeps_every_frame_and_supports_seeking(workspace): import json import shutil import subprocess if not shutil.which('ffmpeg') or not shutil.which('ffprobe'): pytest.skip('Local FFmpeg is required for complete cine preview test') client, app, _ = workspace study = upload(client, [dicom(frames=60)]).json()['studies'][0] url = study['projections'][0]['video_url'] video = client.get(url) assert video.status_code == 200 and video.headers['content-type'] == 'video/mp4' stored = app.state.store.studies[study['id']] path = stored.directory / (study['projections'][0]['id'] + '.mp4') info = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'stream=nb_frames,width,height', '-of', 'json', str(path)], check=True, capture_output=True) assert int(json.loads(info.stdout)['streams'][0]['nb_frames']) == 60 mtime = path.stat().st_mtime_ns part = client.get(url, headers={'Range': 'bytes=0-99'}) assert part.status_code == 206 and len(part.content) == 100 assert path.stat().st_mtime_ns == mtime assert stored.readers == 0 assert not app.state.store.workspaces assert client.delete('/api/studies/' + study['id']).status_code == 200 assert not path.exists() def test_expansion_limit_is_shared_between_archives(tmp_path): payload1, payload2 = dicom(), dicom() archives = [] for index, payload in enumerate((payload1, payload2)): stream = io.BytesIO() with zipfile.ZipFile(stream, 'w', compression=zipfile.ZIP_DEFLATED) as z: z.writestr('image.dcm', payload) archives.append(('files', (f'{index}.zip', stream.getvalue(), 'application/zip'))) app = create_app(data_root=tmp_path / 'data', engine=FakeEngine(), limits=Limits(max_request_bytes=len(payload1) + 100)) with TestClient(app) as client: response = client.post('/api/studies', files=archives) assert response.status_code == 200 assert len(response.json()['studies']) == 1 assert len(response.json()['rejected']) == 1 assert 'uncompressed size limit' in response.json()['rejected'][0]['reason'] assert not app.state.store.workspaces def test_active_workspace_and_preview_are_not_expired(workspace): import os client, app, _ = workspace store = app.state.store study = upload(client, [dicom()]).json()['studies'][0] held = store.acquire(study['id']) held.touched_at = 0 staging = store.workspace('incoming-') os.utime(staging, (0, 0)) store.cleanup() assert staging.exists() and held.directory.exists() assert client.delete('/api/studies/' + study['id']).status_code == 409 store.release(held) held.touched_at = 0 assert client.get('/api/studies/' + study['id']).status_code == 404 store.remove_workspace(staging) def test_streamed_body_without_content_length_is_bounded(tmp_path): app = create_app(data_root=tmp_path / 'data', engine=FakeEngine(), limits=Limits(max_request_bytes=100)) with TestClient(app) as client: response = client.post('/api/studies', content=iter([b'--xxx\r\n', b'a' * 101]), headers={'Content-Type': 'multipart/form-data; boundary=xxx'}) assert response.status_code == 413 def test_concurrent_upload_is_bounded_before_parsing(workspace, monkeypatch): import threading from concurrent.futures import ThreadPoolExecutor import service.api as api client, _, _ = workspace entered, release = threading.Event(), threading.Event() original = api.inspect_dicom def slow_inspect(*args, **kwargs): entered.set() assert release.wait(2) return original(*args, **kwargs) monkeypatch.setattr(api, 'inspect_dicom', slow_inspect) with ThreadPoolExecutor(max_workers=1) as pool: first = pool.submit(upload, client, [dicom()]) assert entered.wait(2) try: assert upload(client, [dicom()]).status_code == 429 finally: release.set() assert first.result().status_code == 200 def test_queue_and_active_study_deletion_are_bounded(tmp_path): import threading engine = FakeEngine() entered, release = threading.Event(), threading.Event() original = engine.classify def delayed(paths, progress): entered.set() assert release.wait(2) return original(paths, progress) engine.classify = delayed app = create_app(data_root=tmp_path / 'data', engine=engine, limits=Limits(max_pending_jobs=1)) with TestClient(app) as client: studies = upload(client, [dicom(), dicom()]).json()['studies'] job = client.post('/api/studies/' + studies[0]['id'] + '/classify').json() assert entered.wait(2) try: assert client.post('/api/studies/' + studies[1]['id'] + '/classify').status_code == 429 assert client.delete('/api/studies/' + studies[0]['id']).status_code == 409 finally: release.set() assert wait(client, job)['status'] == 'completed' def test_uncertain_classifier_outputs_are_automatically_excluded(workspace): client, _, engine = workspace uid = generate_uid() study = upload(client, [dicom(uid), dicom(uid), dicom(uid), dicom(uid, frames=5)]).json()['studies'][0] def outputs(paths, progress): return [{'path': p, 'artery': side, 'probability_right': probability} for p, side, probability in zip(paths, ['left', 'unassigned', 'right'], [.1, .5, .9])] engine.classify = outputs finished = wait(client, client.post('/api/studies/' + study['id'] + '/classify').json()) classified = finished['result']['study'] assert classified['classification_complete'] and classified['classification_source'] == 'server_classifier' assert [p['artery'] for p in classified['projections']] == ['left', 'exclude', 'right', 'exclude'] assert classified['projections'][1]['probability'] == .5 assert classified['projections'][1]['reason'] == 'Low-confidence artery classification; automatically excluded.' assert classified['projections'][3]['reason'] == 'Fewer than 10 frames; automatically excluded.' scored = wait(client, client.post('/api/studies/' + study['id'] + '/run', json={}).json()) assert scored['status'] == 'completed' and scored['result']['input_counts']['excluded'] == 2 assert [len(paths) for paths in engine.calls[-1]] == [1, 1] assert len(scored['result']['classification']['outputs']) == 4 @pytest.mark.parametrize('failure', ['count', 'identity', 'probability', 'label', 'probability_alias']) def test_invalid_classifier_output_does_not_apply_partial_updates(workspace, failure): client, app, engine = workspace uid = generate_uid() study = upload(client, [dicom(uid), dicom(uid)]).json()['studies'][0] assert wait(client, client.post('/api/studies/' + study['id'] + '/classify').json())['status'] == 'completed' before = client.get('/api/studies/' + study['id']).json()['projections'] def bad_outputs(paths, progress): values = [{'path': paths[0], 'artery': 'right', 'probability_right': .99}, {'path': paths[1], 'artery': 'left', 'probability_right': .01}] if failure == 'count': values.pop() elif failure == 'identity': values[1]['path'] = paths[0] elif failure == 'probability': values[1]['probability_right'] = float('nan') elif failure == 'probability_alias': values[1]['probability'] = .99 else: values[1]['artery'] = 'right' return values engine.classify = bad_outputs failed = wait(client, client.post('/api/studies/' + study['id'] + '/classify').json()) assert failed['status'] == 'failed' after = client.get('/api/studies/' + study['id']).json() assert after['projections'] == before assert after['classification_complete'] is False and after['classification_source'] is None assert client.post('/api/studies/' + study['id'] + '/run', json={}).status_code == 409