openapi
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
"""Тесты OpenAPI-спецификации: файл валиден и синхронен с сервисом.
|
||||
|
||||
Спецификация — рукописная копия контракта docs/05 (автогенерация FastAPI не
|
||||
видит multipart-части, разбираемые вручную), поэтому фиксируется тестами.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
SPEC_PATH = Path(__file__).resolve().parents[2] / "openapi.yaml"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def spec() -> dict:
|
||||
return yaml.safe_load(SPEC_PATH.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
class TestSpecFile:
|
||||
def test_version_and_paths(self, spec):
|
||||
assert spec["openapi"].startswith("3.")
|
||||
paths = spec["paths"]
|
||||
for path in ("/api/v1/features", "/api/v1/verify", "/api/v1/profiles", "/health", "/ready"):
|
||||
assert path in paths, path
|
||||
|
||||
def test_security_scheme(self, spec):
|
||||
scheme = spec["components"]["securitySchemes"]["ApiKeyAuth"]
|
||||
assert scheme["type"] == "apiKey"
|
||||
assert scheme["in"] == "header"
|
||||
assert scheme["name"] == "X-API-Key"
|
||||
assert spec["security"] == [{"ApiKeyAuth": []}]
|
||||
|
||||
def test_health_and_ready_without_auth(self, spec):
|
||||
# диагностика переопределяет глобальную безопасность
|
||||
assert spec["paths"]["/health"]["get"]["security"] == []
|
||||
assert spec["paths"]["/ready"]["get"]["security"] == []
|
||||
|
||||
def test_verify_reference_is_repeated_part(self, spec):
|
||||
schema = spec["paths"]["/api/v1/verify"]["post"]["requestBody"]["content"][
|
||||
"multipart/form-data"
|
||||
]["schema"]
|
||||
reference = schema["properties"]["reference"]
|
||||
assert reference["type"] == "array"
|
||||
assert reference["minItems"] == 1
|
||||
assert reference["maxItems"] == 32 # MAX_REFERENCES_PER_REQUEST по умолчанию
|
||||
|
||||
def test_features_response_headers(self, spec):
|
||||
headers = spec["paths"]["/api/v1/features"]["post"]["responses"]["200"]["headers"]
|
||||
for name in (
|
||||
"X-Feature-Format-Version",
|
||||
"X-Algo-Id",
|
||||
"X-Keypoints-Count",
|
||||
"X-Image-Width",
|
||||
"X-Image-Height",
|
||||
):
|
||||
assert name in headers, name
|
||||
|
||||
def test_error_schema_codes(self, spec):
|
||||
codes = set(spec["components"]["schemas"]["Error"]["properties"]["code"]["enum"])
|
||||
# все коды из таблицы docs/05 §5.3
|
||||
assert codes == {
|
||||
"IMAGE_DECODE_FAILED", "FEATURE_BLOB_INVALID", "FEATURE_FORMAT_UNSUPPORTED",
|
||||
"TOO_MANY_REFERENCES", "UNKNOWN_PROFILE", "IMAGE_TOO_SMALL",
|
||||
"UNAUTHORIZED", "FORBIDDEN", "PAYLOAD_TOO_LARGE", "UNSUPPORTED_MEDIA_TYPE",
|
||||
"VALIDATION_ERROR", "INVALID_SETTINGS", "INTERNAL",
|
||||
}
|
||||
|
||||
def test_settings_match_validation_ranges(self, spec):
|
||||
comparison = spec["components"]["schemas"]["ComparisonSettings"]["properties"]
|
||||
assert comparison["lowe_ratio"]["minimum"] == 0.5
|
||||
assert comparison["lowe_ratio"]["maximum"] == 0.95
|
||||
extraction = spec["components"]["schemas"]["ExtractionSettings"]["properties"]
|
||||
assert extraction["max_image_size"] == {
|
||||
"type": "integer", "minimum": 320, "maximum": 8192,
|
||||
"description": extraction["max_image_size"]["description"],
|
||||
}
|
||||
|
||||
|
||||
class TestSpecServed:
|
||||
def test_openapi_json_serves_file_spec(self, client: TestClient):
|
||||
"""Живой сервис отдаёт /openapi.json из openapi.yaml, а не автогенерацию."""
|
||||
response = client.get("/openapi.json")
|
||||
assert response.status_code == 200
|
||||
served = response.json()
|
||||
assert served["paths"].keys() == yaml.safe_load(SPEC_PATH.read_text())["paths"].keys()
|
||||
assert "/api/v1/verify" in served["paths"]
|
||||
assert served["components"]["securitySchemes"]["ApiKeyAuth"]["name"] == "X-API-Key"
|
||||
|
||||
def test_docs_ui_available(self, client: TestClient):
|
||||
response = client.get("/docs")
|
||||
assert response.status_code == 200
|
||||
assert "swagger" in response.text.lower()
|
||||
Reference in New Issue
Block a user