150 lines
6.4 KiB
Python
150 lines
6.4 KiB
Python
"""Юнит-тесты блоб-кодека — 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
|
||
)
|