Download projects/core-api/tests/test_api.py from KineJIng/kinejing-open-source: direct link, hf CLI and curl.
- Browser
- Download file 7.03 kB
-
https://huggingface.co/datasets/KineJIng/kinejing-open-source/resolve/main/projects/core-api/tests/test_api.py
- Command line
-
hf download hf://datasets/KineJIng/kinejing-open-source/projects/core-api/tests/test_api.py
-
curl -L -o test_api.py https://huggingface.co/datasets/KineJIng/kinejing-open-source/resolve/main/projects/core-api/tests/test_api.py
7.03 kB
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| import threading | |
| import numpy as np | |
| import pytest | |
| from fastapi.testclient import TestClient | |
| from kinejing_core.app import create_app | |
| from kinejing_core.engine import (ACTION_SCHEMA, ENCODER_SHA256, FEATURE_SPACE, | |
| MODEL_ID, DynamicsEngine) | |
| ASSET = Path(__file__).resolve().parents[1] / "assets/kinejing-dynamics-v01.npz" | |
| KEY = "test-only-placeholder-key-never-deploy-0123456789" | |
| AUTH = {"Authorization": "Bearer " + KEY} | |
| def payload(): | |
| return {"model": MODEL_ID, "feature_space": FEATURE_SPACE, | |
| "encoder_weights_sha256": ENCODER_SHA256, "action_schema": ACTION_SCHEMA, | |
| "initial_features": [[0.0] * 768 for _ in range(3)], | |
| "actions": [[0.0] * 14 for _ in range(9)]} | |
| def test_real_asset_http_and_no_auth_metadata(): | |
| with TestClient(create_app(ASSET, KEY)) as client: | |
| assert client.get("/health").json()["ready"] is True | |
| assert client.get("/v1/models").json()["data"][0]["commercial_ready"] is False | |
| assert client.post("/v1/predict", json=payload()).status_code == 401 | |
| result = client.post("/v1/predict", json=payload(), headers=AUTH) | |
| assert result.status_code == 200 | |
| body = result.json() | |
| assert body["shape"] == [9, 3, 768] | |
| assert np.asarray(body["predicted_features"]).shape == (9, 3, 768) | |
| assert np.isfinite(body["predicted_features"]).all() | |
| assert body["billing"] == "none" and body["commercial_ready"] is False | |
| assert body["predicted_features"][0] == payload()["initial_features"] | |
| assert "C:\\" not in result.text | |
| def test_reject_invalid_contract(change): | |
| with TestClient(create_app(ASSET, KEY)) as client: | |
| body = payload() | |
| change(body) | |
| assert client.post("/v1/predict", json=body, headers=AUTH).status_code == 422 | |
| def test_auth_precedes_body_limit_and_finite_json(): | |
| with TestClient(create_app(ASSET, KEY)) as client: | |
| assert client.post("/v1/predict", content=b"x" * 150000).status_code == 401 | |
| assert client.post("/v1/predict", content=b"x" * 150000, headers=AUTH).status_code == 413 | |
| raw = __import__("json").dumps(payload()).replace("0.0", "1e400", 1) | |
| assert client.post("/v1/predict", content=raw, headers={**AUTH, "Content-Type": "application/json"}).status_code == 422 | |
| def test_rate_limit_and_missing_model(): | |
| with TestClient(create_app(ASSET, KEY, rpm=1)) as client: | |
| assert client.post("/v1/predict", json=payload(), headers=AUTH).status_code == 200 | |
| reply = client.post("/v1/predict", json=payload(), headers=AUTH) | |
| assert reply.status_code == 429 and reply.headers["retry-after"] == "60" | |
| with pytest.raises(FileNotFoundError): | |
| with TestClient(create_app(ASSET.with_name("absent.npz"), KEY)): | |
| pass | |
| with pytest.raises(ValueError): | |
| create_app(ASSET, "short") | |
| def test_individual_key_revocation_and_rate_isolation(tmp_path): | |
| import hashlib | |
| import json | |
| registry = tmp_path / "key-hashes.json" | |
| second = "second-test-only-key-never-deploy-0123456789" | |
| first_digest = hashlib.sha256(KEY.encode()).hexdigest() | |
| second_digest = hashlib.sha256(second.encode()).hexdigest() | |
| registry.write_text(json.dumps({first_digest: "first", second_digest: "second"})) | |
| with TestClient(create_app(ASSET, key_hash_file=registry, rpm=1)) as client: | |
| assert client.post("/v1/predict", json=payload(), headers=AUTH).status_code == 200 | |
| second_auth = {"Authorization": "Bearer " + second} | |
| assert client.post("/v1/predict", json=payload(), headers=second_auth).status_code == 200 | |
| registry.write_text(json.dumps({second_digest: "second"})) | |
| assert client.post("/v1/predict", json=payload(), headers=AUTH).status_code == 401 | |
| registry.write_text("{}") | |
| assert client.post("/v1/predict", json=payload(), headers=second_auth).status_code == 401 | |
| registry.write_text("malformed") | |
| assert client.post("/v1/predict", json=payload(), headers=second_auth).status_code == 503 | |
| def test_corrupt_model_never_falls_back(tmp_path): | |
| broken = tmp_path / "bad.npz" | |
| broken.write_bytes(b"not a trained model") | |
| with pytest.raises(ValueError, match="hash"): | |
| DynamicsEngine(broken) | |
| def test_concurrent_rejection_and_recovery(): | |
| entered = threading.Barrier(3) | |
| release = threading.Event() | |
| class SlowEngine: | |
| def predict(self, initial, actions, times=None): | |
| entered.wait(timeout=5) | |
| assert release.wait(5) | |
| return np.zeros((9, 3, 768), dtype=np.float32) | |
| with TestClient(create_app(ASSET, KEY, engine_factory=SlowEngine)) as client: | |
| with ThreadPoolExecutor(2) as workers: | |
| pending = [workers.submit(client.post, "/v1/predict", json=payload(), headers=AUTH) for _ in range(2)] | |
| entered.wait(timeout=5) | |
| rejected = client.post("/v1/predict", json=payload(), headers=AUTH) | |
| assert rejected.status_code == 503 and rejected.headers["retry-after"] == "1" | |
| release.set() | |
| assert all(task.result().status_code == 200 for task in pending) | |
| client.app.state.engine = DynamicsEngine(ASSET) | |
| assert client.post("/v1/predict", json=payload(), headers=AUTH).status_code == 200 | |
| def test_trained_action_sensitivity_and_causal_prefix(): | |
| engine = DynamicsEngine(ASSET) | |
| rng = np.random.default_rng(20261020) | |
| initial = rng.normal(size=(3, 768)).astype(np.float32) | |
| actions = rng.normal(size=(9, 14)).astype(np.float32) | |
| before = engine.predict(initial, actions) | |
| changed = actions.copy() | |
| changed[5:] += 2 | |
| after = engine.predict(initial, changed) | |
| np.testing.assert_array_equal(before[:5], after[:5]) | |
| assert np.max(np.abs(before[5:] - after[5:])) > 0.0001 | |
| def test_original_rounded_sample_times_and_openapi_security(): | |
| with TestClient(create_app(ASSET, KEY)) as client: | |
| body = payload() | |
| body["time_grid"] = (np.round(np.linspace(0, 30, 9)) / 30).tolist() | |
| response = client.post("/v1/predict", json=body, headers=AUTH) | |
| assert response.status_code == 200 | |
| assert response.json()["time_grid"] == body["time_grid"] | |
| schema = client.get("/openapi.json").json() | |
| assert schema["paths"]["/v1/predict"]["post"]["security"] == [{"HTTPBearer": []}] | |