This commit is contained in:
2026-09-29 00:17:58 +03:00
parent 2f8d4098c5
commit da32158789
38 changed files with 3106 additions and 10 deletions
View File
+55
View File
@@ -0,0 +1,55 @@
"""Помощники интеграционных тестов: вызовы API и модификация блобов."""
from __future__ import annotations
import io
import json
import numpy as np
API_KEY_HEADERS = {"X-API-Key": "test-key"}
def post_features(client, image: bytes, settings: dict | None = None):
data = {"settings": json.dumps(settings)} if settings else None
return client.post(
"/api/v1/features",
headers=API_KEY_HEADERS,
files={"image": ("image.jpg", image, "image/jpeg")},
data=data,
)
def post_verify(client, probe: bytes, references: list[tuple[str, bytes, str]], settings: dict | None = None):
"""references — список (имя, байты, content_type)."""
files = [("probe", ("probe.jpg", probe, "image/jpeg"))]
files += [("reference", (name, body, ctype)) for name, body, ctype in references]
data = {"settings": json.dumps(settings)} if settings else None
return client.post(
"/api/v1/verify",
headers=API_KEY_HEADERS,
files=files,
data=data,
)
def make_blob_ref(blob: bytes) -> tuple[str, bytes, str]:
return ("reference.npz", blob, "application/octet-stream")
def make_image_ref(image: bytes) -> tuple[str, bytes, str]:
return ("reference.jpg", image, "image/jpeg")
def rewrite_blob_meta(blob: bytes, **overrides) -> bytes:
"""Пересобирает блоб с изменёнными полями meta (для IT-05)."""
npz = np.load(io.BytesIO(blob), allow_pickle=False)
meta = json.loads(str(npz["meta"].item()))
meta.update(overrides)
buffer = io.BytesIO()
np.savez_compressed(
buffer,
descriptors=npz["descriptors"],
keypoints=npz["keypoints"],
meta=np.array(json.dumps(meta)),
)
return buffer.getvalue()
+86
View File
@@ -0,0 +1,86 @@
"""Интеграционные тесты: аутентификация, единый формат ошибок, профили,
health/ready — docs/08 §8.3, IT-08, IT-09, IT-17."""
from __future__ import annotations
import numpy as np
from tests.api.helpers import make_blob_ref, post_features, post_verify
class TestAuth:
def test_it08_missing_key_401(self, client, facade_a):
response = client.post(
"/api/v1/features",
files={"image": ("image.jpg", facade_a, "image/jpeg")},
)
assert response.status_code == 401
assert response.json()["error"]["code"] == "UNAUTHORIZED"
def test_it08_wrong_key_403(self, client, facade_a):
response = client.post(
"/api/v1/features",
headers={"X-API-Key": "wrong-key"},
files={"image": ("image.jpg", facade_a, "image/jpeg")},
)
assert response.status_code == 403
assert response.json()["error"]["code"] == "FORBIDDEN"
def test_it08_health_without_key(self, client):
"""IT-08: /health без ключа — 200 (FR-004)."""
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
def test_ready_without_key(self, client):
response = client.get("/ready")
assert response.status_code == 200
assert response.json() == {"status": "ready"}
def test_profiles_require_key(self, client):
assert client.get("/api/v1/profiles").status_code == 401
assert client.get("/api/v1/profiles", headers={"X-API-Key": "bad"}).status_code == 403
class TestErrorFormat:
def test_it09_unified_error_shape(self, client, facade_a, blob_a):
"""IT-09: все 4xx соответствуют единому формату ошибки."""
cases = [
client.post("/api/v1/verify", headers={"X-API-Key": "nope"}, files=[]),
post_features(client, b"not an image"),
post_verify(client, facade_a, []),
post_verify(client, facade_a, [make_blob_ref(blob_a[:100])]),
]
for response in cases:
assert 400 <= response.status_code < 500, response.status_code
body = response.json()
error = body["error"]
assert set(error) >= {"code", "message", "details", "trace_id"}
assert isinstance(error["code"], str) and error["code"]
assert len(error["trace_id"]) == 12
class TestProfiles:
def test_it17_catalog(self, client):
"""IT-17: каталог содержит facade, monument, repetitive (FR-009)."""
response = client.get("/api/v1/profiles", headers={"X-API-Key": "test-key"})
assert response.status_code == 200
body = response.json()
names = {p["name"] for p in body["profiles"]}
assert {"facade", "monument", "repetitive"} <= names
monument = next(p for p in body["profiles"] if p["name"] == "monument")
assert monument["comparison"]["geometry_model"] == "fundamental"
assert monument["extraction"]["clahe_clip_limit"] == 3.0
repetitive = next(p for p in body["profiles"] if p["name"] == "repetitive")
assert repetitive["comparison"]["lowe_ratio"] == 0.70
assert repetitive["comparison"]["match_inliers_min"] == 60
# базовые значения для наследования незаполненных полей
assert body["defaults"]["comparison"]["inliers_match"] == 50
def test_facade_profile_is_default(self, client):
response = client.get("/api/v1/profiles", headers={"X-API-Key": "test-key"})
facade = next(p for p in response.json()["profiles"] if p["name"] == "facade")
assert facade["extraction"] == {}
assert facade["comparison"] == {}
+131
View File
@@ -0,0 +1,131 @@
"""Интеграционные тесты POST /api/v1/features — docs/08 §8.3, IT-01, IT-07,
IT-10, IT-14, IT-15."""
from __future__ import annotations
import io
import json
import numpy as np
import pytest
from tests.api.helpers import post_features
class TestFeaturesEndpoint:
def test_it01_valid_photo(self, client, facade_a):
"""IT-01: 200, контрактные заголовки, тело читается numpy.load."""
response = post_features(client, facade_a)
assert response.status_code == 200
assert response.headers["content-type"] == "application/octet-stream"
assert response.headers["x-feature-format-version"] == "1"
assert response.headers["x-algo-id"].startswith("sift-v1:")
kp_count = int(response.headers["x-keypoints-count"])
assert kp_count > 0
assert int(response.headers["x-image-width"]) == 1400
assert int(response.headers["x-image-height"]) == 900
npz = np.load(io.BytesIO(response.content), allow_pickle=False)
assert npz["descriptors"].shape == (kp_count, 128)
meta = json.loads(str(npz["meta"].item()))
assert meta["format_version"] == 1
assert meta["keypoints_count"] == kp_count
def test_it10_idempotency(self, client, facade_a):
"""IT-10: два вызова с тем же файлом — эквивалентные массивы (FR-007)."""
first = post_features(client, facade_a)
second = post_features(client, facade_a)
assert first.status_code == second.status_code == 200
n1 = np.load(io.BytesIO(first.content), allow_pickle=False)
n2 = np.load(io.BytesIO(second.content), allow_pickle=False)
assert np.array_equal(n1["descriptors"], n2["descriptors"])
assert np.array_equal(n1["keypoints"], n2["keypoints"])
m1 = json.loads(str(n1["meta"].item()))
m2 = json.loads(str(n2["meta"].item()))
m1.pop("created_at"), m2.pop("created_at") # различие метки времени допустимо
assert m1 == m2
def test_it14_settings_change_algo_id(self, client, facade_a):
"""IT-14: профиль monument + переопределение меняют X-Algo-Id;
meta.settings записываются в блоб."""
plain = post_features(client, facade_a)
tuned = post_features(
client, facade_a,
settings={"profile": "monument", "extraction": {"clahe_clip_limit": 4.0}},
)
assert plain.status_code == tuned.status_code == 200
assert tuned.headers["x-algo-id"] != plain.headers["x-algo-id"]
npz = np.load(io.BytesIO(tuned.content), allow_pickle=False)
meta = json.loads(str(npz["meta"].item()))
assert meta["settings"] == {
"profile": "monument",
"extraction": {"clahe_clip_limit": 4.0},
}
def test_it15_unknown_profile(self, client, facade_a):
response = post_features(client, facade_a, settings={"profile": "castle"})
assert response.status_code == 400
assert response.json()["error"]["code"] == "UNKNOWN_PROFILE"
def test_it15_unknown_settings_key(self, client, facade_a):
response = post_features(client, facade_a, settings={"comparison": {"threshold": 5}})
assert response.status_code == 422
assert response.json()["error"]["code"] == "INVALID_SETTINGS"
def test_it15_value_out_of_range(self, client, facade_a):
response = post_features(client, facade_a, settings={"comparison": {"lowe_ratio": 2.0}})
assert response.status_code == 422
assert response.json()["error"]["code"] == "INVALID_SETTINGS"
def test_it07_invalid_images(self, client, tiny_image):
"""IT-07: пустой файл, текст .jpg, 300×200 — 4xx, процесс жив."""
empty = post_features(client, b"")
assert empty.status_code == 400
assert empty.json()["error"]["code"] == "IMAGE_DECODE_FAILED"
text = post_features(client, b"this is definitely not an image")
assert text.status_code == 400
assert text.json()["error"]["code"] == "IMAGE_DECODE_FAILED"
small = post_features(client, tiny_image)
assert small.status_code == 400
assert small.json()["error"]["code"] == "IMAGE_TOO_SMALL"
# процесс жив после некорректного ввода (NFR-004)
assert post_features(client, tiny_image).status_code == 400
assert client.get("/health").status_code == 200
def test_it07_oversized_image_413(self, client):
"""IT-07: изображение больше MAX_IMAGE_MB — 413 (CL проверяется рано)."""
big = b"\xff\xd8\xff\xe0" + b"\x00" * (2 * 1024 * 1024) # > 1 МБ тестового лимита
response = post_features(client, big)
assert response.status_code == 413
assert response.json()["error"]["code"] == "PAYLOAD_TOO_LARGE"
def test_415_unsupported_media_type(self, client):
"""415: часть image заявлена как image/gif (05 §5.3)."""
response = client.post(
"/api/v1/features",
headers={"X-API-Key": "test-key"},
files={"image": ("image.gif", b"GIF89a....", "image/gif")},
)
assert response.status_code == 415
assert response.json()["error"]["code"] == "UNSUPPORTED_MEDIA_TYPE"
def test_missing_image_part(self, client, facade_a):
response = client.post(
"/api/v1/features",
headers={"X-API-Key": "test-key"},
files={"photo": ("image.jpg", facade_a, "image/jpeg")},
)
assert response.status_code == 422
assert response.json()["error"]["code"] == "VALIDATION_ERROR"
assert response.json()["error"]["details"]["part"] == "image"
def test_exif_orientation_headers(self, client, exif_image):
"""EXIF-ориентация применяется сервером: 1400×900 с orientation 6 → 900×1400."""
response = post_features(client, exif_image)
assert response.status_code == 200
assert int(response.headers["x-image-width"]) == 900
assert int(response.headers["x-image-height"]) == 1400
+145
View File
@@ -0,0 +1,145 @@
"""Интеграционные тесты POST /api/v1/verify — docs/08 §8.3, IT-02..IT-07,
IT-11..IT-13, IT-16."""
from __future__ import annotations
import pytest
from tests.api.helpers import (
make_blob_ref,
make_image_ref,
post_features,
post_verify,
rewrite_blob_meta,
)
class TestVerifyEndpoint:
def test_it02_roundtrip_same_photo(self, client, facade_a, blob_a):
"""IT-02: /features → /verify с той же пробой — match."""
response = post_verify(client, facade_a, [make_blob_ref(blob_a)])
assert response.status_code == 200
body = response.json()
assert body["verdict"] == "match"
assert body["is_match"] is True
assert body["confidence"] >= 0.6
assert body["details"]["best_reference_index"] == 0
assert body["details"]["references_compared"] == 1
assert len(body["probe_sha256"]) == 64
assert body["processing_ms"] >= 0
thresholds = body["details"]["thresholds"]
assert thresholds["inliers_match"] == 50
assert thresholds["inlier_ratio_match"] == pytest.approx(0.30)
assert thresholds["coverage_min"] == pytest.approx(0.05)
assert thresholds["inliers_uncertain_min"] == 20
def test_it03_probe_of_other_building(self, client, facade_b, blob_a):
"""IT-03: проба другого здания — no_match/uncertain, не match."""
response = post_verify(client, facade_b, [make_blob_ref(blob_a)])
assert response.status_code == 200
body = response.json()
assert body["verdict"] in ("no_match", "uncertain")
assert body["is_match"] is False
def test_it04_no_references(self, client, facade_a):
"""IT-04: 0 частей reference — 422 VALIDATION_ERROR."""
response = post_verify(client, facade_a, [])
assert response.status_code == 422
body = response.json()
assert body["error"]["code"] == "VALIDATION_ERROR"
assert body["error"]["details"]["part"] == "reference"
def test_it04_too_many_references(self, client, facade_a):
"""IT-04: 33 части reference — 400 TOO_MANY_REFERENCES.
Части-пустышки: лимит числа эталонов проверяется до разбора контента,
но после ранней CL-проверки тела.
"""
refs = [("reference.bin", b"garbage", "application/octet-stream")] * 33
response = post_verify(client, facade_a, refs)
assert response.status_code == 400
assert response.json()["error"]["code"] == "TOO_MANY_REFERENCES"
def test_it05_unsupported_format_version(self, client, facade_a, blob_a):
"""IT-05: блоб с format_version=99 — 400 FEATURE_FORMAT_UNSUPPORTED,
в details — индекс эталона."""
foreign = rewrite_blob_meta(blob_a, format_version=99)
response = post_verify(client, facade_a, [make_blob_ref(foreign)])
assert response.status_code == 400
body = response.json()
assert body["error"]["code"] == "FEATURE_FORMAT_UNSUPPORTED"
assert body["error"]["details"]["reference_index"] == 0
assert body["error"]["details"]["received"] == 99
def test_it06_corrupted_blob(self, client, facade_a, blob_a):
"""IT-06: повреждённый блоб (обрезаны байты) — 400 FEATURE_BLOB_INVALID."""
response = post_verify(client, facade_a, [make_blob_ref(blob_a[: len(blob_a) // 2])])
assert response.status_code == 400
assert response.json()["error"]["code"] == "FEATURE_BLOB_INVALID"
def test_unrecognized_reference_content(self, client, facade_a):
response = post_verify(
client, facade_a, [("reference.bin", b"\x00\x01\x02garbage", "application/octet-stream")]
)
assert response.status_code == 400
assert response.json()["error"]["code"] == "IMAGE_DECODE_FAILED"
def test_it11_determinism(self, client, facade_a, blob_a):
"""IT-11: два одинаковых /verify — идентичные результаты (NFR-009)."""
first = post_verify(client, facade_a, [make_blob_ref(blob_a)]).json()
second = post_verify(client, facade_a, [make_blob_ref(blob_a)]).json()
assert first["verdict"] == second["verdict"]
assert first["confidence"] == second["confidence"]
assert first["details"]["metrics"] == second["details"]["metrics"]
def test_it12_debug_mode_image_reference(self, client, facade_a):
"""IT-12: эталон-изображение без /features — 200, match (Q-4)."""
response = post_verify(client, facade_a, [make_image_ref(facade_a)])
assert response.status_code == 200
assert response.json()["verdict"] == "match"
def test_it13_mixed_references(self, client, facade_a, facade_b, blob_a):
"""IT-13: смешанные эталоны; best_reference_index сквозной по порядку."""
refs = [make_image_ref(facade_b), make_blob_ref(blob_a), make_image_ref(facade_a)]
response = post_verify(client, facade_a, refs)
assert response.status_code == 200
body = response.json()
assert body["details"]["references_compared"] == 3
assert body["verdict"] == "match"
assert body["details"]["best_reference_index"] == 1
def test_it16_request_override_beats_blob(self, client, facade_a):
"""IT-16: переопределение порога в /verify побеждает значение из блоба."""
blob = post_features(
client, facade_a, settings={"comparison": {"match_inliers_min": 500}}
).content
no_override = post_verify(client, facade_a, [make_blob_ref(blob)]).json()
assert no_override["details"]["thresholds"]["inliers_match"] == 500
overridden = post_verify(
client, facade_a, [make_blob_ref(blob)],
settings={"comparison": {"match_inliers_min": 30}},
).json()
assert overridden["details"]["thresholds"]["inliers_match"] == 30
def test_it16_profile_from_blob(self, client, facade_a):
"""Профиль, сохранённый в блобе, действует при /verify без настроек."""
blob = post_features(client, facade_a, settings={"profile": "monument"}).content
body = post_verify(client, facade_a, [make_blob_ref(blob)]).json()
assert body["details"]["thresholds"]["geometry_model"] == "fundamental"
def test_verify_413_body_limit(self, client, facade_a, facade_b):
"""Суммарный запрос сверх VERIFY_MAX_BODY_MB (8 МБ в тестах) — 413."""
heavy = [make_image_ref(facade_b)] * 32 # 32 × ~0.3 МБ + проба > 8 МБ
response = post_verify(client, facade_a, heavy)
assert response.status_code == 413
assert response.json()["error"]["code"] == "PAYLOAD_TOO_LARGE"
def test_missing_probe_part(self, client, facade_a, blob_a):
response = client.post(
"/api/v1/verify",
headers={"X-API-Key": "test-key"},
files=[("reference", ("reference.npz", blob_a, "application/octet-stream"))],
)
assert response.status_code == 422
assert response.json()["error"]["details"]["part"] == "probe"