Files
o2o-weather/backend/tests/test_embed.py
T
skkim 11ce52a2d1 fix: umami 스크립트를 날씨각에 복사해 두고 써서 외부 스크립트를 직접 실행하지 않게 — 무결성 확인(SRI) 대신
- analytics.webforai.kr/script.js 를 frontend/public/embed/umami.js 로 복사(2026-11-26), 기록은 data-host-url 로 같은 umami 서버에 보냄
- 날씨각 웹(index.html)과 위젯 카드 모두 복사본을 씀. umami 서버가 다른 사이트의 파일 확인 요청(CORS)을 허락하지 않아 SRI 는 쓸 수 없음
- 복사본은 린트에서 뺌, 운영 문서에 다시 받는 법
2026-11-26 15:32:58 +09:00

482 lines
22 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 asyncio
import json
import re
from datetime import datetime, timedelta
from pathlib import Path
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 = "포근해요", sky_mode: str = "day",
stories: tuple[TopIndex, ...] = ()) -> 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=sky_mode, temp_c=8.2, weather_score=weather_score, bubble=bubble, top1=top1,
weather_slots={"morning": 40, "day": 56, "evening": 61, "night": 30},
status=[HeroStat(icon="m", label="습도", value="보통", tone="normal")], moon_name="보름달", moon_pct=99)
return Res_Feed(hero=hero, stories=list(stories))
def _gak(index_id: int, name: str, slots: dict[str, int], ranks: dict[str, int]) -> TopIndex:
return TopIndex(index_id=index_id, code=f"g{index_id}", name=name, icon="x", score=50, rank=index_id, slots=slots, slot_ranks=ranks)
# 아침 1위 러닝각 64점(순위가 점수보다 앞선다), 낮 1위 러닝각 65점, 저녁 1위 산책각 72점, 밤은 구간 값이 있는 각이 없다
_GAKS = (
_gak(1, "러닝각", {"morning": 64, "day": 65, "evening": 70}, {"morning": 1, "day": 1, "evening": 2}),
_gak(2, "산책각", {"morning": 90, "day": 50, "evening": 72}, {"morning": 2, "day": 2, "evening": 1}),
_gak(3, "별보기각", {}, {"night": 1}), # 순위만 있고 점수가 없으면 고르지 않는다 (앱 atSlot 과 같음)
)
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,
"weather_slots": {"morning": 40, "day": 56, "sunset": 61, "night": 30}, "bubble": "포근해요",
"top1": {"summary": "걷기 좋아요"}, "status": [{"label": "습도", "value": "보통", "tone": "normal"}],
"moon_name": "보름달", "moon_pct": 99},
"picks": {},
"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_picks_follow_app_bubble_rule():
# 지금은 낮: 낮 칸 머리말은 '지금', 다른 칸은 '오늘 아침' 등. 65점 이상이면 각 이름, 64점이면 쉬어 가요. 밤은 고를 각이 없어 빠진다
assert card_data(_feed(stories=_GAKS), _today(), "군산시", NOW)["picks"] == {
"morning": {"bubble": "오늘 아침은 쉬어 가요"},
"day": {"bubble": "지금은 러닝각!"},
"sunset": {"bubble": "오늘 저녁은 산책각!"},
}
def test_card_picks_now_prefix_follows_sky_mode():
picks = card_data(_feed(sky_mode="sunset", stories=_GAKS), _today(), "군산시", NOW)["picks"]
assert picks["sunset"]["bubble"] == "지금은 산책각!"
assert picks["day"]["bubble"] == "오늘 낮은 러닝각!"
def test_card_picks_tie_keeps_feed_order():
tied = (_gak(1, "러닝각", {"night": 70}, {"night": 1}), _gak(2, "산책각", {"night": 80}, {"night": 1}))
assert card_data(_feed(stories=tied), _today(), "군산시", NOW)["picks"] == {"night": {"bubble": "오늘 밤은 러닝각!"}}
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_umami_sends_widget_card_page():
data = card_data(_feed(), _today(), "군산시", NOW)
assert "/embed/umami.js" not in render_card("side", "sky", data, card_link(None, "preview"))
html = render_card("home", "dark", data, card_link(None, "unknown"), track=True)
# 외부 스크립트를 직접 실행하지 않는다: 날씨각에 복사해 둔 스크립트를 쓰고 기록만 umami 서버로 보낸다
tag = re.search(r'<script defer src="/embed/umami\.js"[^>]*></script>', html).group(0)
assert 'data-host-url="https://analytics.webforai.kr"' in tag
assert 'data-auto-track="false"' in tag and 'data-domains="weather.o2o.kr,www.weather.o2o.kr"' in tag
assert "&quot;/widget-card&quot;" in tag and "날씨 위젯 · 상세형" in tag
assert 'src="https://analytics.webforai.kr' not in html
assert "날씨 위젯 · 기본형" in render_card("side", "sky", data, card_link(None, "unknown"), track=True)
def test_card_umami_matches_index_html():
frontend = Path(__file__).resolve().parents[2] / "frontend"
index = (frontend / "index.html").read_text(encoding="utf-8")
assert f'data-website-id="{embed_service.UMAMI_WEBSITE_ID}"' in index
assert f'src="{embed_service.UMAMI_SRC}"' in index and f'data-host-url="{embed_service.UMAMI_HOST}"' in index
assert (frontend / "public" / embed_service.UMAMI_SRC.lstrip("/")).is_file()
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 "/embed/umami.js" in res.text
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 "/embed/umami.js" not in res.text
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