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

+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