diff --git a/ai-moderation/tests/test_image_api.py b/ai-moderation/tests/test_image_api.py new file mode 100644 index 0000000..5dcf758 --- /dev/null +++ b/ai-moderation/tests/test_image_api.py @@ -0,0 +1,160 @@ +import asyncio + +from pydantic import SecretStr + +from app.config.settings import settings +from app.core.body_limit import BodySizeLimitMiddleware +from app.core.concurrency import InferenceLimiter +from app.ml.model_manager import model_manager +from tests.conftest import image_bytes + +URL = "/api/v1/moderation/image" + + +def upload(client, data, content_type="image/jpeg", filename="photo.jpg", headers=None): + return client.post(URL, files={"file": (filename, data, content_type)}, headers=headers) + + +def test_contract_matches_refound_backend(client): + response = upload(client, image_bytes()) + assert response.status_code == 200 + # Поля, которые читает ImageModerationResponse в ReFound + assert response.json() == { + "approved": True, + "score": 1.0, + "reason": "OK", + "label": "normal", + "detected_labels": [] + } + + +def test_service_gets_downscaled_image(client, image_service): + upload(client, image_bytes(size=(4000, 3000))) + assert max(image_service.seen_sizes[0]) <= settings.MODERATION_MAX_SIDE + + +def test_unsupported_content_type(client): + response = upload(client, image_bytes(), content_type="image/gif") + assert response.status_code == 400 + assert response.json()["detail"] == "Unsupported image format" + + +def test_octet_stream_with_real_jpeg_is_accepted(client): + # Spring без расширения в имени файла шлёт application/octet-stream + response = upload(client, image_bytes(), content_type="application/octet-stream", filename="blob") + assert response.status_code == 200 + + +def test_spoofed_content_type_with_garbage(client): + response = upload(client, b"") + assert response.status_code == 400 + assert response.json()["detail"] == "Invalid image" + + +def test_empty_file(client): + response = upload(client, b"") + assert response.status_code == 400 + + +def test_truncated_image_is_400(client): + data = image_bytes(size=(800, 600)) + response = upload(client, data[: len(data) // 2]) + assert response.status_code == 400 + + +def test_too_small_image_has_error_body(client): + response = upload(client, image_bytes(size=(10, 10))) + assert response.status_code == 400 + assert response.json()["code"] == "INVALID_IMAGE" + + +def test_file_over_limit_is_413(client, monkeypatch): + monkeypatch.setattr(settings, "MAX_IMAGE_BYTES", 1000) + response = upload(client, b"\xff" * 2000) + assert response.status_code == 413 + + +def test_body_far_over_limit_rejected_by_content_length(client, monkeypatch): + monkeypatch.setattr(settings, "MAX_IMAGE_BYTES", 1000) + response = upload(client, b"\xff" * 200_000) + assert response.status_code == 413 + assert response.json()["code"] == "PAYLOAD_TOO_LARGE" + + +def test_unexpected_error_is_json_500_without_details(client, image_service): + image_service.error = RuntimeError("secret internal detail") + response = upload(client, image_bytes()) + assert response.status_code == 500 + assert response.json() == {"code": "INTERNAL_ERROR", "message": "Internal server error"} + + +def test_busy_service_returns_503(client, monkeypatch): + import app.routers.image_moderation_router as router_module + + limiter = InferenceLimiter("Image", 1) + monkeypatch.setattr(router_module, "image_limiter", limiter) + monkeypatch.setattr(settings, "INFERENCE_QUEUE_TIMEOUT", 0.01) + + with limiter.slot(): + response = upload(client, image_bytes()) + + assert response.status_code == 503 + assert response.json()["code"] == "SERVICE_BUSY" + assert response.headers["retry-after"] + + +def test_api_key_required_when_configured(client, monkeypatch): + monkeypatch.setattr(settings, "API_KEY", SecretStr("s3cret")) + + assert upload(client, image_bytes()).status_code == 401 + assert upload(client, image_bytes(), headers={"X-API-Key": "wrong"}).status_code == 401 + assert upload(client, image_bytes(), headers={"X-API-Key": "s3cret"}).status_code == 200 + # health-пробы без ключа + assert client.get("/health").status_code == 200 + + +def test_empty_api_key_in_env_means_disabled(): + from app.config.settings import Settings + + assert Settings(API_KEY="", HF_TOKEN=" ", _env_file=None).API_KEY is None + + +def test_health_and_ready(client, monkeypatch): + assert client.get("/health").json() == {"status": "ok"} + + monkeypatch.setattr(model_manager, "ready", False) + assert client.get("/ready").status_code == 503 + monkeypatch.setattr(model_manager, "ready", True) + assert client.get("/ready").status_code == 200 + + +def test_chunked_body_over_limit_is_cut_off(): + """Тело без Content-Length считается на лету и обрывается с 413.""" + app_read = [] + + async def app(scope, receive, send): + while True: + message = await receive() + app_read.append(len(message.get("body", b""))) + if not message.get("more_body"): + break + await send({"type": "http.response.start", "status": 200, "headers": []}) + await send({"type": "http.response.body", "body": b"ok"}) + + middleware = BodySizeLimitMiddleware(app, limit_for_path=lambda path: 100) + chunks = [b"x" * 60] * 10 + sent = [] + + async def receive(): + body = chunks.pop(0) + return {"type": "http.request", "body": body, "more_body": bool(chunks)} + + async def send(message): + sent.append(message) + + scope = {"type": "http", "path": "/api/v1/moderation/image", "headers": []} + asyncio.run(middleware(scope, receive, send)) + + assert sent[0]["status"] == 413 + assert len(sent) == 2 + assert sum(app_read) <= 120 # дальше второго куска не читали diff --git a/ai-moderation/tests/test_image_loader.py b/ai-moderation/tests/test_image_loader.py new file mode 100644 index 0000000..2b5a73f --- /dev/null +++ b/ai-moderation/tests/test_image_loader.py @@ -0,0 +1,80 @@ +import io + +import pytest +from PIL import Image + +from app.exceptions.invalid_image_exception import InvalidImageException +from app.moderation.image.loader import CorruptImageError, load_image +from app.moderation.image.validator import ImageValidator +from tests.conftest import image_bytes, png_header_only + +validator = ImageValidator() + + +@pytest.mark.parametrize("fmt", ["JPEG", "PNG", "WEBP"]) +def test_loads_allowed_formats_as_rgb(fmt): + image = load_image(image_bytes(fmt=fmt), validator) + assert image.mode == "RGB" + assert image.size == (200, 150) + + +def test_large_photo_is_downscaled_to_max_side(): + image = load_image(image_bytes(size=(4000, 3000)), validator, max_side=1280) + assert max(image.size) == 1280 + assert image.size == (1280, 960) + + +def test_exif_rotation_is_applied(): + exif = Image.Exif() + exif[0x0112] = 6 # Orientation: повернуть на 90° + data = image_bytes(size=(200, 100), exif=exif.tobytes()) + assert load_image(data, validator).size == (100, 200) + + +def test_transparent_pixels_become_white_not_hidden_rgb(): + data = image_bytes(fmt="PNG", mode="RGBA", color=(255, 0, 0, 0)) + image = load_image(data, validator) + assert image.getpixel((10, 10)) == (255, 255, 255) + + +def test_garbage_is_rejected(): + with pytest.raises(CorruptImageError): + load_image(b"definitely not an image", validator) + + +def test_disallowed_format_is_rejected_even_if_valid(): + with pytest.raises(CorruptImageError): + load_image(image_bytes(fmt="GIF", mode="P", color=1), validator) + + +def test_truncated_jpeg_is_client_error_not_500(): + data = image_bytes(size=(800, 600)) + with pytest.raises(CorruptImageError): + load_image(data[: len(data) // 2], validator) + + +def test_too_small_image_is_rejected(): + with pytest.raises(InvalidImageException): + load_image(image_bytes(size=(10, 10)), validator) + + +def test_extreme_aspect_ratio_is_rejected(): + with pytest.raises(InvalidImageException): + load_image(image_bytes(size=(60, 3000), fmt="PNG"), validator) + + +def test_pixel_bomb_over_limit_rejected_before_decoding(): + # 9000×9000 = 81 Мп: в пределах MAX_WIDTH/HEIGHT, но больше MAX_IMAGE_PIXELS + with pytest.raises(InvalidImageException): + load_image(png_header_only(9000, 9000), validator) + + +def test_huge_pixel_bomb_rejected_by_pillow_guard(): + with pytest.raises((CorruptImageError, InvalidImageException)): + load_image(png_header_only(60000, 60000), validator) + + +def test_validator_works_on_lazy_image_without_decoding(): + image = Image.open(io.BytesIO(png_header_only(9000, 9000))) + with pytest.raises(InvalidImageException): + validator.validate(image) diff --git a/ai-moderation/tests/test_image_service.py b/ai-moderation/tests/test_image_service.py new file mode 100644 index 0000000..f15188d --- /dev/null +++ b/ai-moderation/tests/test_image_service.py @@ -0,0 +1,72 @@ +from PIL import Image + +from app.ml.image.clip_prediction_result import ClipPredictionResult +from app.ml.image.image_prediction_result import ImagePredictionResult +from app.ml.image.weapon_detector import owlv2_target_size +from app.ml.image.weapon_prediction_result import WeaponPredictionResult +from app.moderation.image.validator import ImageValidator +from app.services.image_moderation_service import ImageModerationService + + +class Stub: + def __init__(self, result): + self.result = result + self.calls = 0 + + def predict(self, image): + self.calls += 1 + return self.result + + +def make_service(nsfw=("normal", 0.99), weapon=None, clip_labels=()): + nsfw_stub = Stub(ImagePredictionResult(label=nsfw[0], score=nsfw[1], approved=False)) + weapon_stub = Stub(weapon or WeaponPredictionResult(label="normal", score=0.0)) + clip_stub = Stub(ClipPredictionResult( + label=clip_labels[0] if clip_labels else "a normal photo", + score=0.9, + detected_labels=list(clip_labels), + scores={} + )) + service = ImageModerationService( + classifier=nsfw_stub, + validator=ImageValidator(), + clip_classifier=clip_stub, + weapon_detector=weapon_stub + ) + return service, nsfw_stub, weapon_stub, clip_stub + + +IMAGE = Image.new("RGB", (300, 200)) + + +def test_clean_image_is_approved(): + service, *_ = make_service() + result = service.moderate(IMAGE) + assert (result.approved, result.reason, result.label) == (True, "OK", "normal") + + +def test_nsfw_short_circuits_other_models(): + service, _, weapon, clip = make_service(nsfw=("nsfw", 0.95)) + result = service.moderate(IMAGE) + assert (result.approved, result.reason, result.detected_labels) == (False, "NSFW", ["nsfw"]) + assert weapon.calls == 0 and clip.calls == 0 + + +def test_weapon_is_forbidden(): + weapon = WeaponPredictionResult(label="a gun", score=0.7, detected_labels=["a gun"], box_count=1) + service, *_ , clip = make_service(weapon=weapon) + result = service.moderate(IMAGE) + assert (result.approved, result.reason, result.detected_labels) == (False, "FORBIDDEN_CONTENT", ["a gun"]) + assert clip.calls == 0 + + +def test_clip_forbidden_label(): + service, *_ = make_service(clip_labels=["a photo containing drugs"]) + result = service.moderate(IMAGE) + assert (result.approved, result.reason) == (False, "FORBIDDEN_CONTENT") + + +def test_owlv2_boxes_scaled_to_padded_square(): + # OWLv2 паддит до квадрата: обе оси масштабируются по длинной стороне + assert owlv2_target_size(1280, 720) == (1280, 1280) + assert owlv2_target_size(600, 900) == (900, 900) diff --git a/ai-moderation/tests/test_profanity.py b/ai-moderation/tests/test_profanity.py new file mode 100644 index 0000000..89d0e1f --- /dev/null +++ b/ai-moderation/tests/test_profanity.py @@ -0,0 +1,45 @@ +import time + +import pytest + +from app.core.dependencies import get_profanity_detector + + +@pytest.fixture(scope="module") +def detector(): + return get_profanity_detector() + + +@pytest.mark.parametrize("text", [ + "Потерял кошелёк в парке, нашедшему вознаграждение", + "Найдена собака, рыжая, с ошейником", + "Потерялись ключи с брелоком, 3 шт., район 6 мкр", + "Буфера у машины помяты, опущенный козырёк", + "Lost black wallet near the station", + "", +]) +def test_clean_texts(detector, text): + assert detector.detect(text) == [] + + +@pytest.mark.parametrize("text", [ + "бля", + "БЛЯ, где мой телефон", + "иди нахуй", + "6ля", # цифра вместо буквы, есть в словаре + "fuck", # транслит/латиница из словаря + "xуй", # латинская x вместо кириллической х + "бля123", # мусор после слова + "бляха-муха", # слово через дефис из словаря + "ёбаный", # ё/е +]) +def test_profanity_detected(detector, text): + assert detector.detect(text), text + + +def test_long_text_is_fast(detector): + # Раньше каждое слово сравнивалось со всеми ~7 тыс. словами словаря + text = "обычный текст объявления о находке " * 140 + start = time.perf_counter() + assert detector.detect(text[:5000]) == [] + assert time.perf_counter() - start < 1.0 diff --git a/ai-moderation/tests/test_text_api.py b/ai-moderation/tests/test_text_api.py new file mode 100644 index 0000000..c6d2c66 --- /dev/null +++ b/ai-moderation/tests/test_text_api.py @@ -0,0 +1,45 @@ +from app.config.settings import settings + +URL = "/api/v1/moderation/text" + + +def test_clean_text_contract(client): + response = client.post(URL, json={"text": "Потерял кошелёк в парке Горького, нашедшему вознаграждение"}) + assert response.status_code == 200 + # Поля, которые читает ModerationResponse в ReFound + assert response.json() == {"approved": True, "score": 0.01, "reason": "OK"} + + +def test_profanity_is_rejected(client): + response = client.post(URL, json={"text": "Нашёл кошелёк, бля"}) + body = response.json() + assert response.status_code == 200 + assert body["approved"] is False + assert body["reason"] == "PROFANITY" + + +def test_toxic_text_is_rejected(client, text_classifier): + text_classifier.score = 0.99 + body = client.post(URL, json={"text": "какой-то текст"}).json() + assert body == {"approved": False, "score": 0.99, "reason": "TOXIC"} + + +def test_whitespace_text_is_400(client): + response = client.post(URL, json={"text": " "}) + assert response.status_code == 400 + assert response.json()["code"] == "INVALID_TEXT" + + +def test_empty_and_too_long_text_are_422(client): + assert client.post(URL, json={"text": ""}).status_code == 422 + too_long = "а" * (settings.TEXT_MAX_LENGTH + 1) + assert client.post(URL, json={"text": too_long}).status_code == 422 + + +def test_large_json_body_is_413(client): + response = client.post( + URL, + content=b'{"text": "' + b"a" * (settings.MAX_REQUEST_BYTES + 10) + b'"}', + headers={"content-type": "application/json"} + ) + assert response.status_code == 413 diff --git a/ai-moderation/tests/test_text_classifier.py b/ai-moderation/tests/test_text_classifier.py new file mode 100644 index 0000000..9e488af --- /dev/null +++ b/ai-moderation/tests/test_text_classifier.py @@ -0,0 +1,65 @@ +from types import SimpleNamespace + +import torch + +from app.ml import text_classifier as module +from app.ml.text_classifier import TextClassifier, split_windows, toxic_label_index + +CLS, SEP, TOXIC_TOKEN = 101, 102, 999 + + +def test_toxic_label_index(): + assert toxic_label_index({0: "LABEL_0", 1: "LABEL_1"}) == 1 + assert toxic_label_index({0: "toxic", 1: "neutral"}) == 0 + assert toxic_label_index({0: "non-toxic", 1: "toxic"}) == 1 + + +def test_split_windows_cover_whole_text(): + ids = list(range(300)) + windows = split_windows(ids, size=126, overlap=32) + assert all(len(window) <= 126 for window in windows) + assert windows[0][0] == 0 + assert windows[-1][-1] == 299 + covered = {token for window in windows for token in window} + assert covered == set(ids) + + +def test_short_text_is_single_window(): + assert split_windows([1, 2, 3], size=126, overlap=32) == [[1, 2, 3]] + + +class FakeTokenizer: + pad_token_id = 0 + + def __call__(self, text, **kwargs): + if not text: + return {"input_ids": [CLS, SEP]} + # 600 «нейтральных» токенов и один токсичный в самом конце + return {"input_ids": [5] * 600 + [TOXIC_TOKEN]} + + +class FakeModel: + config = SimpleNamespace(id2label={0: "LABEL_0", 1: "LABEL_1"}) + + def __init__(self): + self.batch = None + + def __call__(self, input_ids, attention_mask): + self.batch = input_ids + toxic = (input_ids == TOXIC_TOKEN).any(dim=1).float() * 8 - 4 + return SimpleNamespace(logits=torch.stack([-toxic, toxic], dim=1)) + + +def test_toxic_tail_of_long_text_is_seen(monkeypatch): + model = FakeModel() + monkeypatch.setattr(module.model_manager, "text_tokenizer", FakeTokenizer()) + monkeypatch.setattr(module.model_manager, "text_model", model) + monkeypatch.setattr(module.model_manager, "device", torch.device("cpu")) + + result = TextClassifier().predict("длинный текст") + + assert model.batch.shape[0] > 1 + assert model.batch.shape[1] <= module.MAX_TOKENS + assert (model.batch[:, 0] == CLS).all() + assert result.score > 0.99 + assert result.label == "LABEL_1"