calibrate

This commit is contained in:
2026-10-06 17:58:35 +03:00
parent 86222f5f93
commit 476cfe0b17
21 changed files with 1666 additions and 14 deletions
+8
View File
@@ -32,6 +32,14 @@ def post_verify(client, probe: bytes, references: list[tuple[str, bytes, str]],
)
def post_calibrate(client, positives: list[tuple[str, bytes, str]],
negatives: list[tuple[str, bytes, str]]):
"""Пачки калибровки — списки (имя, байты, content_type)."""
files = [("positive", p) for p in positives]
files += [("negative", n) for n in negatives]
return client.post("/api/v1/calibrate", headers=API_KEY_HEADERS, files=files)
def make_blob_ref(blob: bytes) -> tuple[str, bytes, str]:
return ("reference.npz", blob, "application/octet-stream")
+134
View File
@@ -0,0 +1,134 @@
"""Интеграционные тесты POST /api/v1/calibrate — docs/08 §8.3 (IT-18..IT-25).
Фикстуры — синтетические изображения (docs/08 §8.6): позитивы — «фасад» и его
проективный поворот, негатив — фасад с другой раскраской.
"""
from __future__ import annotations
import pytest
from fastapi.testclient import TestClient
from tests import synth
from tests.api.helpers import API_KEY_HEADERS, post_calibrate, post_features
_ONE_MB = 1024 * 1024 # как в тестовом конфиге conftest.make_config
@pytest.fixture(scope="module")
def positive_pack():
facade = synth.make_facade(seed=7, width=900, height=640)
return [
("pos-a.jpg", synth.encode_jpg(facade), "image/jpeg"),
("pos-b.jpg", synth.encode_jpg(synth.warp_perspective(facade)), "image/jpeg"),
]
@pytest.fixture(scope="module")
def negative_pack():
other = synth.make_facade(seed=99, width=900, height=640)
return [("neg-c.jpg", synth.encode_jpg(other), "image/jpeg")]
@pytest.fixture(scope="module")
def tiny_jpg():
return ("tiny.jpg", synth.encode_jpg(synth.make_flat(width=300, height=200)), "image/jpeg")
class TestCalibrateEndpoint:
def test_it18_returns_settings_and_report(self, client, positive_pack, negative_pack):
"""IT-18: две пачки → 200, готовый settings + полный отчёт;
выданные настройки принимаются /features (цикл регистрации эталонов)."""
response = post_calibrate(client, positive_pack, negative_pack)
assert response.status_code == 200
body = response.json()
settings = body["settings"]["comparison"]
assert set(settings) == {
"geometry_model", "lowe_ratio", "ransac_reproj_threshold",
"match_inliers_min", "match_inliers_ratio_min",
"match_coverage_min", "uncertain_inliers_min",
}
assert body["metrics"]["false_matches"] == 0
assert body["metrics"]["positive_pairs"] == 2
assert body["metrics"]["negative_pairs"] == 2
assert len(body["ranking"]) == 18 # 2 геометрии × 3 lowe × 3 ransac
verdicts = {(p["probe"], p["ref"]): p["verdict"] for p in body["pairs"]}
assert verdicts[("pos-a.jpg", "pos-b.jpg")] == "match"
assert verdicts[("pos-b.jpg", "pos-a.jpg")] == "match"
assert verdicts[("neg-c.jpg", "pos-a.jpg")] != "match"
assert verdicts[("neg-c.jpg", "pos-b.jpg")] != "match"
assert body["selfcheck"]["matched"] == body["selfcheck"]["checked"] == 4
assert body["skipped"] == []
# финал цикла пользователя: /features с откалиброванными настройками
features = post_features(client, positive_pack[0][1], settings=body["settings"])
assert features.status_code == 200
def test_it19_skips_invalid_files(self, client, positive_pack, negative_pack, tiny_jpg):
"""IT-19: битый файл в пачке пропускается и попадает в skipped."""
response = post_calibrate(
client, positive_pack + [tiny_jpg], negative_pack
)
assert response.status_code == 200
body = response.json()
assert len(body["skipped"]) == 1
assert body["skipped"][0]["name"] == "tiny.jpg"
assert body["skipped"][0]["group"] == "positive"
assert "640x480" in body["skipped"][0]["reason"]
def test_it20_all_positives_invalid(self, client, tiny_jpg, negative_pack):
"""IT-20: после отбраковки <2 позитивов → 422 CALIBRATION_DATASET_INVALID."""
response = post_calibrate(client, [tiny_jpg, tiny_jpg], negative_pack)
assert response.status_code == 422
error = response.json()["error"]
assert error["code"] == "CALIBRATION_DATASET_INVALID"
def test_it21_single_positive_part(self, client, negative_pack):
response = post_calibrate(client, [negative_pack[0]], negative_pack)
assert response.status_code == 422
error = response.json()["error"]
assert error["code"] == "VALIDATION_ERROR"
assert error["details"]["part"] == "positive"
def test_it22_no_negative_parts(self, client, positive_pack):
response = post_calibrate(client, positive_pack, [])
assert response.status_code == 422
error = response.json()["error"]
assert error["code"] == "VALIDATION_ERROR"
assert error["details"]["part"] == "negative"
def test_it23_too_many_images_in_pack(self, client, negative_pack):
"""IT-23: > CALIBRATION_MAX_IMAGES_PER_PACK (8 в тестовом конфиге)."""
flats = [
(f"flat-{i}.jpg", synth.encode_jpg(synth.make_flat(width=640, height=480)), "image/jpeg")
for i in range(9)
]
response = post_calibrate(client, flats, negative_pack)
assert response.status_code == 400
error = response.json()["error"]
assert error["code"] == "TOO_MANY_CALIBRATION_IMAGES"
assert error["details"]["limit"] == 8
def test_it24_oversized_part(self, client, positive_pack, negative_pack):
response = post_calibrate(
client,
[("huge.jpg", b"0" * (_ONE_MB + 1), "image/jpeg")] + positive_pack[1:],
negative_pack,
)
assert response.status_code == 413
error = response.json()["error"]
assert error["code"] == "PAYLOAD_TOO_LARGE"
assert error["details"]["part"] == "positive[0]"
def test_it25_auth(self, client, positive_pack, negative_pack):
files = [("positive", p) for p in positive_pack]
files += [("negative", n) for n in negative_pack]
assert client.post("/api/v1/calibrate", files=files).status_code == 401
assert (
client.post(
"/api/v1/calibrate",
headers={"X-API-Key": "wrong"},
files=files,
).status_code
== 403
)
+16 -2
View File
@@ -23,7 +23,10 @@ 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"):
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):
@@ -68,11 +71,22 @@ class TestSpecFile:
# все коды из таблицы docs/05 §5.3
assert codes == {
"IMAGE_DECODE_FAILED", "FEATURE_BLOB_INVALID", "FEATURE_FORMAT_UNSUPPORTED",
"TOO_MANY_REFERENCES", "UNKNOWN_PROFILE", "IMAGE_TOO_SMALL",
"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