Files
open_cv/tests/api/test_openapi.py
T
2026-10-06 17:58:35 +03:00

124 lines
5.5 KiB
Python

"""Тесты 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/calibrate",
"/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_no_hardcoded_servers(self, spec):
"""Без блока servers: Swagger UI «Try it out» и клиенты работают
относительно хоста, с которого получена спецификация (любой порт/деплой)."""
assert "servers" not in spec
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", "TOO_MANY_CALIBRATION_IMAGES", "CALIBRATION_DATASET_INVALID",
"UNKNOWN_PROFILE", "IMAGE_TOO_SMALL",
"UNAUTHORIZED", "FORBIDDEN", "PAYLOAD_TOO_LARGE", "UNSUPPORTED_MEDIA_TYPE",
"VALIDATION_ERROR", "INVALID_SETTINGS", "INTERNAL",
}
def test_calibrate_packs_are_repeated_parts(self, spec):
schema = spec["paths"]["/api/v1/calibrate"]["post"]["requestBody"]["content"][
"multipart/form-data"
]["schema"]
assert schema["required"] == ["positive", "negative"]
positive = schema["properties"]["positive"]
assert positive["type"] == "array"
assert positive["minItems"] == 2
assert positive["maxItems"] == 8 # CALIBRATION_MAX_IMAGES_PER_PACK по умолчанию
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):
"""Живой сервис отдаёт /api/openapi.json из openapi.yaml, а не автогенерацию."""
response = client.get("/api/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("/api/docs")
assert response.status_code == 200
assert "swagger" in response.text.lower()
def test_docs_moved_from_root(self, client: TestClient):
"""Swagger живёт под /api/docs; корневой /docs больше не отдаётся."""
assert client.get("/docs").status_code == 404
def test_redoc_available(self, client: TestClient):
response = client.get("/api/redoc")
assert response.status_code == 200
assert "redoc" in response.text.lower()