feat: 다른 사이트에 붙이는 날씨각 위젯 — 누구나 붙이는 카드(/embed/card, 기본형·상세형, 배경 3종)와 사용 방법 페이지(/widget, 스크립트·iframe 코드)

- 카드: 군산각 카드를 옮겨 그림, 토끼 로딩, 실패하면 '날씨각에서 날씨 보기' 링크, 8초 제한, nginx 대체 화면, '자세히 보기' 버튼만 링크
- 크기: 폭은 자리에 맞춰 자동, 높이는 폭에 따라 비율대로(기본형 245~320px, 상세형 400~520px)
- 부하: 지역별 카드 데이터 5분 저장, 저장분이 비면 지역마다 한 요청만 새로 만듦, 노출 수는 Redis 에 쌓았다가 관리자 조회 때 DB(widget_view_daily)로 옮김
- 사용 방법 페이지: 지역(앱 지역은 바꾸지 않음)·모양·배경 고르기, 미리보기, 코드 복사. 들어오는 길은 문의 창 버튼(토스에서는 숨김)과 검색
- GA: 위젯_안내_보기, 위젯_옵션_고름, 위젯_코드_복사
- 문서: docs/위젯_운영.md, 백엔드 테스트 실행법(CLAUDE.md)
This commit is contained in:
skkim committed 2026-11-26 13:03:29 +09:00
1 parent 1a98adc155
commit dc8201e5f5
38 files changed
+4219 -28

No files matched your search

+1
View File
@@ -44,6 +44,7 @@ def anyio_backend():
_VOLATILE = (
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "comment_report", "user_block", "holiday", "solar_term", "users", "card_set", "card_image", "reel",
"widget_view_daily",
)
+421
View File
@@ -0,0 +1,421 @@
import asyncio
import json
import re
from datetime import datetime, timedelta
import pytest
from httpx import ASGITransport, AsyncClient
from redis.asyncio import Redis
from redis.exceptions import RedisError
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.database.model.models import Region, WeatherHourly
from common.enums import ErrorType, SlotTone
from common.utils.kma_time import KST, now_kst
from crud.region_crud import RegionCRUD
from crud.widget_crud import WidgetCRUD
from router.router import app
from router.v1.feed.protocol import Hero, HeroStat, Res_Feed, TopIndex
from services.embed_referer import OTHER_HOST, UNKNOWN_HOST
from services.embed_service import card_data, card_link, region_path, render_card, render_quiet
from services.feed_service import FeedService
from services.weather_service import Slot, TodayWeather
REGION = "1114000000"
CARD = "/v1/embed/card"
CARD_KEY = f"widget:card:v{embed_service.ASSET_VERSION}:{REGION}"
SITE = "co.webforai.kr"
NOW = datetime(2026, 11, 25, 9, tzinfo=KST)
_DATA = re.compile(r'<script type="application/json" id="wx-data">(.*?)</script>', re.S)
def client():
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
@pytest.fixture(autouse=True)
def _roomy_build_timeout(monkeypatch):
"""빈 시험 DB 에서 처음 만드는 카드는 날씨 수집부터 해서 8초를 넘기기도 한다. 시간 제한은 그것을 보는 시험만 줄인다."""
monkeypatch.setattr(embed_service, "CARD_BUILD_TIMEOUT_SEC", 60)
def _feed(now_at: datetime = NOW, weather_score=56, bubble: str = "포근해요") -> Res_Feed:
top1 = TopIndex(index_id=1, code="x", name="산책각", icon="x", score=80, rank=1, summary="걷기 좋아요")
hero = Hero(now_at=now_at, sky_mode="day", temp_c=8.2, weather_score=weather_score, bubble=bubble, top1=top1,
status=[HeroStat(icon="m", label="습도", value="보통", tone="normal")], moon_name="보름달", moon_pct=99)
return Res_Feed(hero=hero)
def _today(temp=0.0) -> TodayWeather:
at = datetime(2026, 11, 25, 0, tzinfo=KST)
row = WeatherHourly(forecast_at=at, temp_c=temp, sky=2, rain_type=1, rain_prob=0) if temp is not None else None
slot = Slot(at=at, row=row, icon="cloud" if row else "none", tone=SlotTone.NIGHT, note="")
return TodayWeather(region=Region(code="5213000000", short_name="군산시"), day=NOW.date(), issued_at=None, headline="", slots=[slot])
def _card(html: str) -> dict:
return json.loads(_DATA.search(html).group(1))
def _count_feed_calls(monkeypatch) -> list[str]:
"""FeedService.feed 를 부른 지역 코드를 모은다 (원래 동작은 그대로)."""
calls: list[str] = []
original = FeedService.feed
async def counting(self, region_code):
calls.append(region_code)
return await original(self, region_code)
monkeypatch.setattr(FeedService, "feed", counting)
return calls
def _views_key() -> str:
return f"widget:views:{now_kst().date().isoformat()}"
async def _views() -> dict[str, int]:
"""오늘 Redis 에 쌓인 노출 수, 호스트별 합 (관리자 API 가 DB 로 옮기기 전)."""
out: dict[str, int] = {}
for field, n in (await REDIS.conn.hgetall(_views_key())).items():
host = field.split("\t", 1)[0]
out[host] = out.get(host, 0) + int(n)
return out
async def _db_views() -> dict[str, int]:
err, views = await DB_SESSION_MNG.execute_lambda(lambda s: WidgetCRUD().views_since(s, now_kst().date()))
assert err is ErrorType.SUCCESS
return views
async def _cache_today(name: str) -> None:
cached = card_data(_feed(), _today(), name, NOW)
cached["today"]["day"] = now_kst().date().isoformat()
await REDIS.conn.set(CARD_KEY, json.dumps(cached, ensure_ascii=False))
def test_region_path():
assert region_path("5213000000") == "jeonbuk/gunsan"
assert region_path("0000000000") is None
def test_card_link():
assert card_link("jeonbuk/gunsan", "co.webforai.kr") == "/today/jeonbuk/gunsan?utm_source=widget&utm_medium=embed&utm_campaign=co.webforai.kr"
assert card_link(None, "unknown") == "/?utm_source=widget&utm_medium=embed&utm_campaign=unknown"
def test_card_data_shape():
assert card_data(_feed(), _today(), "군산시", NOW) == {
"name": "군산시",
"hero": {"now_at": "2026-11-25T09:00:00+09:00", "sky_mode": "day", "temp_c": 8.2, "weather_score": 56, "bubble": "포근해요",
"top1": {"summary": "걷기 좋아요"}, "status": [{"label": "습도", "value": "보통", "tone": "normal"}],
"moon_name": "보름달", "moon_pct": 99},
"today": {"day": "2026-11-25", "slots": [{"at": "2026-11-25T00:00:00+09:00", "temp_c": 0.0, "sky": 2, "rain_type": 1, "icon": "cloud"}]},
}
def test_card_data_none_when_stale_or_empty():
assert card_data(_feed(now_at=datetime(2026, 11, 24, 23, tzinfo=KST)), _today(), "군산시", NOW) is None
assert card_data(_feed(weather_score=None), _today(), "군산시", NOW) is None
assert card_data(_feed(), _today(temp=None), "군산시", NOW) is None
def test_render_card_escapes():
bubble = '</script><b>"x"'
link = card_link(None, "unknown")
html = render_card("side", "sky", card_data(_feed(bubble=bubble), _today(), "군산시", NOW), link)
assert "</script><b>" not in html
data = _card(html)
assert data["hero"]["bubble"] == bubble and data["link"] == link
assert 'class="wx wx-side wx-bg-sky"' in html
def test_card_markup():
link = card_link("jeonbuk/gunsan", "co.webforai.kr")
html = render_card("home", "sky", card_data(_feed(), _today(), "군산시", NOW), link)
head, body = html.split("<body>", 1)
assert '<meta name="color-scheme" content="light">' in head
assert '<span class="wx-t">군산시 날씨</span>' in body
assert 'class="wx-go"' in body and 'target="_blank"' in body and 'rel="noopener"' in body
assert f'href="{link.replace("&", "&amp;")}"' in body
assert "data-wx-dt" in body and "data-wx-b" in body
assert "/embed/card.js?v=" in body
assert f'<noscript><a class="wx-ns" href="{link.replace("&", "&amp;")}" target="_blank" rel="noopener">날씨각에서 날씨 보기 ›</a></noscript>' in body
def test_card_has_rabbit_loading():
html = render_card("side", "sky", card_data(_feed(), _today(), "군산시", NOW), card_link(None, "unknown"))
box = html.split('<div class="wx wx-side wx-bg-sky">', 1)[1].split('<div class="wx-b" data-wx-b></div>', 1)[0]
assert 'class="wx-load"' in box and 'role="status"' in box
assert '<img src="/icons/rabbit.webp" alt=""' in box
assert "날씨 불러오는 중…" in box
def test_failed_link_matches_quiet_words():
html = render_card("home", "sky", card_data(_feed(), _today(), "군산시", NOW), card_link(None, "unknown"))
assert "<span data-wx-gl>날씨각에서 날씨 보기 ›</span>" in html
def test_quiet_follows_bg():
link = card_link("jeonbuk/gunsan", "unknown")
dark, sky = render_quiet(link, "dark"), render_quiet(link, "sky")
assert 'class="wx-q-dark"' in dark and 'class="wx-q-sky"' in sky
assert "#1c3252" in dark and "#9fd3ff" in sky
for html in (dark, sky):
assert '<meta name="color-scheme" content="light">' in html
assert f'href="{link.replace("&", "&amp;")}" target="_blank" rel="noopener">날씨각에서 날씨 보기 ›</a>' in html
def test_card_markup_escapes_name():
html = render_card("side", "sky", card_data(_feed(), _today(), '<b>"군산"', NOW), card_link(None, "unknown"))
body = html.split("<body>", 1)[1].split('<script type="application/json"', 1)[0]
assert "<b>" not in body and "&lt;b&gt;&quot;군산&quot; 날씨" in body
@pytest.mark.anyio
async def test_any_site_gets_card(offline):
async with client() as c:
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": "https://evil.example/x"})
assert res.status_code == 200
assert 'id="wx-data"' in res.text and "wx-side" in res.text and "wx-bg-sky" in res.text
for header in ("content-security-policy", "x-frame-options", "set-cookie"):
assert header not in res.headers, header
assert res.headers["cache-control"] == "no-store"
assert res.headers["x-robots-tag"] == "noindex"
assert await _views() == {"evil.example": 1}
@pytest.mark.anyio
async def test_card_view_counts_in_redis_not_db(offline):
async with client() as c:
for kind in ("side", "home", "side"):
res = await c.get(CARD, params={"region": REGION, "type": kind}, headers={"Referer": f"https://{SITE}/s/stay"})
assert res.status_code == 200 and 'id="wx-data"' in res.text
assert await REDIS.conn.hgetall(_views_key()) == {f"{SITE}\tside": "2", f"{SITE}\thome": "1"}
assert await _db_views() == {}
@pytest.mark.anyio
async def test_bg_and_kind_classes(offline):
async with client() as c:
res = await c.get(CARD, params={"region": REGION, "type": "home", "bg": "dark"})
assert res.status_code == 200
assert "wx-home" in res.text and "wx-bg-dark" in res.text
@pytest.mark.anyio
async def test_no_referer_counts_unknown(offline):
async with client() as c:
res = await c.get(CARD, params={"region": REGION, "type": "side"})
assert res.status_code == 200
assert "utm_campaign=unknown" in _card(res.text)["link"]
assert await _views() == {UNKNOWN_HOST: 1}
@pytest.mark.anyio
async def test_self_preview_not_counted(offline):
async with client() as c:
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": "http://test/widget"})
assert res.status_code == 200 and 'id="wx-data"' in res.text
assert "utm_campaign=preview" in _card(res.text)["link"]
assert await _views() == {}
@pytest.mark.anyio
async def test_daily_host_cap(offline, monkeypatch):
monkeypatch.setattr(embed_service, "DAILY_HOST_CAP", 2)
async with client() as c:
for host in ("a.example", "b.example", "c.example", "a.example"):
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": f"https://{host}/"})
assert res.status_code == 200 and 'id="wx-data"' in res.text, host
assert await _views() == {"a.example": 2, "b.example": 1, OTHER_HOST: 1}
@pytest.mark.anyio
async def test_bad_input_is_quiet_html():
async with client() as c:
for params in ({"region": "abc", "type": "side"}, {"region": "9999999999", "type": "side"}, {"region": REGION, "type": "big"},
{"region": REGION, "type": "side", "bg": "pink"}):
res = await c.get(CARD, params=params)
assert res.status_code == 404, params
assert res.headers["content-type"].startswith("text/html"), params
assert "wx-data" not in res.text, params
# 위젯 유입이 GA 에서 구분되게 잘못된 입력도 utm 이 붙은 링크
assert f'href="{card_link(None, "unknown").replace("&", "&amp;")}"' in res.text, params
assert await _views() == {}
@pytest.mark.anyio
async def test_bad_bg_is_sky_quiet():
async with client() as c:
res = await c.get(CARD, params={"region": REGION, "type": "side", "bg": "pink"})
assert res.status_code == 404
assert 'class="wx-q-sky"' in res.text and "pink" not in res.text
@pytest.mark.anyio
async def test_slow_card_build_is_quiet(offline, monkeypatch):
original = FeedService.feed
async def slow(self, region_code):
await asyncio.sleep(30)
return await original(self, region_code)
monkeypatch.setattr(embed_service, "CARD_BUILD_TIMEOUT_SEC", 0.1)
monkeypatch.setattr(FeedService, "feed", slow)
async with client() as c:
res = await asyncio.wait_for(c.get(CARD, params={"region": REGION, "type": "side", "bg": "dark"},
headers={"Referer": f"https://{SITE}/s/stay"}), 5)
assert res.status_code == 200
assert "날씨각에서 날씨 보기" in res.text and "wx-data" not in res.text and 'class="wx-q-dark"' in res.text
assert await _views() == {}
# 시간을 넘겨 멈춘 작업이 남아 DB·Redis 를 망가뜨리지 않는다: 바로 다음 요청은 카드를 그린다
monkeypatch.setattr(FeedService, "feed", original)
monkeypatch.setattr(embed_service, "CARD_BUILD_TIMEOUT_SEC", 60)
async with client() as c:
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": f"https://{SITE}/s/stay"})
assert res.status_code == 200 and 'id="wx-data"' in res.text
assert await _views() == {SITE: 1}
@pytest.mark.anyio
async def test_feed_failure_is_quiet(offline, monkeypatch):
async def broken(self, region_code):
return ErrorType.DB_ERROR, None
monkeypatch.setattr(FeedService, "feed", broken)
async with client() as c:
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": f"https://{SITE}/s/stay"})
assert res.status_code == 200
assert "날씨각에서 날씨 보기" in res.text and "wx-data" not in res.text
assert res.headers["cache-control"] == "no-store"
assert await _views() == {}
@pytest.mark.anyio
async def test_feed_exception_is_quiet(offline, monkeypatch):
async def crash(self, region_code):
raise RuntimeError("feed down")
monkeypatch.setattr(FeedService, "feed", crash)
async with client() as c:
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": f"https://{SITE}/s/stay"})
assert res.status_code == 200
assert res.headers["content-type"].startswith("text/html")
assert "날씨각에서 날씨 보기" in res.text and "Internal Server Error" not in res.text
assert await _views() == {}
@pytest.mark.anyio
async def test_card_data_is_cached(offline, monkeypatch):
calls = _count_feed_calls(monkeypatch)
async with client() as c:
for _ in range(2):
res = await c.get(CARD, params={"region": REGION, "type": "side"})
assert res.status_code == 200 and 'id="wx-data"' in res.text
assert calls == [REGION]
@pytest.mark.anyio
async def test_cached_card_skips_region_lookup(monkeypatch):
await _cache_today("캐시된곳")
lookups: list[str] = []
async def counting_get(self, s, code):
lookups.append(code)
raise AssertionError("캐시가 있으면 지역을 조회하지 않는다")
monkeypatch.setattr(RegionCRUD, "get", counting_get)
async with client() as c:
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": f"https://{SITE}/"})
assert res.status_code == 200 and 'id="wx-data"' in res.text
assert "캐시된곳 날씨" in res.text
assert lookups == []
@pytest.mark.anyio
async def test_concurrent_misses_build_once(offline, monkeypatch):
# 빈 시험 DB 에서 처음 만드는 카드는 몇 초 걸려, 기다리는 쪽이 먼저 포기하지 않게 기다림을 넉넉히 준다
monkeypatch.setattr(embed_service, "_LOCK_WAIT_STEPS", 300)
calls: list[str] = []
original = FeedService.feed
async def slow_counting(self, region_code):
calls.append(region_code)
await asyncio.sleep(0.5) # 두 요청이 확실히 겹치게
return await original(self, region_code)
monkeypatch.setattr(FeedService, "feed", slow_counting)
async with client() as c:
results = await asyncio.gather(*[c.get(CARD, params={"region": REGION, "type": kind}) for kind in ("side", "home")])
for res in results:
assert res.status_code == 200 and 'id="wx-data"' in res.text
assert calls == [REGION]
assert await REDIS.conn.get(f"lock:widget:card:{REGION}") is None # 다 만든 뒤 잠금이 풀렸다
@pytest.mark.anyio
async def test_card_builds_without_lock_when_lock_fails(offline, monkeypatch):
calls = _count_feed_calls(monkeypatch)
original = Redis.set
async def lock_down(self, name, *a, **kw):
if str(name).startswith("lock:widget:card:"):
raise RedisError("redis down")
return await original(self, name, *a, **kw)
monkeypatch.setattr(Redis, "set", lock_down)
async with client() as c:
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": f"https://{SITE}/"})
assert res.status_code == 200 and 'id="wx-data"' in res.text
assert calls == [REGION]
@pytest.mark.anyio
async def test_stale_cached_card_is_rebuilt(offline, monkeypatch):
stale = card_data(_feed(), _today(), "군산시", NOW)
stale["today"]["day"] = (now_kst().date() - timedelta(days=1)).isoformat()
await REDIS.conn.set(CARD_KEY, json.dumps(stale, ensure_ascii=False))
calls = _count_feed_calls(monkeypatch)
async with client() as c:
res = await c.get(CARD, params={"region": REGION, "type": "side"})
assert res.status_code == 200 and 'id="wx-data"' in res.text
assert calls == [REGION]
assert _card(res.text)["today"]["day"] == now_kst().date().isoformat()
@pytest.mark.anyio
async def test_cached_card_key_has_asset_version(offline, monkeypatch):
cached = card_data(_feed(), _today(), "캐시된곳", NOW)
cached["today"]["day"] = now_kst().date().isoformat()
await REDIS.conn.set(CARD_KEY, json.dumps(cached, ensure_ascii=False))
async with client() as c:
res = await c.get(CARD, params={"region": REGION, "type": "side"})
assert res.status_code == 200 and "캐시된곳" in res.text
monkeypatch.setattr(embed_service, "ASSET_VERSION", "999") # 카드 파일이 바뀌면 예전 저장 데이터를 쓰지 않는다
res = await c.get(CARD, params={"region": REGION, "type": "side"})
assert res.status_code == 200 and 'id="wx-data"' in res.text
assert "캐시된곳" not in res.text
@pytest.mark.anyio
async def test_broken_cached_card_is_rebuilt(offline):
await REDIS.conn.set(CARD_KEY, "not json{")
async with client() as c:
res = await c.get(CARD, params={"region": REGION, "type": "side"})
assert res.status_code == 200 and 'id="wx-data"' in res.text
@pytest.mark.anyio
@pytest.mark.parametrize("error", [RedisError("redis down"), RuntimeError("count broke")])
async def test_count_failure_still_serves_card(offline, monkeypatch, error):
async def down(self, *a, **kw):
raise error
monkeypatch.setattr(Redis, "hincrby", down)
async with client() as c:
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": f"https://{SITE}/s/stay"})
assert res.status_code == 200 and 'id="wx-data"' in res.text
+39
View File
@@ -0,0 +1,39 @@
from services.embed_referer import UNKNOWN_HOST, normalize_host, view_host
OWN = frozenset({"weather.o2o.kr", "localhost:8080"})
def test_normalize_host_trims_address_to_host():
assert normalize_host("https://Co.WebForAI.kr/s/stay") == "co.webforai.kr"
assert normalize_host(" gunsan.webforai.kr ") == "gunsan.webforai.kr"
assert normalize_host("www.example.co.kr") == "www.example.co.kr"
assert normalize_host("my-shop.example.co.kr") == "my-shop.example.co.kr"
def test_normalize_host_rejects_what_cannot_go_in_a_header():
for bad in ("", "localhost", "exa mple.com", "a.com; script-src *", "https://a.com:8443", "1.2.3.4", "*.example.com", "a..com", "'self'", "-a.com", "a-.com", "a.-b.kr"):
assert normalize_host(bad) is None, bad
def test_normalize_host_length_limits():
assert normalize_host("a" * 63 + ".example.com") == "a" * 63 + ".example.com"
assert normalize_host("a" * 64 + ".example.com") is None
ok = ".".join(["a" * 63, "b" * 63, "c" * 63, "d" * 58]) + ".kr" # 253자
assert len(ok) == 253 and normalize_host(ok) == ok
assert normalize_host(".".join(["a" * 63, "b" * 63, "c" * 63, "d" * 59]) + ".kr") is None # 254자
def test_view_host_takes_site_host():
assert view_host("https://co.webforai.kr/s/stay", OWN) == "co.webforai.kr"
assert view_host("http://Blog.Example.com:8080/a", OWN) == "blog.example.com"
def test_view_host_self_is_not_counted():
assert view_host("https://weather.o2o.kr/widget", OWN) is None
assert view_host("http://localhost:8080/widget", OWN) is None
def test_view_host_unknown():
for bad in (None, "", "null", "about:blank", "android-app://com.example/", "https://", "not a url",
"https://1.2.3.4/", "https://a.com; x/", "https://" + "a" * 300 + ".com/"):
assert view_host(bad, OWN) == UNKNOWN_HOST, bad
+134
View File
@@ -0,0 +1,134 @@
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}]