Files

169 lines
9.4 KiB
Python

from datetime import date, datetime
import pytest
from httpx import ASGITransport, AsyncClient
from common.utils.kma_time import KST
from common.database.model.models import WeatherHourly
from router.router import app
from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex
from services import seo_service
from services.seo_service import SeoService, day_summary, fill, today_copy, today_line, tomorrow_copy, tomorrow_line
REGION = "1114000000"
TEMPLATE = (
'<html><head><meta name="description" content="소개" /><meta property="og:description" content="소개" />'
f'<meta name="region-code" content="{REGION}" />\n </head><body><main><h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>소개 글</p></main></body></html>'
)
def _top(name: str, score: int, ranks: dict[str, int]) -> TopIndex:
return TopIndex(index_id=1, code="x", name=name, icon="x", score=score, rank=1, slot_ranks=ranks)
def _feed() -> Res_Feed:
stories = [_top("러닝각", 80, {"morning": 1, "day": 2}), _top("빨래각", 77, {"day": 1}), _top("별보기각", 70, {"night": 1})]
hero = Hero(now_at=datetime(2026, 10, 14, 9), sky_mode="morning", temp_c=13.4,
status=[HeroStat(icon="m", label="습도", value="보통", tone="normal"), HeroStat(icon="m", label="미세먼지", value="좋음", tone="normal")])
return Res_Feed(hero=hero, stories=stories, bands=Bands(top5=stories[:2]))
def _hour(h: int, temp: float, sky: int = 1, rain: int = 1, prob: int = 0) -> WeatherHourly:
return WeatherHourly(forecast_at=datetime(2026, 10, 14, h, tzinfo=KST), temp_c=temp, sky=sky, rain_type=rain, rain_prob=prob)
def test_day_summary_min_max_prob_and_daytime_sky():
rows = [_hour(3, 8.6, sky=4), _hour(9, 12, sky=3), _hour(12, 19.5, sky=1, prob=10), _hour(15, 20.2, sky=1), _hour(21, 14)]
assert day_summary(rows) == "최저 9°·최고 20°, 강수확률 10%, 맑음."
assert day_summary([_hour(12, 15, rain=2, prob=70)]) == "최저 15°·최고 15°, 강수확률 70%, 비."
def test_today_line_has_day_now_slot_firsts_and_sunset():
line = today_line(_feed(), [_hour(12, 19.5, prob=10)], datetime(2026, 10, 14, 17, 52, tzinfo=KST))
assert line == "최저 20°·최고 20°, 강수확률 10%, 맑음. 지금 13°, 습도 보통·미세먼지 좋음. 아침은 러닝각, 낮은 빨래각, 밤은 별보기각. 해 지는 시각 오후 5시 52분."
def test_fill_puts_today_into_description_and_body():
html = fill(TEMPLATE, _feed(), [], "서울 중구", None)
assert html.count('content="지금 13°, 습도 보통·미세먼지 좋음.') == 2
assert "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>지금 13°" in html
assert "<li>러닝각 80점</li><li>빨래각 77점</li>" in html
def test_fill_keeps_template_when_no_weather():
assert fill(TEMPLATE, Res_Feed(), [], "서울 중구", None) == TEMPLATE
@pytest.mark.anyio
async def test_today_page_fills_real_feed(offline, monkeypatch):
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset())
async def template(self, path):
return TEMPLATE if path == "today/seoul/jung" else None
monkeypatch.setattr(SeoService, "template", template)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
page = await client.get("/v1/seo/today/seoul/jung")
missing = await client.get("/v1/seo/today/seoul/nowhere")
assert page.status_code == 200 and "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>최저 " in page.text and "지금 20°" in page.text
assert "해 지는 시각 오후" in page.text and "<ol><li>" in page.text
assert missing.status_code == 404
@pytest.mark.anyio
async def test_gu_page_of_city_has_its_own_address(offline, monkeypatch):
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset())
async def template(self, path):
return TEMPLATE if path == "today/gyeonggi/seongnam/bundang" else None
monkeypatch.setattr(SeoService, "template", template)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
page = await client.get("/v1/seo/today/gyeonggi/seongnam/bundang")
assert page.status_code == 200 and "지금 20°" in page.text
def test_tomorrow_line_has_day_and_sunset():
line = tomorrow_line([_hour(12, 19.5, prob=10)], datetime(2026, 10, 15, 17, 51, tzinfo=KST))
assert line == "최저 20°·최고 20°, 강수확률 10%, 맑음. 해 지는 시각 오후 5시 51분."
assert tomorrow_line([], datetime(2026, 10, 15, 17, 51, tzinfo=KST)) == ""
@pytest.mark.anyio
async def test_tomorrow_page_fills_tomorrow_forecast(offline, monkeypatch):
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset())
tmpl = TEMPLATE.replace("오늘 날씨", "내일 날씨")
async def template(self, path):
return tmpl if path == "tomorrow/gyeonggi/seongnam/bundang" else None
monkeypatch.setattr(SeoService, "template", template)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
page = await client.get("/v1/seo/tomorrow/gyeonggi/seongnam/bundang")
missing = await client.get("/v1/seo/tomorrow/seoul/nowhere")
assert page.status_code == 200 and "<h1>서울 중구 내일 날씨, 뭐 할까?</h1><p>최저 " in page.text
assert "지금 " not in page.text and "<ol>" not in page.text
assert missing.status_code == 404
def test_today_copy_has_date_place_morning_day_firsts_and_status():
line = today_copy(date(2026, 10, 14), "중구", _feed(), [_hour(12, 19.5, prob=10)], datetime(2026, 10, 14, 17, 52, tzinfo=KST))
assert line == "10월 14일(수) 중구 오늘 날씨: 최저 20°·최고 20°, 비 올 확률 10%. 아침엔 러닝각, 낮엔 빨래각이 1위예요. 미세먼지 좋음, 해 지는 시각 오후 5시 52분."
same = _feed()
same.stories = [_top("캠핑각", 90, {"morning": 1, "day": 1})]
assert "아침·낮엔 캠핑각이 1위예요." in today_copy(date(2026, 10, 14), "중구", same, [], None)
def test_today_copy_lists_dust_discomfort_uv_in_order():
feed = _feed()
feed.hero.status = [HeroStat(icon="m", label=label, value=value, tone="normal") for label, value in (("습도", "보통"), ("불쾌지수", "쾌적"), ("자외선", "보통"), ("미세먼지", "보통"))]
line = today_copy(date(2026, 10, 30), "성남시", feed, [_hour(12, 18, rain=2, prob=60)], None)
assert line.endswith("미세먼지 보통, 불쾌지수 쾌적, 자외선 보통.")
assert "습도" not in line
def test_tomorrow_copy_has_date_place_top1_and_sunset():
sunset = datetime(2026, 10, 31, 17, 36, tzinfo=KST)
line = tomorrow_copy(date(2026, 10, 31), "평택시", [_hour(12, 15, prob=30)], "빨래각", sunset)
assert line == "10월 31일(토) 평택시 내일 날씨: 최저 15°·최고 15°, 맑음, 비 올 확률 30%. 내일 하기 좋은 일 1위는 빨래각, 해 지는 시각은 오후 5시 36분이에요."
on_hour = tomorrow_copy(date(2026, 10, 31), "평택시", [_hour(12, 15)], None, datetime(2026, 10, 31, 18, 0, tzinfo=KST))
assert on_hour.endswith("해 지는 시각은 오후 6시예요.")
assert tomorrow_copy(date(2026, 10, 31), "평택시", [], "빨래각", sunset) == ""
@pytest.mark.anyio
async def test_new_copy_pages_get_new_title_and_description(offline, monkeypatch):
tomorrow = TEMPLATE.replace("오늘 날씨", "내일 날씨").replace("</head>", "<title>중구 내일 날씨, 뭐 할까? · 서울 | 날씨각</title></head>")
async def template(self, path):
return {"today/seoul/jung": TEMPLATE, "tomorrow/seoul/jung": tomorrow}.get(path)
monkeypatch.setattr(SeoService, "template", template)
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset({"today/seoul/jung", "tomorrow/seoul/jung"}))
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
today = await client.get("/v1/seo/today/seoul/jung")
ahead = await client.get("/v1/seo/tomorrow/seoul/jung")
assert today.status_code == 200 and ahead.status_code == 200
assert '<meta name="description" content="10월 ' in today.text and " 중구 오늘 날씨: 최저 " in today.text
assert "<ol><li>" in today.text and '<meta name="seo-copy" content="new" />' in today.text
assert " 중구 내일 날씨: 최저 " in ahead.text and "해 지는 시각은 오후" in ahead.text
assert "<title>중구 내일 날씨 · 내일 1위는 " in ahead.text and 'property="og:description" content="10월 ' in ahead.text
assert '<meta name="seo-copy" content="new" />' in ahead.text
@pytest.mark.anyio
async def test_old_copy_pages_keep_old_text_and_are_marked(offline, monkeypatch):
async def template(self, path):
return TEMPLATE if path == "today/seoul/jung" else None
monkeypatch.setattr(SeoService, "template", template)
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset())
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
page = await client.get("/v1/seo/today/seoul/jung")
assert "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>최저 " in page.text
assert '<meta name="seo-copy" content="old" />' in page.text
def test_copy_test_groups_split_region_pages_in_half():
assert seo_service.NEW_COPY and all(p.startswith(("today/", "tomorrow/")) for p in seo_service.NEW_COPY)
today = sum(p.startswith("today/") for p in seo_service.NEW_COPY)
assert today == len(seo_service.NEW_COPY) - today