init app
This commit is contained in:
@@ -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()
|
||||
@@ -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"] == {}
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Общие фикстуры: конфиг, приложение, клиент, синтетические изображения.
|
||||
|
||||
Лимиты входа в тестовом конфиге меньше боевых (1 МБ на изображение),
|
||||
чтобы сценарии 413/IT-07 не генерировали десятки мегабайт.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.config import Config
|
||||
from app.main import create_app
|
||||
from tests import synth
|
||||
|
||||
TEST_API_KEY = "test-key"
|
||||
|
||||
|
||||
def make_config(**overrides) -> Config:
|
||||
values = dict(
|
||||
api_key=TEST_API_KEY,
|
||||
host="127.0.0.1",
|
||||
port=8000,
|
||||
workers=1,
|
||||
log_level="WARNING",
|
||||
max_image_bytes=1 * 1024 * 1024,
|
||||
verify_max_body_bytes=8 * 1024 * 1024,
|
||||
max_references=32,
|
||||
sift_max_image_size=1600,
|
||||
sift_max_keypoints=16384,
|
||||
lowe_ratio=0.75,
|
||||
ransac_reproj_threshold=5.0,
|
||||
match_inliers_min=50,
|
||||
match_inliers_ratio_min=0.30,
|
||||
match_coverage_min=0.05,
|
||||
uncertain_inliers_min=20,
|
||||
)
|
||||
values.update(overrides)
|
||||
return Config(**values)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def config() -> Config:
|
||||
return make_config()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def app(config: Config):
|
||||
return create_app(config)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def client(app) -> TestClient:
|
||||
with TestClient(app, raise_server_exceptions=False) as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def blob_a(client: TestClient, facade_a: bytes) -> bytes:
|
||||
"""Блоб признаков базового «фасада», вычисленный через боевой эндпоинт."""
|
||||
from tests.api.helpers import post_features
|
||||
|
||||
response = post_features(client, facade_a)
|
||||
assert response.status_code == 200
|
||||
return response.content
|
||||
|
||||
|
||||
# ------------------------------------------------------------ изображения
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def facade_a() -> bytes:
|
||||
return synth.encode_jpg(synth.make_facade(seed=7))
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def facade_a_warp() -> bytes:
|
||||
return synth.encode_jpg(synth.warp_perspective(synth.make_facade(seed=7)))
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def facade_a_half() -> bytes:
|
||||
return synth.encode_jpg(synth.scale_half(synth.make_facade(seed=7)))
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def facade_a_crop() -> bytes:
|
||||
return synth.encode_jpg(synth.crop_center(synth.make_facade(seed=7)))
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def facade_b() -> bytes:
|
||||
return synth.encode_jpg(synth.make_facade(seed=99))
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def flat_image() -> bytes:
|
||||
return synth.encode_jpg(synth.make_flat())
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def tiny_image() -> bytes:
|
||||
return synth.encode_jpg(synth.make_flat(width=300, height=200))
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def exif_image() -> bytes:
|
||||
return synth.encode_exif_oriented(synth.make_facade(seed=11))
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Синтетические изображения для тестов (docs/08 §8.2, §8.6).
|
||||
|
||||
Реальных фото в git нет — только детерминированная генерация OpenCV/NumPy.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
|
||||
def make_facade(seed: int = 7, width: int = 1400, height: int = 900) -> np.ndarray:
|
||||
"""Текстурированный «фасад»: сетка окон со случайными цветами + швы + шум."""
|
||||
rng = np.random.default_rng(seed)
|
||||
img = np.full((height, width, 3), 118, np.uint8)
|
||||
for y in range(0, height, 28): # кладка
|
||||
cv2.line(img, (0, y), (width, y), (132, 128, 122), 1)
|
||||
for y in range(40, height - 160, 140):
|
||||
for x in range(60, width - 200, 190):
|
||||
col = tuple(int(c) for c in rng.integers(28, 225, 3))
|
||||
cv2.rectangle(img, (x, y), (x + 110, y + 95), col, -1)
|
||||
cv2.rectangle(img, (x, y), (x + 110, y + 95), (205, 198, 170), 3)
|
||||
cv2.circle(img, (x + 55, y + 47), 8, (240, 240, 235), 2)
|
||||
return cv2.add(img, rng.integers(0, 16, img.shape, dtype=np.uint8))
|
||||
|
||||
|
||||
def encode_jpg(img: np.ndarray, quality: int = 92) -> bytes:
|
||||
ok, buf = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, quality])
|
||||
if not ok:
|
||||
raise RuntimeError("не удалось закодировать JPEG")
|
||||
return buf.tobytes()
|
||||
|
||||
|
||||
def warp_perspective(img: np.ndarray) -> np.ndarray:
|
||||
"""Проективное искажение — имитация смены ракурса (UT-02)."""
|
||||
h, w = img.shape[:2]
|
||||
src = np.float32([[0, 0], [w, 0], [w, h], [0, h]])
|
||||
dst = np.float32(
|
||||
[[w * 0.12, h * 0.10], [w * 0.95, h * 0.04], [w * 0.90, h * 0.97], [w * 0.05, h * 0.90]]
|
||||
)
|
||||
m = cv2.getPerspectiveTransform(src, dst)
|
||||
return cv2.warpPerspective(img, m, (w, h), flags=cv2.INTER_LINEAR)
|
||||
|
||||
|
||||
def scale_half(img: np.ndarray) -> np.ndarray:
|
||||
h, w = img.shape[:2]
|
||||
return cv2.resize(img, (w // 2, h // 2), interpolation=cv2.INTER_AREA)
|
||||
|
||||
|
||||
def crop_center(img: np.ndarray, fraction: float = 0.45) -> np.ndarray:
|
||||
"""Фрагмент фасада — частичная видимость (UT-06)."""
|
||||
h, w = img.shape[:2]
|
||||
ch, cw = int(h * fraction), int(w * fraction)
|
||||
y0, x0 = (h - ch) // 2, (w - cw) // 2
|
||||
return img[y0 : y0 + ch, x0 : x0 + cw]
|
||||
|
||||
|
||||
def make_flat(width: int = 700, height: int = 520) -> np.ndarray:
|
||||
"""Однотонная заливка — «бедная» текстура (UT-07)."""
|
||||
return np.full((height, width, 3), 128, np.uint8)
|
||||
|
||||
|
||||
def encode_exif_oriented(img: np.ndarray, orientation: int = 6) -> bytes:
|
||||
"""JPEG с EXIF-ориентацией (UT-09): 6 = поворот на 90° по часовой."""
|
||||
import io
|
||||
|
||||
from PIL import Image
|
||||
|
||||
pil = Image.fromarray(img)
|
||||
exif = Image.Exif()
|
||||
exif[274] = orientation # Orientation
|
||||
buffer = io.BytesIO()
|
||||
pil.save(buffer, format="JPEG", exif=exif)
|
||||
return buffer.getvalue()
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Юнит-тесты блоб-кодека — docs/08 §8.2, UT-10..UT-15."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from app.cv.blob import UnpackedBlob, build_meta, compute_algo_id, pack, unpack
|
||||
from app.cv.exceptions import BlobInvalid, FormatUnsupported
|
||||
from app.cv.extraction import Features, extract
|
||||
from app.cv.params import base_extraction
|
||||
from tests import synth
|
||||
from tests.conftest import make_config
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def config():
|
||||
return make_config()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def sample(config) -> tuple[Features, dict, bytes]:
|
||||
features = extract(synth.encode_jpg(synth.make_facade(seed=7)), base_extraction(config))
|
||||
params = base_extraction(config)
|
||||
meta = build_meta(
|
||||
params=params,
|
||||
algo_id=compute_algo_id(params),
|
||||
features=features,
|
||||
settings_payload={"profile": "monument", "comparison": {"lowe_ratio": 0.70}},
|
||||
source_sha256="ab12cd34",
|
||||
)
|
||||
return features, meta, pack(features, meta)
|
||||
|
||||
|
||||
def _repack(descriptors, keypoints, meta) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
np.savez_compressed(
|
||||
buffer,
|
||||
descriptors=descriptors,
|
||||
keypoints=keypoints,
|
||||
meta=np.array(json.dumps(meta)),
|
||||
)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
class TestBlobCodec:
|
||||
def test_ut10_roundtrip(self, config, sample):
|
||||
"""UT-10: save → load — идентичные массивы, meta сохраняется."""
|
||||
features, meta, blob = sample
|
||||
unpacked = unpack(blob, config)
|
||||
|
||||
assert np.array_equal(unpacked.features.descriptors, features.descriptors)
|
||||
assert np.array_equal(unpacked.features.keypoints, features.keypoints)
|
||||
for key, value in meta.items():
|
||||
if key == "created_at":
|
||||
continue
|
||||
assert unpacked.meta[key] == value, key
|
||||
|
||||
def test_ut10b_descriptor_range(self, config):
|
||||
"""UT-10 (продолжение): uint8-дескрипторы в диапазоне 0–255."""
|
||||
features = extract(synth.encode_jpg(synth.make_facade(seed=5)), base_extraction(config))
|
||||
assert features.descriptors.dtype == np.uint8
|
||||
assert features.descriptors.min() >= 0 and features.descriptors.max() <= 255
|
||||
|
||||
def test_ut11_uint8_float32_lossless(self):
|
||||
"""UT-11: конверсия uint8 ↔ float32 без потерь (значения целые)."""
|
||||
descs = np.array([0, 1, 127, 254, 255] * 25 + [3, 3, 3], dtype=np.uint8).reshape(1, 128)
|
||||
assert descs.dtype == np.uint8
|
||||
restored = descs.astype(np.float32).astype(np.uint8)
|
||||
assert np.array_equal(descs, restored)
|
||||
|
||||
def test_ut12_broken_zip(self, config):
|
||||
"""UT-12: битый zip / не-npz — FEATURE_BLOB_INVALID."""
|
||||
with pytest.raises(BlobInvalid):
|
||||
unpack(b"not a zip at all", config)
|
||||
with pytest.raises(BlobInvalid):
|
||||
unpack(b"PK\x03\x04truncated", config)
|
||||
|
||||
def test_ut13a_missing_array(self, config, sample):
|
||||
"""UT-13: отсутствует массив — FEATURE_BLOB_INVALID."""
|
||||
_, meta, _ = sample
|
||||
buffer = io.BytesIO()
|
||||
np.savez_compressed(
|
||||
buffer,
|
||||
descriptors=np.zeros((10, 128), np.uint8),
|
||||
meta=np.array(json.dumps({**meta, "keypoints_count": 10})),
|
||||
)
|
||||
with pytest.raises(BlobInvalid):
|
||||
unpack(buffer.getvalue(), config)
|
||||
|
||||
def test_ut13b_shape_mismatch(self, config, sample):
|
||||
"""UT-13: несогласованные формы массивов — FEATURE_BLOB_INVALID."""
|
||||
_, meta, _ = sample
|
||||
descs = np.zeros((10, 128), np.uint8)
|
||||
kps = np.zeros((7, 5), np.float32)
|
||||
with pytest.raises(BlobInvalid):
|
||||
unpack(_repack(descs, kps, {**meta, "keypoints_count": 10}), config)
|
||||
|
||||
def test_ut13c_count_mismatch(self, config, sample):
|
||||
"""UT-13: keypoints_count ≠ N — FEATURE_BLOB_INVALID."""
|
||||
_, meta, _ = sample
|
||||
descs = np.zeros((10, 128), np.uint8)
|
||||
kps = np.zeros((10, 5), np.float32)
|
||||
with pytest.raises(BlobInvalid):
|
||||
unpack(_repack(descs, kps, {**meta, "keypoints_count": 999}), config)
|
||||
|
||||
def test_ut14_format_version(self, config, sample):
|
||||
"""UT-14: meta.format_version не тот — FEATURE_FORMAT_UNSUPPORTED."""
|
||||
_, meta, _ = sample
|
||||
descs = np.zeros((10, 128), np.uint8)
|
||||
kps = np.zeros((10, 5), np.float32)
|
||||
foreign = {**meta, "format_version": 99, "keypoints_count": 10}
|
||||
with pytest.raises(FormatUnsupported) as excinfo:
|
||||
unpack(_repack(descs, kps, foreign), config)
|
||||
assert excinfo.value.details["received"] == 99
|
||||
assert excinfo.value.details["expected_format_version"] == 1
|
||||
|
||||
def test_ut15_zip_bomb(self, config, sample):
|
||||
"""UT-15: корректная структура, но массив сверх лимита — отклонение
|
||||
по SIFT_MAX_KEYPOINTS без распаковки в память."""
|
||||
_, meta, _ = sample
|
||||
small = make_config(sift_max_keypoints=100)
|
||||
descs = np.zeros((20_000, 128), np.uint8) # 2.56 МБ распакованных
|
||||
kps = np.zeros((20_000, 5), np.float32)
|
||||
blob = _repack(descs, kps, {**meta, "keypoints_count": 20_000})
|
||||
with pytest.raises(BlobInvalid, match="лимит"):
|
||||
unpack(blob, small)
|
||||
|
||||
def test_meta_without_settings(self, config):
|
||||
"""meta без необязательного settings — читается, settings = None (06 §6.5)."""
|
||||
features = extract(synth.encode_jpg(synth.make_facade(seed=7)), base_extraction(config))
|
||||
params = base_extraction(config)
|
||||
meta = build_meta(params, compute_algo_id(params), features, None, "ff00")
|
||||
unpacked = unpack(pack(features, meta), config)
|
||||
assert unpacked.settings is None
|
||||
|
||||
def test_unpacked_resized_dims(self, config, sample):
|
||||
"""Размеры приведённого изображения восстанавливаются из meta."""
|
||||
_, meta, blob = sample
|
||||
unpacked: UnpackedBlob = unpack(blob, config)
|
||||
assert unpacked.features.width <= meta["extraction_params"]["max_image_size"]
|
||||
assert unpacked.features.height <= meta["extraction_params"]["max_image_size"]
|
||||
ratio = unpacked.features.width / unpacked.features.source_width
|
||||
assert ratio == pytest.approx(
|
||||
unpacked.features.height / unpacked.features.source_height, rel=0.02
|
||||
)
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Юнит-тесты извлечения и сравнения — docs/08 §8.2, UT-01..UT-09, UT-17."""
|
||||
from __future__ import annotations
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from app.cv.comparison import PairResult, compare_features
|
||||
from app.cv.extraction import extract
|
||||
from app.cv.params import ComparisonParams, base_extraction, base_comparison
|
||||
from tests import synth
|
||||
from tests.conftest import make_config
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def config():
|
||||
return make_config()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def features_pair(config):
|
||||
"""Признаки базового «фасада» и его копии — общая база для UT-01..UT-08."""
|
||||
base = synth.encode_jpg(synth.make_facade(seed=7))
|
||||
f1 = extract(base, base_extraction(config))
|
||||
f2 = extract(base, base_extraction(config))
|
||||
return f1, f2
|
||||
|
||||
|
||||
def _compare(config, probe, ref, **overrides) -> PairResult:
|
||||
params = base_comparison(config)
|
||||
if overrides:
|
||||
params = ComparisonParams(**{**vars(params), **overrides})
|
||||
return compare_features(probe, ref, params)
|
||||
|
||||
|
||||
class TestExtractionComparison:
|
||||
def test_ut01_photo_vs_copy(self, config, features_pair):
|
||||
"""UT-01: фото vs копия — match, высокий confidence, inlier_ratio ≥ 0.8."""
|
||||
f1, f2 = features_pair
|
||||
result = _compare(config, f1, f2)
|
||||
assert result.verdict == "match"
|
||||
assert result.confidence >= 0.6
|
||||
assert result.metrics.inlier_ratio >= 0.8
|
||||
|
||||
def test_ut02_photo_vs_warped(self, config):
|
||||
"""UT-02: проективно искажённая копия — match."""
|
||||
base = synth.make_facade(seed=7)
|
||||
f1 = extract(synth.encode_jpg(base), base_extraction(config))
|
||||
f2 = extract(synth.encode_jpg(synth.warp_perspective(base)), base_extraction(config))
|
||||
result = _compare(config, f1, f2)
|
||||
assert result.verdict == "match"
|
||||
|
||||
def test_ut03_photo_vs_half(self, config):
|
||||
"""UT-03: уменьшенная копия (0.5×) — match.
|
||||
|
||||
База берётся 1600×1200, чтобы уменьшенная копия (800×600) оставалась
|
||||
выше минимального разрешения 640×480.
|
||||
"""
|
||||
base = synth.make_facade(seed=7, width=1600, height=1200)
|
||||
f1 = extract(synth.encode_jpg(base), base_extraction(config))
|
||||
f2 = extract(synth.encode_jpg(synth.scale_half(base)), base_extraction(config))
|
||||
result = _compare(config, f1, f2)
|
||||
assert result.verdict == "match"
|
||||
|
||||
def test_ut04_photo_vs_other_building(self, config):
|
||||
"""UT-04: другое здание — no_match или uncertain, но не match."""
|
||||
f1 = extract(synth.encode_jpg(synth.make_facade(seed=7)), base_extraction(config))
|
||||
f2 = extract(synth.encode_jpg(synth.make_facade(seed=99)), base_extraction(config))
|
||||
result = _compare(config, f1, f2)
|
||||
assert result.verdict in ("no_match", "uncertain")
|
||||
|
||||
def test_ut05_photo_vs_other_angle(self, config):
|
||||
"""UT-05: тот же объект, другой ракурс — match при «широком» ракурсе."""
|
||||
base = synth.make_facade(seed=7)
|
||||
h, w = base.shape[:2]
|
||||
src = np.float32([[0, 0], [w, 0], [w, h], [0, h]])
|
||||
dst = np.float32(
|
||||
[[w * 0.08, h * 0.06], [w * 0.97, h * 0.10], [w * 0.88, h * 0.95], [w * 0.10, h * 0.92]]
|
||||
)
|
||||
m = cv2.getPerspectiveTransform(src, dst)
|
||||
other_angle = cv2.warpPerspective(base, m, (w, h))
|
||||
f1 = extract(synth.encode_jpg(base), base_extraction(config))
|
||||
f2 = extract(synth.encode_jpg(other_angle), base_extraction(config))
|
||||
assert _compare(config, f1, f2).verdict == "match"
|
||||
|
||||
def test_ut06_cropped_fragment(self, config):
|
||||
"""UT-06: фрагмент как эталон — coverage корректно мал.
|
||||
|
||||
Проба — полный кадр, эталон — кроп 60 %: инлаеры покрывают только
|
||||
область фрагмента (защита от «локального совпадения» — 04 §4.3).
|
||||
Кроп 60 % сохраняет разрешение выше 640×480.
|
||||
"""
|
||||
base = synth.make_facade(seed=7)
|
||||
f_full = extract(synth.encode_jpg(base), base_extraction(config))
|
||||
f_crop = extract(synth.encode_jpg(synth.crop_center(base, fraction=0.6)),
|
||||
base_extraction(config))
|
||||
result = _compare(config, f_full, f_crop)
|
||||
assert result.verdict in ("uncertain", "match")
|
||||
assert result.metrics.coverage == pytest.approx(0.6 * 0.6, abs=0.15)
|
||||
|
||||
def test_ut07_poor_texture(self, config):
|
||||
"""UT-07: однотонная заливка — мало keypoints, деградация без исключений."""
|
||||
features = extract(synth.encode_jpg(synth.make_flat()), base_extraction(config))
|
||||
assert features.count < 500
|
||||
other = extract(synth.encode_jpg(synth.make_facade(seed=3)), base_extraction(config))
|
||||
result = _compare(config, features, other) # не должно упасть
|
||||
assert result.verdict in ("no_match", "uncertain")
|
||||
|
||||
def test_ut08_determinism(self, config, features_pair):
|
||||
"""UT-08: повторный compare тех же входов — идентичные метрики (NFR-009)."""
|
||||
f1, f2 = features_pair
|
||||
first = _compare(config, f1, f2)
|
||||
second = _compare(config, f1, f2)
|
||||
assert first.metrics == second.metrics
|
||||
assert first.verdict == second.verdict
|
||||
assert first.confidence == second.confidence
|
||||
|
||||
def test_ut09_preprocessing(self, config):
|
||||
"""UT-09: EXIF-ориентация, ресайз, CLAHE — корректные размеры/типы."""
|
||||
from app.cv.extraction import decode_image, _preprocess
|
||||
from app.cv.params import ExtractionParams
|
||||
|
||||
# EXIF-ориентация 6 (поворот 90°): размеры меняются местами
|
||||
raw = synth.make_facade(seed=11, width=1400, height=900)
|
||||
exif_jpg = synth.encode_exif_oriented(raw, orientation=6)
|
||||
_, width, height = decode_image(exif_jpg)
|
||||
assert (width, height) == (900, 1400)
|
||||
|
||||
# ресайз до max_image_size длинной стороны
|
||||
params = ExtractionParams(max_image_size=800, max_keypoints=4096,
|
||||
clahe_clip_limit=2.0, clahe_tile_grid=(8, 8))
|
||||
gray, w, h = _preprocess(np.asarray(cv2.cvtColor(raw, cv2.COLOR_BGR2RGB)), params)
|
||||
assert max(w, h) <= 800
|
||||
assert gray.dtype == np.uint8 and gray.ndim == 2
|
||||
|
||||
# CLAHE не меняет размеров и тип
|
||||
assert (w, h) == (gray.shape[1], gray.shape[0])
|
||||
|
||||
def test_ut17_fundamental_model(self, config):
|
||||
"""UT-17: fundamental на синтетической паре — метрики считаются и
|
||||
детерминированы; обе модели дают согласованные вердикты.
|
||||
|
||||
Сравнение абсолютных чисел инлаеров H vs F на плоской синтетике
|
||||
нестабильно (порог F — расстояние до эпиполярной линии, не пиксели
|
||||
репроекции), поэтому проверяется вычислимость и детерминизм.
|
||||
"""
|
||||
base = synth.make_facade(seed=7)
|
||||
f1 = extract(synth.encode_jpg(base), base_extraction(config))
|
||||
f2 = extract(synth.encode_jpg(synth.warp_perspective(base)), base_extraction(config))
|
||||
|
||||
fund_a = _compare(config, f1, f2, geometry_model="fundamental")
|
||||
fund_b = _compare(config, f1, f2, geometry_model="fundamental")
|
||||
homo = _compare(config, f1, f2, geometry_model="homography")
|
||||
|
||||
assert fund_a.metrics.inliers > 0 # метрики считаются
|
||||
assert fund_a.metrics == fund_b.metrics # детерминизм
|
||||
assert fund_a.confidence == fund_b.confidence
|
||||
assert homo.metrics.inliers > 0
|
||||
assert homo.verdict == fund_a.verdict # согласованность моделей
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Юнит-тесты резолвера настроек и валидации — docs/08 §8.2, UT-16, UT-18."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.cv.exceptions import InvalidSettings, UnknownProfile
|
||||
from app.cv.params import (
|
||||
RequestSettings,
|
||||
parse_settings,
|
||||
validate_stored_settings,
|
||||
)
|
||||
from app.cv.resolver import (
|
||||
effective_comparison,
|
||||
effective_extraction,
|
||||
effective_probe_extraction,
|
||||
)
|
||||
from tests.conftest import make_config
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def config():
|
||||
return make_config()
|
||||
|
||||
|
||||
class TestResolver:
|
||||
def test_ut16_comparison_priority(self, config):
|
||||
"""UT-16: env → профиль → блоб → запрос (docs/04 §4.5.4)."""
|
||||
blob = RequestSettings(
|
||||
profile="monument", extraction={}, comparison={"lowe_ratio": 0.70}
|
||||
)
|
||||
request = RequestSettings(profile=None, extraction={}, comparison={})
|
||||
|
||||
# env-умолчания
|
||||
base = effective_comparison(config, None, None)
|
||||
assert base.lowe_ratio == config.lowe_ratio
|
||||
assert base.geometry_model == "homography"
|
||||
|
||||
# профиль из блоба подключается, если запрос профиль не задаёт
|
||||
with_blob_profile = effective_comparison(config, request, blob)
|
||||
assert with_blob_profile.geometry_model == "fundamental" # из monument
|
||||
assert with_blob_profile.lowe_ratio == 0.70 # из блоба
|
||||
assert with_blob_profile.match_inliers_min == 40 # из monument
|
||||
|
||||
# профиль запроса сильнее профиля блоба, переопределения запроса —
|
||||
# сильнее всего
|
||||
req = RequestSettings(
|
||||
profile="facade",
|
||||
extraction={},
|
||||
comparison={"match_inliers_min": 70, "lowe_ratio": 0.68},
|
||||
)
|
||||
top = effective_comparison(config, req, blob)
|
||||
assert top.geometry_model == "homography" # facade из запроса победил monument
|
||||
assert top.match_inliers_min == 70
|
||||
assert top.lowe_ratio == 0.68
|
||||
|
||||
def test_ut16_extraction_priority(self, config):
|
||||
"""UT-16: извлечение — env → профиль → переопределения запроса."""
|
||||
req = RequestSettings(
|
||||
profile="monument",
|
||||
extraction={"max_image_size": 1000},
|
||||
comparison={},
|
||||
)
|
||||
params = effective_extraction(config, req)
|
||||
assert params.max_image_size == 1000 # запрос
|
||||
assert params.clahe_clip_limit == 3.0 # профиль monument
|
||||
assert params.max_keypoints == config.sift_max_keypoints # env
|
||||
|
||||
# проба в /verify: extraction-override запроса не действует (FR-002)
|
||||
probe = effective_probe_extraction(config, req)
|
||||
assert probe.max_image_size == config.sift_max_image_size
|
||||
assert probe.clahe_clip_limit == 3.0 # профиль действует
|
||||
|
||||
def test_cross_field_validation(self, config):
|
||||
"""uncertain_inliers_min > match_inliers_min в эффективных значениях — 422."""
|
||||
req = RequestSettings(profile=None, extraction={}, comparison={"match_inliers_min": 15})
|
||||
with pytest.raises(InvalidSettings):
|
||||
effective_comparison(config, req, None)
|
||||
|
||||
|
||||
class TestSettingsValidation:
|
||||
def test_ut18_unknown_profile(self, config):
|
||||
with pytest.raises(UnknownProfile):
|
||||
parse_settings({"profile": "skyscraper"}, config)
|
||||
|
||||
def test_ut18_unknown_key(self, config):
|
||||
with pytest.raises(InvalidSettings, match="(?i)неизвестн") as exc:
|
||||
parse_settings({"comparison": {"ratio_lowe": 0.7}}, config)
|
||||
assert exc.value.details.get("key") == "ratio_lowe"
|
||||
|
||||
def test_ut18_out_of_range(self, config):
|
||||
with pytest.raises(InvalidSettings) as exc:
|
||||
parse_settings({"comparison": {"lowe_ratio": 0.05}}, config)
|
||||
assert exc.value.details["key"] == "lowe_ratio"
|
||||
|
||||
def test_ut18_unknown_top_level_key(self, config):
|
||||
with pytest.raises(InvalidSettings):
|
||||
parse_settings({"comparson": {}}, config)
|
||||
|
||||
def test_valid_settings_pass(self, config):
|
||||
parsed = parse_settings(
|
||||
{
|
||||
"profile": "monument",
|
||||
"extraction": {"clahe_clip_limit": 3.0, "clahe_tile_grid": [8, 8]},
|
||||
"comparison": {"geometry_model": "fundamental", "lowe_ratio": 0.72},
|
||||
},
|
||||
config,
|
||||
)
|
||||
assert parsed.profile == "monument"
|
||||
assert parsed.comparison["geometry_model"] == "fundamental"
|
||||
|
||||
def test_max_keypoints_capped_by_env(self, config):
|
||||
with pytest.raises(InvalidSettings, match="потолка|ceil"):
|
||||
parse_settings({"extraction": {"max_keypoints": 60_000}}, config)
|
||||
|
||||
def test_stored_settings_invalid_becomes_blob_invalid(self, config):
|
||||
from app.cv.exceptions import BlobInvalid
|
||||
|
||||
with pytest.raises(BlobInvalid):
|
||||
validate_stored_settings({"profile": "no-such-profile"}, config)
|
||||
Reference in New Issue
Block a user