DispelEvilBot/tests/test_admin_logs.py

121 lines
3.8 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.

"""Тесты раздела «Логи» (Postgres не требуется — чтение подменяется)."""
from __future__ import annotations
from datetime import date, datetime
from typing import Any
import pytest
from common.analytics import read as analytics_read
EVENT: dict[str, Any] = {
"event_time": datetime(2026, 10, 18, 17, 0, 0), # UTC без tz — как отдаёт psycopg
"event_type": "command",
"user_id": 42,
"username": "test_user",
"chat_id": -100123,
"payload": {"command": "инфо", "args_count": 0},
"bot_version": "0.4.8",
"prod": False,
}
MESSAGE: dict[str, Any] = {
"day": date(2026, 10, 18),
"user_id": 42,
"username": "test_user",
"chat_id": -100123,
"count": 17,
}
@pytest.fixture
def fake_read(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
state: dict[str, Any] = {"total": 1, "messages_total": 1}
async def fetch_events(settings: Any, **kwargs: Any) -> tuple[list[dict[str, Any]], int]:
state["kwargs"] = kwargs
return [EVENT], state["total"]
async def fetch_messages(settings: Any, **kwargs: Any) -> tuple[list[dict[str, Any]], int]:
state["message_kwargs"] = kwargs
return [MESSAGE], state["messages_total"]
monkeypatch.setattr(analytics_read, "fetch_events", fetch_events)
monkeypatch.setattr(analytics_read, "fetch_messages", fetch_messages)
return state
def test_logs_page(fake_read: dict[str, Any], client_factory) -> None:
response = client_factory().get("/logs")
assert response.status_code == 200
assert "command" in response.text
assert "@test_user" in response.text
assert "инфо" in response.text
assert "20:00:00" in response.text # 17:00 UTC -> 20:00 МСК
def test_logs_messages_view(fake_read: dict[str, Any], client_factory) -> None:
response = client_factory().get("/logs", params={"view": "messages"})
assert response.status_code == 200
assert "Сообщения по дням" in response.text
assert "18.10.2026" in response.text
assert "17" in response.text
assert fake_read["message_kwargs"]["limit"] == 50
def test_logs_filters_passed(fake_read: dict[str, Any], client_factory) -> None:
client_factory().get(
"/logs",
params={
"event_type": "command",
"user": "42",
"date_from": "2026-10-01",
"date_to": "2026-10-18",
},
)
assert fake_read["kwargs"] == {
"event_type": "command",
"user": "42",
"date_from": "2026-10-01",
"date_to": "2026-10-18",
"limit": 50,
"offset": 0,
}
def test_logs_pagination(fake_read: dict[str, Any], client_factory) -> None:
fake_read["total"] = 120
response = client_factory().get("/logs", params={"page": "2"})
assert "Страница 2 из 3" in response.text
assert fake_read["kwargs"]["offset"] == 50
def test_logs_postgres_error(client_factory, monkeypatch: pytest.MonkeyPatch) -> None:
async def fetch_events(settings: Any, **kwargs: Any) -> tuple[list[dict[str, Any]], int]:
raise RuntimeError("Postgres недоступен")
monkeypatch.setattr(analytics_read, "fetch_events", fetch_events)
response = client_factory().get("/logs")
assert response.status_code == 200
assert "Postgres недоступен" in response.text
def test_logs_bad_date(client_factory, monkeypatch: pytest.MonkeyPatch) -> None:
async def fetch_events(settings: Any, **kwargs: Any) -> tuple[list[dict[str, Any]], int]:
raise ValueError("bad date")
monkeypatch.setattr(analytics_read, "fetch_events", fetch_events)
response = client_factory().get("/logs", params={"date_from": "18.10.2026"})
assert response.status_code == 200
assert "формате ГГГГ-ММ-ДД" in response.text