Тесты: unit+api с фейковым эмбеддером, real-model smoke за RUN_REAL_MODEL
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
"""Хелперы HTTP-тестов: post_verify собирает multipart с повторяемой частью reference."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # tests/ для synth
|
||||
|
||||
from synth import make_blocks # noqa: E402
|
||||
|
||||
# Блочные паттерны 4x4 (16 бит, по строкам): A и B делят ровно половину единиц,
|
||||
# C не пересекается с A — косинусы для FakeEmbedder: A/A=1.0, A/B=0.5, A/C=0.0
|
||||
PATTERN_A = (1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0)
|
||||
PATTERN_B = (1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0)
|
||||
PATTERN_C = (0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1)
|
||||
|
||||
|
||||
def block_jpeg(pattern) -> bytes:
|
||||
from synth import encode
|
||||
|
||||
return encode(make_blocks(list(pattern), size=256), fmt="JPEG")
|
||||
|
||||
|
||||
def post_verify(client, probe: bytes, references: list[bytes], headers: dict | None = None):
|
||||
files = [("probe", ("probe.jpg", probe, "image/jpeg"))]
|
||||
files += [
|
||||
("reference", (f"ref_{i}.jpg", blob, "image/jpeg")) for i, blob in enumerate(references)
|
||||
]
|
||||
return client.post("/api/v1/verify", files=files, headers=headers)
|
||||
@@ -0,0 +1,67 @@
|
||||
"""IT: аутентификация X-API-Key, /health, /ready, поведение при неготовности модели."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from conftest import make_config
|
||||
from fakes import FailingEmbedder, FakeEmbedder
|
||||
from helpers import PATTERN_A, block_jpeg, post_verify
|
||||
|
||||
from app.main import create_app
|
||||
|
||||
|
||||
class TestAuth:
|
||||
def test_401_without_key(self):
|
||||
app = create_app(make_config(api_key="secret"), embedder=FakeEmbedder())
|
||||
with TestClient(app, raise_server_exceptions=False) as client:
|
||||
response = post_verify(client, block_jpeg(PATTERN_A), [block_jpeg(PATTERN_A)])
|
||||
assert response.status_code == 401
|
||||
assert response.json()["error"]["code"] == "UNAUTHORIZED"
|
||||
|
||||
def test_403_wrong_key(self):
|
||||
app = create_app(make_config(api_key="secret"), embedder=FakeEmbedder())
|
||||
with TestClient(app, raise_server_exceptions=False) as client:
|
||||
response = post_verify(
|
||||
client, block_jpeg(PATTERN_A), [block_jpeg(PATTERN_A)], headers={"X-API-Key": "nope"}
|
||||
)
|
||||
assert response.status_code == 403
|
||||
assert response.json()["error"]["code"] == "FORBIDDEN"
|
||||
|
||||
def test_valid_key_passes(self):
|
||||
app = create_app(make_config(api_key="secret"), embedder=FakeEmbedder())
|
||||
with TestClient(app, raise_server_exceptions=False) as client:
|
||||
response = post_verify(
|
||||
client, block_jpeg(PATTERN_A), [block_jpeg(PATTERN_A)],
|
||||
headers={"X-API-Key": "secret"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_health_and_ready_skip_auth(self):
|
||||
app = create_app(make_config(api_key="secret"), embedder=FakeEmbedder())
|
||||
with TestClient(app, raise_server_exceptions=False) as client:
|
||||
assert client.get("/health").status_code == 200
|
||||
assert client.get("/ready").status_code == 200
|
||||
|
||||
|
||||
class TestReadiness:
|
||||
def test_ready_ok_when_model_loaded(self, client):
|
||||
response = client.get("/ready")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ready", "reasons": []}
|
||||
|
||||
def test_not_ready_when_model_load_fails(self):
|
||||
app = create_app(make_config(), embedder=FailingEmbedder())
|
||||
with TestClient(app, raise_server_exceptions=False) as client:
|
||||
ready = client.get("/ready")
|
||||
assert ready.status_code == 503
|
||||
body = ready.json()
|
||||
assert body["status"] == "unavailable"
|
||||
assert any("boom" in reason for reason in body["reasons"])
|
||||
|
||||
verify = post_verify(client, block_jpeg(PATTERN_A), [block_jpeg(PATTERN_A)])
|
||||
assert verify.status_code == 503
|
||||
assert verify.json()["error"]["code"] == "SERVICE_UNAVAILABLE"
|
||||
|
||||
# health отвечает и при неготовности
|
||||
assert client.get("/health").status_code == 200
|
||||
@@ -0,0 +1,142 @@
|
||||
"""IT: POST /api/v1/verify — вердикты, ошибки декодирования, лимиты."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from helpers import PATTERN_A, PATTERN_B, PATTERN_C, block_jpeg, post_verify
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def jpeg_a():
|
||||
return block_jpeg(PATTERN_A)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def jpeg_b():
|
||||
return block_jpeg(PATTERN_B)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def jpeg_c():
|
||||
return block_jpeg(PATTERN_C)
|
||||
|
||||
|
||||
class TestVerifyVerdicts:
|
||||
def test_match_same_image(self, client, jpeg_a):
|
||||
# IT: probe == эталон -> similarity 1.0 -> match
|
||||
response = post_verify(client, jpeg_a, [jpeg_a])
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["verdict"] == "match"
|
||||
assert body["is_match"] is True
|
||||
assert body["confidence"] == pytest.approx(1.0, abs=1e-4)
|
||||
details = body["details"]
|
||||
assert details["references_compared"] == 1
|
||||
assert details["best_reference_index"] == 0
|
||||
assert details["similarities"][0] == pytest.approx(1.0, abs=1e-4)
|
||||
assert details["thresholds"] == {"match": 0.55, "no_match": 0.40}
|
||||
assert len(body["probe_sha256"]) == 64
|
||||
assert body["processing_ms"] >= 0
|
||||
|
||||
def test_uncertain_half_overlap(self, client, jpeg_a, jpeg_b):
|
||||
# IT: косинус 0.5 между порогами -> uncertain, is_match False
|
||||
response = post_verify(client, jpeg_a, [jpeg_b])
|
||||
body = response.json()
|
||||
assert body["verdict"] == "uncertain"
|
||||
assert body["is_match"] is False
|
||||
assert body["confidence"] == pytest.approx(0.5, abs=1e-3)
|
||||
|
||||
def test_no_match_disjoint(self, client, jpeg_a, jpeg_c):
|
||||
response = post_verify(client, jpeg_a, [jpeg_c])
|
||||
body = response.json()
|
||||
assert body["verdict"] == "no_match"
|
||||
assert body["is_match"] is False
|
||||
|
||||
def test_best_reference_across_many(self, client, jpeg_a, jpeg_c, jpeg_b):
|
||||
# IT: лучший эталон — индекс совпавшего вида среди нескольких
|
||||
response = post_verify(client, jpeg_a, [jpeg_c, jpeg_b, jpeg_a])
|
||||
body = response.json()
|
||||
assert body["verdict"] == "match"
|
||||
assert body["details"]["best_reference_index"] == 2
|
||||
assert len(body["details"]["similarities"]) == 3
|
||||
|
||||
|
||||
class TestVerifyValidation:
|
||||
def test_missing_probe_part(self, client, jpeg_a):
|
||||
response = client.post(
|
||||
"/api/v1/verify", files=[("reference", ("r.jpg", jpeg_a, "image/jpeg"))]
|
||||
)
|
||||
assert response.status_code == 422
|
||||
assert response.json()["error"]["code"] == "VALIDATION_ERROR"
|
||||
|
||||
def test_no_references(self, client, jpeg_a):
|
||||
response = client.post(
|
||||
"/api/v1/verify", files=[("probe", ("p.jpg", jpeg_a, "image/jpeg"))]
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_too_many_references(self, client, jpeg_a, config):
|
||||
limit = config.max_references
|
||||
response = post_verify(client, jpeg_a, [jpeg_a] * (limit + 1))
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "TOO_MANY_REFERENCES"
|
||||
|
||||
def test_undecodable_probe(self, client):
|
||||
response = post_verify(client, b"not an image at all", [b"x"])
|
||||
# первый же декод (probe) падает
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "IMAGE_DECODE_FAILED"
|
||||
|
||||
def test_undecodable_reference(self, client, jpeg_a):
|
||||
response = post_verify(client, jpeg_a, [jpeg_a, b"broken"])
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "IMAGE_DECODE_FAILED"
|
||||
|
||||
def test_unsupported_format_bmp(self, client):
|
||||
buffer = io.BytesIO()
|
||||
Image.new("RGB", (64, 64), (200, 10, 10)).save(buffer, format="BMP")
|
||||
bmp = buffer.getvalue()
|
||||
response = post_verify(client, bmp, [bmp])
|
||||
assert response.status_code == 415
|
||||
assert response.json()["error"]["code"] == "UNSUPPORTED_MEDIA_TYPE"
|
||||
|
||||
def test_image_too_small(self, client, jpeg_a):
|
||||
buffer = io.BytesIO()
|
||||
Image.new("RGB", (16, 16), (10, 200, 30)).save(buffer, format="JPEG")
|
||||
tiny = buffer.getvalue()
|
||||
response = post_verify(client, tiny, [jpeg_a])
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "IMAGE_TOO_SMALL"
|
||||
|
||||
def test_trace_id_in_errors(self, client):
|
||||
response = post_verify(client, b"garbage", [b"garbage"])
|
||||
assert response.headers.get("X-Trace-Id")
|
||||
assert response.json()["error"]["trace_id"] == response.headers["X-Trace-Id"]
|
||||
|
||||
|
||||
class TestVerifyLimits:
|
||||
def test_per_file_oversize_413(self, client, config):
|
||||
big = b"\0" * (config.max_image_bytes + 1)
|
||||
response = post_verify(client, big, [big])
|
||||
assert response.status_code == 413
|
||||
assert response.json()["error"]["code"] == "PAYLOAD_TOO_LARGE"
|
||||
|
||||
def test_body_oversize_rejected_early(self):
|
||||
# Тело целиком больше max_body_bytes -> 413 ещё до разбора multipart
|
||||
from conftest import make_config
|
||||
from fakes import FakeEmbedder
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import create_app
|
||||
|
||||
tight = make_config(max_image_bytes=64 * 1024, max_references=2) # лимит ~208 КБ
|
||||
app = create_app(tight, embedder=FakeEmbedder())
|
||||
with TestClient(app, raise_server_exceptions=False) as tight_client:
|
||||
blob = b"\0" * (110 * 1024)
|
||||
response = post_verify(tight_client, blob, [blob])
|
||||
assert response.status_code == 413
|
||||
assert response.json()["error"]["code"] == "PAYLOAD_TOO_LARGE"
|
||||
Reference in New Issue
Block a user