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

135 lines
6.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Интеграционные тесты 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
)