initial commit
This commit is contained in:
commit
88c14b627e
224 files changed
+17204
No files matched your search
@@ -0,0 +1,106 @@
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import yaml
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
from lincodex_ml.api.models import MLHealthResponse, MLReadinessResponse
|
||||
from lincodex_ml.main import app
|
||||
|
||||
CONTRACT_PATH = Path(__file__).resolve().parents[2] / "api" / "ml" / "openapi.bundle.yml"
|
||||
|
||||
|
||||
def _resolve_schema(document: dict[str, Any], schema: dict[str, Any]) -> dict[str, Any]:
|
||||
reference = schema.get("$ref")
|
||||
if reference is None:
|
||||
return schema
|
||||
component_name = reference.rsplit("/", maxsplit=1)[-1]
|
||||
return document["components"]["schemas"][component_name]
|
||||
|
||||
|
||||
def _status_values(document: dict[str, Any], response: dict[str, Any]) -> list[str]:
|
||||
content = response["content"]["application/json"]["schema"]
|
||||
response_schema = _resolve_schema(document, content)
|
||||
status_schema = response_schema["properties"]["status"]
|
||||
if "enum" in status_schema:
|
||||
return status_schema["enum"]
|
||||
if "const" in status_schema:
|
||||
return [status_schema["const"]]
|
||||
raise AssertionError("Status schema must declare enum values or a single constant.")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend() -> str:
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def test_health_and_readiness_match_shared_openapi_contract() -> None:
|
||||
contract = yaml.safe_load(CONTRACT_PATH.read_text(encoding="utf-8"))
|
||||
implementation = app.openapi()
|
||||
|
||||
assert set(implementation["paths"]) >= {"/healthz", "/readyz"}
|
||||
for path in ("/healthz", "/readyz"):
|
||||
expected_operation = contract["paths"][path]["get"]
|
||||
actual_operation = implementation["paths"][path]["get"]
|
||||
assert actual_operation["operationId"] == expected_operation["operationId"]
|
||||
|
||||
for response_code, expected_response in expected_operation["responses"].items():
|
||||
actual_response = actual_operation["responses"][response_code]
|
||||
assert _status_values(contract, expected_response) == _status_values(
|
||||
implementation, actual_response
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_unready_probe_returns_the_contractual_503_response() -> None:
|
||||
contract = yaml.safe_load(CONTRACT_PATH.read_text(encoding="utf-8"))
|
||||
readiness = contract["paths"]["/readyz"]["get"]["responses"]
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app=app), base_url="http://test"
|
||||
) as client:
|
||||
response = await client.get("/readyz")
|
||||
|
||||
assert str(response.status_code) in readiness
|
||||
assert response.status_code == 503
|
||||
assert response.json()["status"] in _status_values(contract, readiness["503"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("model", "valid_status"),
|
||||
[(MLHealthResponse, "ok"), (MLReadinessResponse, "ready"), (MLReadinessResponse, "not_ready")],
|
||||
)
|
||||
def test_generated_models_accept_contract_statuses(
|
||||
model: type[BaseModel], valid_status: str
|
||||
) -> None:
|
||||
assert model.model_validate({"status": valid_status}).model_dump() == {"status": valid_status}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", [MLHealthResponse, MLReadinessResponse])
|
||||
@pytest.mark.parametrize(
|
||||
("payload", "error_type"),
|
||||
[
|
||||
({}, "missing"),
|
||||
({"status": "unknown"}, "literal_error"),
|
||||
({"status": 1}, "literal_error"),
|
||||
],
|
||||
)
|
||||
def test_generated_models_reject_invalid_statuses(
|
||||
model: type[BaseModel], payload: dict[str, object], error_type: str
|
||||
) -> None:
|
||||
with pytest.raises(ValidationError) as error:
|
||||
model.model_validate(payload)
|
||||
|
||||
assert error.value.errors()[0]["type"] == error_type
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("model", "valid_status"), [(MLHealthResponse, "ok"), (MLReadinessResponse, "not_ready")]
|
||||
)
|
||||
def test_generated_models_forbid_extra_fields(model: type[BaseModel], valid_status: str) -> None:
|
||||
with pytest.raises(ValidationError) as error:
|
||||
model.model_validate({"status": valid_status, "details": "unexpected"})
|
||||
|
||||
assert error.value.errors()[0]["type"] == "extra_forbidden"
|
||||
Reference in new issue
Block a user