from datetime import timedelta import pytest from httpx import ASGITransport, AsyncClient from sqlalchemy.exc import SQLAlchemyError import services.embed_service as embed_service from common.cache.redis_client import REDIS from common.database.db_session_manager import DB_SESSION_MNG from common.enums import ErrorType from common.utils.kma_time import now_kst from config.settings import settings from crud.widget_crud import WidgetCRUD from router.router import app from services.embed_referer import UNKNOWN_HOST KEY = "test-admin-key" H = {"X-Admin-Key": KEY} VIEWS = "/v1/admin/widget/views" CARD = "/v1/embed/card" REGION = "1114000000" def client(): return AsyncClient(transport=ASGITransport(app=app), base_url="http://test") def _key(days_ago: int = 0) -> str: return f"widget:views:{(now_kst().date() - timedelta(days=days_ago)).isoformat()}" async def _redis_view_keys() -> list[str]: return sorted([k async for k in REDIS.conn.scan_iter(match="widget:views*")]) async def _get_views(c) -> dict: res = (await c.get(VIEWS, headers=H)).json() assert res["result"]["code"] == ErrorType.SUCCESS.value return res @pytest.mark.anyio async def test_widget_views_need_key(monkeypatch): monkeypatch.setattr(settings, "admin_api_key", KEY) async with client() as c: for headers in ({}, {"X-Admin-Key": "wrong"}): assert (await c.get(VIEWS, headers=headers)).status_code == 401 @pytest.mark.anyio async def test_widget_views_sums_by_host(monkeypatch): monkeypatch.setattr(settings, "admin_api_key", KEY) crud = WidgetCRUD() today = now_kst().date() views = [ (today, "co.webforai.kr", "side"), (today, "co.webforai.kr", "side"), (today - timedelta(days=6), "co.webforai.kr", "home"), (today - timedelta(days=7), "co.webforai.kr", "side"), (today, "blog.example.com", "side"), (today, UNKNOWN_HOST, "side"), ] for day, host, kind in views: err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s, d=day, h=host, k=kind: crud.add_views(s, d, {(h, k): 1})) assert err is ErrorType.SUCCESS async with client() as c: res = await _get_views(c) assert res["items"] == [ {"host": "co.webforai.kr", "views_7d": 3, "views_30d": 4}, {"host": UNKNOWN_HOST, "views_7d": 1, "views_30d": 1}, {"host": "blog.example.com", "views_7d": 1, "views_30d": 1}, ] assert res["total_7d"] == 5 and res["total_30d"] == 6 @pytest.mark.anyio async def test_widget_views_moves_redis_counts_to_db_once(monkeypatch): monkeypatch.setattr(settings, "admin_api_key", KEY) crud = WidgetCRUD() today = now_kst().date() err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: crud.add_views(s, today, {("a.example", "side"): 5})) assert err is ErrorType.SUCCESS await REDIS.conn.hset(_key(), mapping={"a.example\tside": 2, "a.example\thome": 1, f"{UNKNOWN_HOST}\tside": 4}) await REDIS.conn.hset(_key(10), mapping={"a.example\tside": 7}) # 이전 요청이 옮기다 남긴 임시 키도 함께 옮긴다 await REDIS.conn.hset(f"widget:views-flush:{today.isoformat()}:leftover", mapping={"b.example\tside": 3}) async with client() as c: first = await _get_views(c) assert await _redis_view_keys() == [] second = await _get_views(c) # 두 번 불러도 두 번 더하지 않는다 for res in (first, second): assert res["items"] == [ {"host": "a.example", "views_7d": 8, "views_30d": 15}, {"host": UNKNOWN_HOST, "views_7d": 4, "views_30d": 4}, {"host": "b.example", "views_7d": 3, "views_30d": 3}, ] assert res["total_7d"] == 15 and res["total_30d"] == 22 @pytest.mark.anyio async def test_widget_views_keeps_redis_counts_when_db_write_fails(monkeypatch): monkeypatch.setattr(settings, "admin_api_key", KEY) original = WidgetCRUD.add_views async def broken(self, s, day, counts): raise SQLAlchemyError("db down") await REDIS.conn.hset(_key(), mapping={"a.example\tside": 2}) monkeypatch.setattr(WidgetCRUD, "add_views", broken) async with client() as c: await c.get(VIEWS, headers=H) # 수치는 원래 키로 돌아가 있고, 임시 키는 남지 않는다 assert await _redis_view_keys() == [_key()] assert await REDIS.conn.hgetall(_key()) == {"a.example\tside": "2"} monkeypatch.setattr(WidgetCRUD, "add_views", original) res = await _get_views(c) assert res["items"] == [{"host": "a.example", "views_7d": 2, "views_30d": 2}] assert await _redis_view_keys() == [] @pytest.mark.anyio async def test_card_views_reach_admin_api(offline, monkeypatch): monkeypatch.setattr(settings, "admin_api_key", KEY) monkeypatch.setattr(embed_service, "CARD_BUILD_TIMEOUT_SEC", 60) # 빈 시험 DB 의 첫 카드는 8초를 넘기기도 한다 (test_embed 와 같음) async with client() as c: for _ in range(2): res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": "https://blog.example.com/post"}) assert res.status_code == 200 and 'id="wx-data"' in res.text views = await _get_views(c) assert views["items"] == [{"host": "blog.example.com", "views_7d": 2, "views_30d": 2}] # 옮긴 뒤 새 요청은 새 키에 다시 쌓인다 await c.get(CARD, params={"region": REGION, "type": "home"}, headers={"Referer": "https://blog.example.com/post"}) assert await REDIS.conn.hgetall(_key()) == {"blog.example.com\thome": "1"} views = await _get_views(c) assert views["items"] == [{"host": "blog.example.com", "views_7d": 3, "views_30d": 3}]