161 lines
5.4 KiB
Python
161 lines
5.4 KiB
Python
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"<?php echo 1; ?>")
|
||
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 # дальше второго куска не читали
|