|
| 1 | +import os |
| 2 | +from fastapi.testclient import TestClient |
| 3 | + |
| 4 | +from medical_diagnosis_model.backend.app import app, _RATE_LIMIT_STORE |
| 5 | + |
| 6 | + |
| 7 | +def test_cors_preflight_allows_localhost_3000(): |
| 8 | + client = TestClient(app) |
| 9 | + headers = { |
| 10 | + "Origin": "http://localhost:3000", |
| 11 | + "Access-Control-Request-Method": "POST", |
| 12 | + } |
| 13 | + r = client.options("/api/v2/diagnose", headers=headers) |
| 14 | + assert r.status_code in (200, 204) |
| 15 | + # Header may vary case; TestClient lowercases internally |
| 16 | + assert r.headers.get("access-control-allow-origin") == "http://localhost:3000" |
| 17 | + |
| 18 | + |
| 19 | +def test_api_key_auth_enforced_and_allows_valid_key(monkeypatch): |
| 20 | + client = TestClient(app) |
| 21 | + monkeypatch.setenv("MDM_API_KEY", "testkey") |
| 22 | + |
| 23 | + resp = client.post("/api/v2/diagnose", json={"data": {"Fever": 8}}) |
| 24 | + assert resp.status_code == 401 |
| 25 | + |
| 26 | + resp = client.post( |
| 27 | + "/api/v2/diagnose", |
| 28 | + headers={"X-API-Key": "wrong"}, |
| 29 | + json={"data": {"Fever": 8}}, |
| 30 | + ) |
| 31 | + assert resp.status_code == 401 |
| 32 | + |
| 33 | + resp = client.post( |
| 34 | + "/api/v2/diagnose", |
| 35 | + headers={"X-API-Key": "testkey"}, |
| 36 | + json={"data": {"Fever": 8}}, |
| 37 | + ) |
| 38 | + assert resp.status_code == 200 |
| 39 | + |
| 40 | + |
| 41 | +def test_rate_limiting_triggers_429(monkeypatch): |
| 42 | + client = TestClient(app) |
| 43 | + monkeypatch.setenv("MDM_API_KEY", "testkey") |
| 44 | + monkeypatch.setenv("MDM_RATE_LIMIT_RPM", "5") |
| 45 | + monkeypatch.setenv("MDM_RATE_LIMIT_WINDOW_S", "60") |
| 46 | + _RATE_LIMIT_STORE.clear() |
| 47 | + |
| 48 | + url = "/api/v2/diagnose" |
| 49 | + headers = {"X-API-Key": "testkey"} |
| 50 | + ok = 0 |
| 51 | + over = 0 |
| 52 | + for _ in range(8): |
| 53 | + r = client.post(url, headers=headers, json={"data": {"Fever": 8}}) |
| 54 | + if r.status_code == 200: |
| 55 | + ok += 1 |
| 56 | + elif r.status_code == 429: |
| 57 | + over += 1 |
| 58 | + assert over >= 1 |
| 59 | + |
0 commit comments