Download tests/test_usage.py from SQuADDS/squadds-ml-inference-api: direct link, hf CLI and curl.
- Browser
- Download file 2.44 kB
-
https://huggingface.co/spaces/SQuADDS/squadds-ml-inference-api/resolve/main/tests/test_usage.py
- Command line
-
hf download hf://spaces/SQuADDS/squadds-ml-inference-api/tests/test_usage.py
-
curl -L -o test_usage.py https://huggingface.co/spaces/SQuADDS/squadds-ml-inference-api/resolve/main/tests/test_usage.py
2.44 kB
| """Aggregate daily usage counts of the predict routes (squadds_ml_api.usage): no network (mocked CommitScheduler), counts only, | |
| responses unchanged (the legacy oracle in test_legacy.py stays the check of the responses).""" | |
| import json | |
| import threading | |
| from pathlib import Path | |
| from squadds_ml_api.usage import Usage | |
| OLIVIA = "transmon_cross_hamiltonian_inverse" | |
| S = {"qubit_frequency_GHz": 4.85, "anharmonicity_MHz": -205.0} | |
| class _Scheduler: | |
| def __init__(self, folder): | |
| self.folder_path, self.lock = Path(folder), threading.Lock() | |
| self.folder_path.mkdir(parents=True, exist_ok=True) | |
| def test_counts_only(client, tmp_path): | |
| old = client.app.state.usage | |
| client.app.state.usage = Usage("api", scheduler=_Scheduler(tmp_path / "api")) | |
| try: | |
| h = {"x-forwarded-for": "198.51.100.7"} | |
| legacy = client.post("/predict", json={"model_id": OLIVIA, "inputs": {**S, "anharmonicity_MHz": -211.5}}, headers=h) | |
| again = client.post("/predict", json={"model_id": OLIVIA, "inputs": {**S, "anharmonicity_MHz": -211.5}}, headers=h) | |
| assert legacy.status_code == again.status_code == 200 and legacy.json() == again.json() | |
| assert set(legacy.json()) == {"model_id", "display_name", "predictions", "metadata"} | |
| assert client.post("/predict", json={"model_id": "secret-name-xyz", "inputs": S}, headers=h).status_code == 400 | |
| assert client.post(f"/v1/models/{OLIVIA}/predict", json={"inputs": {**S, "anharmonicity_MHz": -212.5}}).status_code == 200 | |
| assert client.post(f"/v1/models/{OLIVIA}/predict", json={"inputs": {"qubit_frequency_GHz": "x"}}).status_code in (400, 422) | |
| assert client.post("/v1/models/nope/predict", json={"inputs": {}}).status_code == 404 | |
| client.get("/v1/models") | |
| files = list((tmp_path / "api").glob("*.json")) | |
| assert len(files) == 1 | |
| text = files[0].read_text() | |
| row = json.loads(text) | |
| assert row["calls_by_route"] == {"legacy": 3, "v1": 3} | |
| assert row["calls_by_model"] == {OLIVIA: 4, "other": 2} | |
| assert row["refusals"] == {"invalid_input": 2, "unknown_model": 1} and row["cache_hits"] == 1 | |
| assert row["latency_s"]["n"] == 3 and row["distinct_users"] == 2 | |
| for s in ("198.51.100.7", "testclient", "secret-name-xyz", "nope"): | |
| assert s not in text, s | |
| print("example row:", json.dumps(row)) | |
| finally: | |
| client.app.state.usage = old | |