Тесты: 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"
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""Общие фикстуры: тестовый конфиг, приложение с фейковым эмбеддером, клиент."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent)) # импорт fakes/synth из tests/
|
||||||
|
|
||||||
|
from fakes import FakeEmbedder # noqa: E402
|
||||||
|
|
||||||
|
from app.config import Config # noqa: E402
|
||||||
|
from app.main import create_app # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def make_config(**overrides) -> Config:
|
||||||
|
"""Конфиг с боевыми правилами, но мелкими лимитами для тестов 413."""
|
||||||
|
defaults = dict(
|
||||||
|
api_key=None,
|
||||||
|
host="127.0.0.1",
|
||||||
|
port=8000,
|
||||||
|
workers=1,
|
||||||
|
model_name="fake-model",
|
||||||
|
device="cpu",
|
||||||
|
image_size=224,
|
||||||
|
torch_home=None,
|
||||||
|
max_image_bytes=1024 * 1024, # 1 МБ на файл
|
||||||
|
min_image_dim=32,
|
||||||
|
max_references=4,
|
||||||
|
threshold_match=0.55,
|
||||||
|
threshold_no_match=0.40,
|
||||||
|
log_level="WARNING",
|
||||||
|
)
|
||||||
|
defaults.update(overrides)
|
||||||
|
return Config(**defaults)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def config() -> Config:
|
||||||
|
return make_config()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def app(config: Config):
|
||||||
|
application = create_app(config, embedder=FakeEmbedder())
|
||||||
|
with TestClient(application, raise_server_exceptions=False) as client:
|
||||||
|
yield application
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(app):
|
||||||
|
# Lifespan (загрузка фейка) уже отработал внутри фикстуры app
|
||||||
|
return TestClient(app, raise_server_exceptions=False)
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
"""Фейковый эмбеддер: детерминированные векторы из пикселей, без torch.
|
||||||
|
|
||||||
|
Изображения-блочники (см. synth.make_blocks) выравниваются по сетке выборки,
|
||||||
|
поэтому близости можно проектировать точно: совпадение блоков -> 1.0,
|
||||||
|
непересекающиеся -> 0.0, половина перекрытия -> 0.5.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
|
||||||
|
class FakeEmbedder:
|
||||||
|
"""Контракту Embedder удовлетворяет; возвращает L2-нормированные векторы."""
|
||||||
|
|
||||||
|
def __init__(self, grid: int = 4):
|
||||||
|
self.grid = grid
|
||||||
|
self.loaded = False
|
||||||
|
|
||||||
|
def load(self) -> None:
|
||||||
|
self.loaded = True
|
||||||
|
|
||||||
|
def embed(self, images) -> np.ndarray:
|
||||||
|
vectors = np.stack([self._vector(img) for img in images]).astype(np.float32)
|
||||||
|
norms = np.linalg.norm(vectors, axis=1, keepdims=True)
|
||||||
|
return vectors / np.maximum(norms, 1e-12)
|
||||||
|
|
||||||
|
def _vector(self, image: Image.Image) -> np.ndarray:
|
||||||
|
gray = image.convert("L")
|
||||||
|
w, h = gray.size
|
||||||
|
g = self.grid
|
||||||
|
values = []
|
||||||
|
for j in range(g):
|
||||||
|
for i in range(g):
|
||||||
|
x = int((i + 0.5) * w / g)
|
||||||
|
y = int((j + 0.5) * h / g)
|
||||||
|
values.append(gray.getpixel((x, y)) / 255.0)
|
||||||
|
return np.array(values, dtype=np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
class FailingEmbedder:
|
||||||
|
"""load() всегда падает — для проверки /ready=503 и 503 на /verify."""
|
||||||
|
|
||||||
|
def load(self) -> None:
|
||||||
|
raise RuntimeError("boom: модель недоступна")
|
||||||
|
|
||||||
|
def embed(self, images): # pragma: no cover - недостижимо при неудачном load
|
||||||
|
raise AssertionError("не должен вызываться")
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
"""Синтетические изображения для тестов: детерминированы, реальных фото в git нет.
|
||||||
|
|
||||||
|
Два семейства:
|
||||||
|
- блочники make_blocks: сетка g x g чёрных/белых блоков — для фейкового эмбеддера;
|
||||||
|
- «фасады» make_facade: окно-сетка + шум + warp — для smoke с реальной моделью.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
|
||||||
|
def make_blocks(pattern, size: int = 256) -> Image.Image:
|
||||||
|
"""pattern — плоская последовательность 0/1 длины g*g (по строкам)."""
|
||||||
|
g = int(round(len(pattern) ** 0.5))
|
||||||
|
assert g * g == len(pattern), "pattern должен быть квадратной сетки g x g"
|
||||||
|
block = size // g
|
||||||
|
canvas = np.zeros((size, size), dtype=np.uint8)
|
||||||
|
for j in range(g):
|
||||||
|
for i in range(g):
|
||||||
|
if pattern[j * g + i]:
|
||||||
|
canvas[j * block : (j + 1) * block, i * block : (i + 1) * block] = 255
|
||||||
|
return Image.fromarray(canvas, mode="L").convert("RGB")
|
||||||
|
|
||||||
|
|
||||||
|
def make_facade(
|
||||||
|
seed: int, width: int = 640, height: int = 480, floors: int = 4, columns: int = 6
|
||||||
|
) -> Image.Image:
|
||||||
|
"""Псевдофасад: сетка окон + детерминированный шум. floors/columns задают
|
||||||
|
планировку — «другое здание» должно отличаться структурно, а не только шумом
|
||||||
|
(иначе глобальный эмбеддинг закономерно считает их одним зданием).
|
||||||
|
"""
|
||||||
|
rng = np.random.default_rng(seed)
|
||||||
|
img = rng.integers(96, 160, size=(height, width, 3), dtype=np.uint8).astype(np.int16)
|
||||||
|
cell_h, cell_w = height // floors, width // columns
|
||||||
|
for f in range(floors):
|
||||||
|
for c in range(columns):
|
||||||
|
y0 = f * cell_h + cell_h // 4
|
||||||
|
x0 = c * cell_w + cell_w // 4
|
||||||
|
window = rng.integers(20, 70, size=(cell_h // 2, cell_w // 2, 3), dtype=np.uint8)
|
||||||
|
img[y0 : y0 + window.shape[0], x0 : x0 + window.shape[1]] = window
|
||||||
|
return Image.fromarray(np.clip(img, 0, 255).astype(np.uint8))
|
||||||
|
|
||||||
|
|
||||||
|
def warp_affine(image: Image.Image, seed: int = 7, strength: float = 0.12) -> Image.Image:
|
||||||
|
"""Небольшая детерминированная аффинная деформация («другой ракурс»)."""
|
||||||
|
rng = np.random.default_rng(seed)
|
||||||
|
w, h = image.size
|
||||||
|
src = np.array([[0, 0], [w, 0], [0, h]], dtype=np.float32)
|
||||||
|
dst = src + rng.uniform(-strength, strength, size=src.shape).astype(np.float32) * [
|
||||||
|
[w, h],
|
||||||
|
[w, h],
|
||||||
|
[w, h],
|
||||||
|
]
|
||||||
|
coeffs = _solve_affine(src, dst)
|
||||||
|
return image.transform(
|
||||||
|
image.size, Image.AFFINE, coeffs, resample=Image.BILINEAR, fillcolor=(128, 128, 128)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _solve_affine(src: np.ndarray, dst: np.ndarray) -> tuple[float, float, float, float, float, float]:
|
||||||
|
"""Коэффициенты PIL AFFINE (a,b,c,d,e,f): dst = (a*x+b*y+c, d*x+e*y+f)."""
|
||||||
|
matrix = np.column_stack([src[:, 0], src[:, 1], np.ones(3)])
|
||||||
|
solution, *_ = np.linalg.lstsq(matrix, dst, rcond=None)
|
||||||
|
a, b, c = solution[:, 0]
|
||||||
|
d, e, f = solution[:, 1]
|
||||||
|
# PIL использует обратное преобразование
|
||||||
|
inv = np.linalg.inv(np.array([[a, b, c], [d, e, f], [0, 0, 1]]))
|
||||||
|
return (inv[0, 0], inv[0, 1], inv[0, 2], inv[1, 0], inv[1, 1], inv[1, 2])
|
||||||
|
|
||||||
|
|
||||||
|
def encode(image: Image.Image, fmt: str = "JPEG", quality: int = 90) -> bytes:
|
||||||
|
buffer = io.BytesIO()
|
||||||
|
params = {"quality": quality} if fmt == "JPEG" else {}
|
||||||
|
image.save(buffer, format=fmt, **params)
|
||||||
|
return buffer.getvalue()
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""Smoke с реальной моделью DINOv2 (загрузка весов ~84 МБ + torch.hub).
|
||||||
|
|
||||||
|
Запуск: RUN_REAL_MODEL=1 .venv/bin/python -m pytest tests/test_real_model.py -v
|
||||||
|
По умолчанию пропущен — обычный набор тестов не ходит в сеть и не грузит torch.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent)) # synth/ из tests/
|
||||||
|
|
||||||
|
from synth import encode, make_facade, warp_affine # noqa: E402
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.skipif(
|
||||||
|
not os.environ.get("RUN_REAL_MODEL"), reason="set RUN_REAL_MODEL=1 to run real-model smoke"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def embedder():
|
||||||
|
from app.dino.model import DinoEmbedder
|
||||||
|
|
||||||
|
embedder = DinoEmbedder("dinov2_vits14", device="cpu", image_size=224)
|
||||||
|
embedder.load()
|
||||||
|
return embedder
|
||||||
|
|
||||||
|
|
||||||
|
class TestRealModelSanity:
|
||||||
|
def test_embedding_shape_and_norm(self, embedder):
|
||||||
|
embeddings = embedder.embed([make_facade(seed=s) for s in (1, 2)])
|
||||||
|
assert embeddings.shape == (2, 384) # ViT-S/14 -> 384-dim CLS
|
||||||
|
norms = np.linalg.norm(embeddings, axis=1)
|
||||||
|
assert np.allclose(norms, 1.0, atol=1e-4)
|
||||||
|
|
||||||
|
def test_warp_closer_than_different_building(self, embedder):
|
||||||
|
# Деформированный тот же фасад ближе, чем фасад с другой планировкой.
|
||||||
|
# (Разный только шум при той же сетке окон модель закономерно считает
|
||||||
|
# тем же зданием — «другое здание» обязано отличаться структурно.)
|
||||||
|
base = make_facade(seed=1)
|
||||||
|
warped = warp_affine(base, seed=7, strength=0.08)
|
||||||
|
other_layout = make_facade(seed=99, floors=2, columns=3)
|
||||||
|
embeddings = embedder.embed([base, warped, other_layout])
|
||||||
|
sim_warp = float(embeddings[0] @ embeddings[1])
|
||||||
|
sim_other = float(embeddings[0] @ embeddings[2])
|
||||||
|
assert sim_warp > sim_other
|
||||||
|
|
||||||
|
def test_service_verify_pipeline(self, embedder):
|
||||||
|
from app.dino.service import DinoService
|
||||||
|
from conftest import make_config
|
||||||
|
|
||||||
|
service = DinoService(make_config(), embedder)
|
||||||
|
base = make_facade(seed=1)
|
||||||
|
outcome = service.verify(
|
||||||
|
encode(warp_affine(base, strength=0.08)),
|
||||||
|
[encode(base), encode(make_facade(seed=99, floors=2, columns=3))],
|
||||||
|
)
|
||||||
|
assert outcome.comparison.best_reference_index == 0
|
||||||
|
assert outcome.processing_ms > 0
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""UT: чистая логика сравнения — пороги, лучший эталон, границы зон."""
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.dino.comparison import ComparisonResult, cosine_similarities, decide
|
||||||
|
|
||||||
|
|
||||||
|
class TestDecide:
|
||||||
|
def test_match_on_and_above_threshold(self):
|
||||||
|
# UT: best >= THRESHOLD_MATCH -> match (граница включительно)
|
||||||
|
assert decide([0.55], 0.55, 0.40).verdict == "match"
|
||||||
|
assert decide([0.9], 0.55, 0.40).verdict == "match"
|
||||||
|
|
||||||
|
def test_uncertain_zone(self):
|
||||||
|
# UT: THRESHOLD_NO_MATCH <= best < THRESHOLD_MATCH -> uncertain
|
||||||
|
assert decide([0.5499], 0.55, 0.40).verdict == "uncertain"
|
||||||
|
assert decide([0.40], 0.55, 0.40).verdict == "uncertain" # граница снизу включительно
|
||||||
|
|
||||||
|
def test_no_match_below_threshold(self):
|
||||||
|
# UT: best < THRESHOLD_NO_MATCH -> no_match
|
||||||
|
result = decide([0.3999], 0.55, 0.40)
|
||||||
|
assert result.verdict == "no_match"
|
||||||
|
assert result.is_match is False
|
||||||
|
|
||||||
|
def test_best_reference_index_across_many(self):
|
||||||
|
# UT: эталоны с разных ракурсов — вердикт по максимуму
|
||||||
|
result = decide([0.10, 0.71, 0.30, 0.56], 0.55, 0.40)
|
||||||
|
assert result.verdict == "match"
|
||||||
|
assert result.best_reference_index == 1
|
||||||
|
assert result.best_similarity == pytest.approx(0.71)
|
||||||
|
assert result.similarities == (0.10, 0.71, 0.30, 0.56)
|
||||||
|
|
||||||
|
def test_empty_similarities_rejected(self):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
decide([], 0.55, 0.40)
|
||||||
|
|
||||||
|
def test_is_match_flag_consistency(self):
|
||||||
|
match = decide([0.99], 0.55, 0.40)
|
||||||
|
assert match.is_match is True
|
||||||
|
uncertain = decide([0.45], 0.55, 0.40)
|
||||||
|
assert uncertain.is_match is False
|
||||||
|
|
||||||
|
|
||||||
|
class TestCosineSimilarities:
|
||||||
|
def test_normalized_inputs_dot_product(self):
|
||||||
|
probe = np.array([1.0, 0.0, 0.0], dtype=np.float32)
|
||||||
|
references = np.array(
|
||||||
|
[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.6, 0.8, 0.0]], dtype=np.float32
|
||||||
|
)
|
||||||
|
sims = cosine_similarities(probe, references)
|
||||||
|
assert sims[0] == pytest.approx(1.0)
|
||||||
|
assert sims[1] == pytest.approx(0.0)
|
||||||
|
assert sims[2] == pytest.approx(0.6)
|
||||||
|
|
||||||
|
def test_self_similarity_is_one(self):
|
||||||
|
vector = np.array([[0.1, -0.2, 0.3, 0.9]], dtype=np.float32)
|
||||||
|
vector /= np.linalg.norm(vector)
|
||||||
|
assert cosine_similarities(vector[0], vector)[0] == pytest.approx(1.0, abs=1e-6)
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""UT: конфигурация — парсинг ENV, диапазоны и связные проверки (fail-fast)."""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.config import Config, ConfigError
|
||||||
|
|
||||||
|
|
||||||
|
class TestFromEnv:
|
||||||
|
def test_defaults(self, monkeypatch):
|
||||||
|
env_vars = [
|
||||||
|
"APP_API_KEY", "HOST", "PORT", "WORKERS", "DINO_MODEL_NAME", "DINO_DEVICE",
|
||||||
|
"DINO_IMAGE_SIZE", "TORCH_HOME", "MAX_IMAGE_MB", "MIN_IMAGE_DIM",
|
||||||
|
"MAX_REFERENCES_PER_REQUEST", "THRESHOLD_MATCH", "THRESHOLD_NO_MATCH", "LOG_LEVEL",
|
||||||
|
]
|
||||||
|
for name in env_vars:
|
||||||
|
monkeypatch.delenv(name, raising=False)
|
||||||
|
config = Config.from_env()
|
||||||
|
assert config.model_name == "dinov2_vits14"
|
||||||
|
assert config.device == "cpu"
|
||||||
|
assert config.image_size == 224
|
||||||
|
assert config.max_image_bytes == 10 * 1024 * 1024
|
||||||
|
assert config.max_references == 8
|
||||||
|
assert config.threshold_match == 0.55
|
||||||
|
assert config.threshold_no_match == 0.40
|
||||||
|
assert config.api_key is None
|
||||||
|
|
||||||
|
def test_override(self, monkeypatch):
|
||||||
|
monkeypatch.setenv("THRESHOLD_MATCH", "0.7")
|
||||||
|
monkeypatch.setenv("MAX_REFERENCES_PER_REQUEST", "3")
|
||||||
|
config = Config.from_env()
|
||||||
|
assert config.threshold_match == 0.7
|
||||||
|
assert config.max_references == 3
|
||||||
|
|
||||||
|
def test_empty_string_means_default(self, monkeypatch):
|
||||||
|
monkeypatch.setenv("APP_API_KEY", "")
|
||||||
|
monkeypatch.delenv("DINO_MODEL_NAME", raising=False)
|
||||||
|
assert Config.from_env().api_key is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestValidation:
|
||||||
|
def test_image_size_must_be_multiple_of_patch(self, monkeypatch):
|
||||||
|
monkeypatch.setenv("DINO_IMAGE_SIZE", "223")
|
||||||
|
with pytest.raises(ConfigError, match="кратно 14"):
|
||||||
|
Config.from_env()
|
||||||
|
|
||||||
|
def test_threshold_order(self, monkeypatch):
|
||||||
|
monkeypatch.setenv("THRESHOLD_MATCH", "0.4")
|
||||||
|
monkeypatch.setenv("THRESHOLD_NO_MATCH", "0.5")
|
||||||
|
with pytest.raises(ConfigError, match="THRESHOLD_NO_MATCH"):
|
||||||
|
Config.from_env()
|
||||||
|
|
||||||
|
def test_equal_thresholds_rejected(self, monkeypatch):
|
||||||
|
monkeypatch.setenv("THRESHOLD_MATCH", "0.5")
|
||||||
|
monkeypatch.setenv("THRESHOLD_NO_MATCH", "0.5")
|
||||||
|
with pytest.raises(ConfigError):
|
||||||
|
Config.from_env()
|
||||||
|
|
||||||
|
def test_non_numeric_rejected(self, monkeypatch):
|
||||||
|
monkeypatch.setenv("PORT", "http")
|
||||||
|
with pytest.raises(ConfigError, match="PORT"):
|
||||||
|
Config.from_env()
|
||||||
|
|
||||||
|
def test_range_enforced(self, monkeypatch):
|
||||||
|
monkeypatch.setenv("MAX_IMAGE_MB", "1000")
|
||||||
|
with pytest.raises(ConfigError, match="MAX_IMAGE_MB"):
|
||||||
|
Config.from_env()
|
||||||
|
|
||||||
|
def test_max_body_bytes_scales_with_limits(self):
|
||||||
|
from conftest import make_config
|
||||||
|
|
||||||
|
small = make_config(max_image_bytes=1024, max_references=2)
|
||||||
|
assert small.max_body_bytes == 3 * 1024 + 64 * 1024
|
||||||
Reference in New Issue
Block a user