Files
han-app/codebase/backend/message-safety/tests/test_service.py
T

104 lines
3.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import os
import random
import uuid
os.environ.setdefault("MESSAGE_SAFETY_SERVICE_TOKEN", "test-service-token-32-characters")
import httpx
import pytest
from app.main import Settings, create_app, normalize
class Store:
def __init__(self):
self.tasks = {}
async def reserve(self, message_id, fingerprint, task_id, ttl):
prior = self.tasks.get(message_id)
if prior and prior[0] != fingerprint:
raise ValueError("conflict")
if prior:
return prior[1]
self.tasks[message_id] = (fingerprint, task_id)
return task_id
async def poll(self, task_id):
return 1 if any(value[1] == task_id for value in self.tasks.values()) else None
async def ready(self):
return True
async def close(self):
pass
class SequenceRandom(random.Random):
def __init__(self):
self.values = iter(("pending", "allow", "final_error"))
def choice(self, _):
return next(self.values)
@pytest.mark.asyncio
async def test_rules_auth_and_independent_poll():
settings = Settings(
app_env="test",
message_safety_service_token="test-service-token-32-characters",
)
app = create_app(settings, Store(), SequenceRandom())
headers = {"X-Service-Token": settings.message_safety_service_token}
message_id = str(uuid.uuid4())
async with app.router.lifespan_context(app):
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app), base_url="http://test"
) as client:
assert (
await client.post(
"/internal/safety/v1/messages/check",
json={
"message_id": str(uuid.uuid4()),
"content_kind": "text",
"text": " Файл",
},
headers=headers,
)
).status_code == 403
pending = await client.post(
"/internal/safety/v1/messages/check",
json={"message_id": message_id, "content_kind": "text", "text": "\u00a0 дней"},
headers=headers,
)
assert pending.status_code == 203
task_id = pending.json()["task_id"]
assert [
(
await client.get(
f"/internal/safety/v1/messages/tasks/{task_id}", headers=headers
)
).status_code
for _ in range(3)
] == [203, 200, 400]
assert (
await client.post(
"/internal/safety/v1/messages/check",
json={
"message_id": str(uuid.uuid4()),
"content_kind": "text",
"text": "документ",
},
headers=headers,
)
).status_code == 200
assert (
await client.post(
"/internal/safety/v1/messages/check",
json={"message_id": str(uuid.uuid4()), "content_kind": "text", "text": "ok"},
)
).status_code == 401
def test_normalization():
assert normalize("\r\n\u00a0 дней") == "7 дней"