feat: 축제·전시·콘서트·팝업 7일마다 수집, 피드 행사 종류 섞기
- 행사 수집을 화면 요청에서 빼고 worker 가 월 04:00(켤 때 7일 기록 없으면 한 번) 전국 17개 시도를 받는다 - 문화정보원 음악/콘서트(B000) 추가, 쪽·시도 사이 1초 간격으로 초당 요청 제한 회피 - 팝가(popga.co.kr) 팝업스토어 수집: 사이트맵 + 상세 JSON-LD, 바뀐 페이지만 다시 읽음 - 수집이 끝나면 Teams Workflows webhook 으로 종류별 건수 알림 (TEAMS_WEBHOOK_URL) - event.kind(1=축제 2=전시 3=콘서트 4=팝업) 칸과 종류별 아이콘 추가 - 피드 행사 카드·띠를 축제→팝업→전시→콘서트 차례로 섞음 - 포스트 종류별 내용·피드 기획 문서 갱신 같은 작업 폴더의 다른 작업(외부 API 가드, 노을·달 계산, 각 API, 문서 파일 이름 정리 등)도 함께 담김.
This commit is contained in:
1 parent
b61ed92c54
commit
997a366e76
70 files changed
+2083
-649
No files matched your search
@@ -2,8 +2,9 @@ import asyncio
|
||||
import os
|
||||
|
||||
# 개발 DB·Redis 를 건드리지 않도록 테스트 전용 DB(<이름>_test)와 Redis 15번을 쓴다. 앱 import 전에 정해야 한다.
|
||||
# 여러 작업 폴더에서 동시에 돌릴 땐 TEST_DB_NAME·TEST_REDIS_DB 를 폴더마다 다르게 준다 (시작할 때 DB 를 지우고 Redis 를 비우므로).
|
||||
os.environ["DB_NAME"] = os.environ.get("TEST_DB_NAME", "nalssigak_test")
|
||||
os.environ["REDIS_DB"] = "15"
|
||||
os.environ["REDIS_DB"] = os.environ.get("TEST_REDIS_DB", "15")
|
||||
|
||||
import asyncpg # noqa: E402
|
||||
import pytest # noqa: E402
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from config.settings import settings
|
||||
from services.external import data_go_kr, guard, open_meteo
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed, get_body
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds
|
||||
|
||||
URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fast(monkeypatch):
|
||||
monkeypatch.setattr(settings, "data_go_kr_service_key", "fake-key")
|
||||
monkeypatch.setattr(data_go_kr, "_BACKOFF_SEC", 0)
|
||||
monkeypatch.setattr(guard, "BUDGET_SEC", 0.3)
|
||||
|
||||
|
||||
def _client(handler) -> httpx.AsyncClient:
|
||||
return httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
||||
|
||||
|
||||
def _ok(_req: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(200, json={"response": {"header": {"resultCode": "00"}, "body": {"items": []}}})
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_hanging_api_gives_up_within_budget_then_is_skipped(fast):
|
||||
calls = []
|
||||
|
||||
async def hang(req: httpx.Request) -> httpx.Response:
|
||||
calls.append(1)
|
||||
await asyncio.sleep(5)
|
||||
return _ok(req)
|
||||
|
||||
async with _client(hang) as client:
|
||||
start = time.perf_counter()
|
||||
with pytest.raises(DataGoKrRequestFailed, match="no answer within"):
|
||||
await get_body(client, URL, {})
|
||||
assert time.perf_counter() - start < 1
|
||||
start = time.perf_counter()
|
||||
with pytest.raises(DataGoKrRequestFailed, match="skipped"):
|
||||
await get_body(client, URL, {})
|
||||
assert time.perf_counter() - start < 0.1
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refused_connection_is_skipped_but_other_apis_still_called(fast):
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
if req.url.path.endswith("getVilageFcst"):
|
||||
raise httpx.ConnectError("refused")
|
||||
return _ok(req)
|
||||
|
||||
async with _client(handler) as client:
|
||||
with pytest.raises(DataGoKrRequestFailed, match="failed after 3 attempts: ConnectError"):
|
||||
await get_body(client, URL, {})
|
||||
with pytest.raises(DataGoKrRequestFailed, match="skipped"):
|
||||
await get_body(client, URL, {})
|
||||
assert await get_body(client, URL.replace("getVilageFcst", "getUltraSrtFcst"), {}) == {"items": []}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_error_code_from_api_does_not_pause_it(fast):
|
||||
calls = []
|
||||
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
calls.append(1)
|
||||
return httpx.Response(200, json={"response": {"header": {"resultCode": "03", "resultMsg": "NO_DATA"}}})
|
||||
|
||||
async with _client(handler) as client:
|
||||
for _ in range(2):
|
||||
with pytest.raises(DataGoKrRequestFailed, match="03 NO_DATA"):
|
||||
await get_body(client, URL, {})
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_open_meteo_down_is_skipped(monkeypatch):
|
||||
monkeypatch.setattr(open_meteo, "_BUDGET_SEC", 0.3)
|
||||
calls = []
|
||||
|
||||
async def hang(req: httpx.Request) -> httpx.Response:
|
||||
calls.append(1)
|
||||
await asyncio.sleep(5)
|
||||
return httpx.Response(200, json=[])
|
||||
|
||||
async with _client(hang) as client:
|
||||
for _ in range(2):
|
||||
with pytest.raises(OpenMeteoRequestFailed):
|
||||
await fetch_clouds(client, [(37.5, 127.0)])
|
||||
assert len(calls) == 1
|
||||
@@ -3,9 +3,10 @@ from datetime import date
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from common.enums import EventKind
|
||||
from config.settings import settings
|
||||
from services.external import culture_api
|
||||
from services.external.culture_api import fetch_exhibitions, parse_exhibitions
|
||||
from services.external.culture_api import CONCERT, fetch_exhibitions, parse_exhibitions
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
|
||||
_ITEM = """<item><serviceName>공연/전시</serviceName><seq>{seq}</seq><title>{title}</title><startDate>{start}</startDate><endDate>{end}</endDate>
|
||||
@@ -23,6 +24,7 @@ def key(monkeypatch):
|
||||
monkeypatch.setattr(settings, "data_go_kr_service_key", "fake-key")
|
||||
monkeypatch.setattr(culture_api, "_PAGE_SIZE", 2)
|
||||
monkeypatch.setattr(culture_api, "_BACKOFF_SEC", 0)
|
||||
monkeypatch.setattr(culture_api, "_PAGE_GAP_SEC", 0)
|
||||
|
||||
|
||||
def _client(handler) -> httpx.AsyncClient:
|
||||
@@ -45,6 +47,19 @@ async def test_fetch_exhibitions_pages_through_xml(key):
|
||||
assert seen[0]["realmCode"] == "D000" and seen[0]["sido"] == "서울" and seen[0]["from"] == "20261006" and seen[0]["to"] == "20261105"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_exhibitions_asks_concert_realm(key):
|
||||
seen = []
|
||||
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
seen.append(dict(req.url.params))
|
||||
return httpx.Response(200, text=_page([], 0))
|
||||
|
||||
async with _client(handler) as client:
|
||||
assert await fetch_exhibitions(client, "26", date(2026, 10, 6), 30, CONCERT) == []
|
||||
assert seen[0]["realmCode"] == "B000" and seen[0]["sido"] == "부산"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_exhibitions_reports_unregistered_key(key):
|
||||
body = ("<OpenAPI_ServiceResponse><cmmMsgHeader><errMsg>SERVICE_KEY_IS_NOT_REGISTERED_ERROR</errMsg>"
|
||||
@@ -76,4 +91,12 @@ def test_parse_exhibitions_maps_fields_and_drops_ended_or_duplicate():
|
||||
assert rows[0]["image_url"] == "https://www.culture.go.kr/upload/a.jpg"
|
||||
assert rows[0]["lat"] == 37.57592 and rows[0]["lon"] == 126.97689
|
||||
assert rows[0]["sido_code"] == "11" and rows[0]["place_name"] == "테스트 미술관"
|
||||
assert rows[0]["kind"] == EventKind.EXHIBITION
|
||||
assert all(len(r["source_id"]) <= 20 for r in rows)
|
||||
|
||||
|
||||
def test_parse_exhibitions_unescapes_title_and_place():
|
||||
items = [{"seq": "601", "title": "테스트 콘서트 <가을밤>", "place": "테스트 홀 & 라운지", "startDate": "20261010", "endDate": "20261010"}]
|
||||
rows = parse_exhibitions(items, "11", date(2026, 10, 6), CONCERT)
|
||||
assert rows[0]["name"] == "테스트 콘서트 <가을밤>" and rows[0]["place_name"] == "테스트 홀 & 라운지"
|
||||
assert rows[0]["kind"] == EventKind.CONCERT and rows[0]["icon"] == "concert"
|
||||
@@ -0,0 +1,83 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
import scheduler.jobs as jobs
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.enums import ErrorType
|
||||
from config.settings import settings
|
||||
from services.external import teams_webhook
|
||||
|
||||
|
||||
async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sent(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def send(title, detail):
|
||||
calls.append((title, detail))
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(jobs.teams_webhook, "send", send)
|
||||
monkeypatch.setattr(jobs, "_SIDO_GAP_SEC", 0)
|
||||
monkeypatch.setattr(jobs, "refresh_popups", lambda: _async(ErrorType.SUCCESS))
|
||||
return calls
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refresh_events_sums_kinds_and_notifies(sent, monkeypatch):
|
||||
monkeypatch.setattr(jobs, "collect_events", lambda sido, today: _async((ErrorType.SUCCESS, {"festival": 2, "exhibition": 1, "concert": 3})))
|
||||
assert await jobs.refresh_events() is ErrorType.SUCCESS
|
||||
n = len(jobs.SIDO_NAME)
|
||||
assert sent[0][0] == "행사 수집 완료"
|
||||
assert f"축제 {2 * n}, 전시 {n}, 콘서트 {3 * n}, 팝업 0" in sent[0][1]
|
||||
assert await REDIS.conn.exists(jobs.EVENTS_DONE)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refresh_events_reports_failed_sido_and_does_not_mark_done(sent, monkeypatch):
|
||||
monkeypatch.setattr(jobs, "collect_events", lambda sido, today: _async(
|
||||
(ErrorType.EXTERNAL_API_ERROR, {}) if sido == "46" else (ErrorType.SUCCESS, {"festival": 1, "exhibition": 0, "concert": 0})))
|
||||
assert await jobs.refresh_events() is ErrorType.EXTERNAL_API_ERROR
|
||||
assert sent[0][0] == "행사 수집 일부 실패" and "실패한 시도: 전남" in sent[0][1]
|
||||
assert not await REDIS.conn.exists(jobs.EVENTS_DONE)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refresh_events_skips_when_done_within_7_days(sent, monkeypatch):
|
||||
await REDIS.conn.set(jobs.EVENTS_DONE, "2026-10-05")
|
||||
monkeypatch.setattr(jobs, "collect_events", lambda *a: pytest.fail("수집하면 안 된다"))
|
||||
assert await jobs.refresh_events(only_if_missing=True) is ErrorType.SUCCESS
|
||||
assert sent == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_teams_send_posts_adaptive_card_only_when_configured(monkeypatch):
|
||||
posted = []
|
||||
|
||||
class Client:
|
||||
def __init__(self, **_):
|
||||
pass
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *_):
|
||||
return False
|
||||
|
||||
async def post(self, url, json):
|
||||
posted.append((url, json))
|
||||
return httpx.Response(202, request=httpx.Request("POST", url))
|
||||
|
||||
monkeypatch.setattr(teams_webhook.httpx, "AsyncClient", Client)
|
||||
monkeypatch.setattr(settings, "teams_webhook_url", "")
|
||||
assert await teams_webhook.send("t", "d") is False
|
||||
monkeypatch.setattr(settings, "teams_webhook_url", "http://example.test/hook")
|
||||
assert await teams_webhook.send("t", "d") is False
|
||||
monkeypatch.setattr(settings, "teams_webhook_url", "https://example.test/hook")
|
||||
assert await teams_webhook.send("행사 수집 완료", "축제 1") is True
|
||||
card = posted[0][1]["attachments"][0]["content"]
|
||||
assert [b["text"] for b in card["body"]] == ["행사 수집 완료", "축제 1"]
|
||||
assert len(posted) == 1
|
||||
@@ -6,10 +6,12 @@ from sqlalchemy import text
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import PostType
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from router.router import app
|
||||
from services.feed_service import build_feed_day
|
||||
from services.week_service import collect_events
|
||||
|
||||
REGION = "1114000000"
|
||||
|
||||
@@ -51,6 +53,7 @@ def test_weekends_groups_this_and_next_weekend():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
await collect_events("11", now_kst().date())
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
@@ -160,6 +163,7 @@ async def test_build_day_makes_every_card_at_three():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feed_has_quote_and_no_adjacent_same_type(offline):
|
||||
await collect_events("11", now_kst().date())
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
articles = (await client.get("/v1/season/article/list")).json()
|
||||
@@ -324,6 +328,7 @@ async def test_feed_has_day_trip_card_with_city_event(offline, monkeypatch):
|
||||
"firstimage": "http://tong.visitkorea.or.kr/c.jpg"}] if sido == "51" else []
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", festivals)
|
||||
await week_service.collect_events("51", today)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/feed", params={"region": "4113500000"})).json()
|
||||
trip = next(p for p in body["posts"] if p["post_type"] == PostType.DAY_TRIP.value)
|
||||
|
||||
@@ -78,3 +78,21 @@ async def test_index_detail_has_six_factors_and_rules(fakes):
|
||||
assert sum(f["weight"] for f in body["factors"]) == 100
|
||||
assert body["zero_rules"] == "비 확률 80% 이상이거나 바람 14m/s 이상이면 0점"
|
||||
assert body["limit"].startswith("모기")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_detail_has_four_score_bands_with_today_marked(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/1", params={"region": REGION})).json()
|
||||
bands = body["bands"]
|
||||
assert [(b["low"], b["high"]) for b in bands] == [(0, 29), (30, 59), (60, 79), (80, 100)]
|
||||
assert all(b["text"] for b in bands)
|
||||
current = [b for b in bands if b["current"]]
|
||||
assert len(current) == 1 and current[0]["low"] <= body["index"]["score"] <= current[0]["high"]
|
||||
|
||||
|
||||
def test_every_index_has_four_band_sentences():
|
||||
import json
|
||||
import os
|
||||
seed = json.load(open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8"))
|
||||
assert all(sorted(d["sentences"], key=int) == ["0", "30", "60", "80"] and all(d["sentences"].values()) for d in seed)
|
||||
@@ -0,0 +1,40 @@
|
||||
from datetime import datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import PostType
|
||||
from common.utils.kma_time import KST
|
||||
from services.calc.moon import nearest, phase_name
|
||||
from services.feed_service import FeedService, _tonight
|
||||
|
||||
|
||||
def test_true_phases_match_published_times_within_five_minutes():
|
||||
known = [(True, datetime(2024, 4, 23, 23, 49, tzinfo=timezone.utc)), (False, datetime(2024, 4, 8, 18, 21, tzinfo=timezone.utc)),
|
||||
(True, datetime(2025, 10, 7, 3, 47, tzinfo=timezone.utc)), (False, datetime(2017, 8, 21, 18, 30, tzinfo=timezone.utc))]
|
||||
for full, at in known:
|
||||
assert abs((nearest(at, full) - at).total_seconds()) < 300
|
||||
|
||||
|
||||
def test_phase_names():
|
||||
assert phase_name(datetime(2025, 10, 7, 3, 47, tzinfo=timezone.utc)) == "보름달"
|
||||
assert phase_name(datetime(2024, 4, 8, 18, 21, tzinfo=timezone.utc)) == "삭"
|
||||
|
||||
|
||||
def test_tonight_follows_feed_day_starting_at_3am():
|
||||
assert _tonight(datetime(2024, 4, 9, 1, 0, tzinfo=KST)) == datetime(2024, 4, 8, 22, 0, tzinfo=KST)
|
||||
assert _tonight(datetime(2024, 4, 8, 20, 0, tzinfo=KST)) == datetime(2024, 4, 8, 22, 0, tzinfo=KST)
|
||||
assert _tonight(datetime(2024, 4, 9, 9, 0, tzinfo=KST)) == datetime(2024, 4, 9, 22, 0, tzinfo=KST)
|
||||
|
||||
|
||||
def _moon_post(now: datetime):
|
||||
base = dict(post_id=1, post_type=PostType.MOON, like_count=0, comment_count=0, published_at=now)
|
||||
c = SimpleNamespace(now=now, region=SimpleNamespace(short_name="분당구"), hourly=[], board=None)
|
||||
return FeedService._moon(None, base, c)
|
||||
|
||||
|
||||
def test_moon_post_every_night_with_full_and_new_moon_stories():
|
||||
full = _moon_post(datetime(2025, 10, 7, 20, 0, tzinfo=KST)) # 보름 10.07 12:47
|
||||
assert full.title == "오늘 밤 보름달" and "12:4" in full.slides[0].line
|
||||
new = _moon_post(datetime(2024, 4, 9, 1, 0, tzinfo=KST)) # 삭 04.09 03:21, 자정 넘긴 새벽에도 그 밤
|
||||
assert new.title == "오늘 밤 달 없는 밤"
|
||||
plain = _moon_post(datetime(2025, 10, 4, 20, 0, tzinfo=KST)) # 보름 사흘 전
|
||||
assert plain.title == "오늘 밤 차오르는 달" and plain.slides[0].rows[-1].label == "다음 보름" and plain.slides[0].rows[-1].value.startswith("10.07")
|
||||
@@ -0,0 +1,64 @@
|
||||
import json
|
||||
from datetime import date
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from common.enums import EventKind
|
||||
from services.external import popga
|
||||
from services.external.popga import fetch_popup_index, parse_popup, sido_of
|
||||
|
||||
|
||||
def _page(popup_id: int, kind: str, start: str, end: str, address: str = "서울 성동구 테스트로 1") -> str:
|
||||
ld = {
|
||||
"@context": "https://schema.org", "@type": "Event", "name": "테스트 팝업 & 굿즈", "startDate": start, "endDate": end,
|
||||
"location": {"@type": "Place", "name": "테스트 빌딩 1F", "address": {"@type": "PostalAddress", "streetAddress": address},
|
||||
"geo": {"@type": "GeoCoordinates", "latitude": 37.5446123, "longitude": 127.0557456}},
|
||||
}
|
||||
payload = f'self.__next_f.push([1,"{{\\"data\\":{{\\"id\\":{popup_id},\\"type\\":\\"{kind}\\",\\"source\\":null}}}}"])'
|
||||
return f'<html><script type="application/ld+json">{json.dumps(ld, ensure_ascii=False)}</script><script>{payload}</script></html>'
|
||||
|
||||
|
||||
def test_parse_popup_maps_store():
|
||||
row = parse_popup(_page(501, "STORE", "2026-10-02", "2026-10-11"), 501, date(2026, 10, 1))
|
||||
assert row == {
|
||||
"source_id": "popga:501", "sido_code": "11", "name": "테스트 팝업 & 굿즈", "place_name": "테스트 빌딩 1F",
|
||||
"start_date": date(2026, 10, 2), "end_date": date(2026, 10, 11), "is_confirmed": True,
|
||||
"source_url": "https://popga.co.kr/popup/501", "image_url": None, "lat": 37.54461, "lon": 127.05575, "kind": EventKind.POPUP, "icon": "popup",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind,end,address", [
|
||||
("PERFORMANCE", "2026-10-11", "서울 성동구 테스트로 1"),
|
||||
("STORE", "2026-09-30", "서울 성동구 테스트로 1"),
|
||||
("STORE", "2026-10-11", "알 수 없는 주소"),
|
||||
])
|
||||
def test_parse_popup_skips_non_store_ended_or_unknown_sido(kind, end, address):
|
||||
assert parse_popup(_page(502, kind, "2026-09-01", end, address), 502, date(2026, 10, 1)) is None
|
||||
|
||||
|
||||
def test_parse_popup_reads_type_of_its_own_id():
|
||||
page = _page(503, "STORE", "2026-10-02", "2026-10-11").replace('\\"id\\":503,\\"type\\":\\"STORE\\"', '\\"id\\":999,\\"type\\":\\"STORE\\"')
|
||||
assert parse_popup(page, 503, date(2026, 10, 1)) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("address,code", [
|
||||
("서울 마포구 테스트로 1", "11"), ("서울특별시 마포구", "11"), ("경기 수원시", "41"), ("경상남도 진주시", "48"),
|
||||
("강원특별자치도 춘천시", "51"), ("전북특별자치도 전주시", "52"), ("", None),
|
||||
])
|
||||
def test_sido_of(address, code):
|
||||
assert sido_of(address) == code
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_popup_index_reads_popup_pages_only(monkeypatch):
|
||||
monkeypatch.setattr(popga, "REQUEST_GAP_SEC", 0)
|
||||
pages = {
|
||||
"/sitemap.xml": "<sitemapindex><sitemap><loc>https://popga.co.kr/sitemap/2.xml</loc></sitemap>"
|
||||
"<sitemap><loc>https://popga.co.kr/sitemap/5.xml</loc></sitemap></sitemapindex>",
|
||||
"/sitemap/2.xml": "<urlset><url><loc>https://popga.co.kr/popup/12</loc><lastmod>2026-10-06T00:00:00Z</lastmod></url>"
|
||||
"<url><loc>https://popga.co.kr/popup/11</loc></url></urlset>",
|
||||
"/sitemap/5.xml": "<urlset><url><loc>https://popga.co.kr/popup/12/review/3</loc><lastmod>2026-10-06</lastmod></url></urlset>",
|
||||
}
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda req: httpx.Response(200, text=pages[req.url.path]))) as client:
|
||||
assert await fetch_popup_index(client) == {12: "2026-10-06T00:00:00Z", 11: ""}
|
||||
@@ -54,8 +54,10 @@ async def test_sky_view_scores_three_days_with_spots(monkeypatch, clean):
|
||||
assert plan["verdict"] == "go" and plan["headline"] == "나가 볼 만해요" and plan["when"] in ("오늘", "내일")
|
||||
assert "알맞게" in plan["reason"]
|
||||
assert plan["spot"]["name"] == "망원한강공원" and plan["best_at"]
|
||||
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "peak", "blue"]
|
||||
assert plan["outlook"].endswith("비슷해요")
|
||||
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "blue"]
|
||||
assert plan["situation_label"] == "하늘이 넓게 물들 수 있어요" and plan["models_agree"] == plan["models_total"] == 4
|
||||
assert plan["outlook"] == ""
|
||||
assert body["sunset"]["verdict"] == "go" and body["spots"][0]["direction"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -104,14 +106,19 @@ def test_nearest_spots_west_first_and_empty_outside_radius():
|
||||
assert sky_service.nearest_spots(33.0, 127.0, spots) == []
|
||||
|
||||
|
||||
def test_outlook_points_to_a_better_day_only_when_clearly_better():
|
||||
def test_outlook_only_when_a_later_day_has_a_better_verdict():
|
||||
from datetime import date, timedelta
|
||||
|
||||
from common.database.model.models import SkyScore
|
||||
from common.enums import SkySituation
|
||||
|
||||
today = date(2026, 10, 6)
|
||||
day = lambda i, v: SkyScore(score_date=today + timedelta(days=i), score=v) # noqa: E731
|
||||
assert sky_service.outlook(day(0, 30), [day(0, 30), day(1, 35), day(2, 72)], today) == "모레가 더 나아요 — 72점, 나가 볼 만해요"
|
||||
assert sky_service.outlook(day(0, 80), [day(0, 80), day(1, 50), day(2, 40)], today).startswith("오늘이 가장 나아요")
|
||||
assert sky_service.outlook(day(0, 50), [day(0, 50), day(1, 55), day(2, 45)], today) == "내일·모레도 비슷해요"
|
||||
sit = lambda i, s: SkyScore(score_date=today + timedelta(days=i), score=48, situation=s.value) # noqa: E731
|
||||
assert sky_service.outlook(day(0, 30), [day(0, 30), day(1, 35), day(2, 72)], today) == "모레가 더 나아요 · 나가 볼 만해요"
|
||||
assert sky_service.outlook(day(0, 80), [day(0, 80), day(1, 50), day(2, 40)], today) == ""
|
||||
assert sky_service.outlook(day(0, 50), [day(0, 50), day(1, 55), day(2, 45)], today) == ""
|
||||
assert sky_service.outlook(day(2, 50), [day(2, 50)], today) == ""
|
||||
few, glow = SkySituation.FEW, SkySituation.GLOW
|
||||
assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few), sit(2, glow)], today) == "모레가 더 나아요 · 하늘이 넓게 물들 수 있어요"
|
||||
assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few)], today) == ""
|
||||
@@ -2,7 +2,7 @@ from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkyType
|
||||
from common.utils.geo import destination, haversine_km
|
||||
from services.calc.sky_score import GRADE_LABEL, Layers, best_times, confidence, grade, reason, score, sunset_timeline, verdict
|
||||
from services.calc.sky_score import GRADE_LABEL, Layers, best_times, confidence, grade, reason, score, situation, sunset_timeline, verdict
|
||||
from services.calc.sun import sun_times
|
||||
|
||||
CLEAR = Layers(0, 0, 0)
|
||||
@@ -43,7 +43,7 @@ def test_sunset_best_times_order():
|
||||
sunset = datetime(2026, 10, 2, 9, 15, tzinfo=timezone.utc)
|
||||
dusk = datetime(2026, 10, 2, 9, 41, tzinfo=timezone.utc)
|
||||
labels = [t["label"] for t in best_times(SkyType.SUNSET, sunset, dusk, 50)]
|
||||
assert labels == ["해 져요", "가장 붉을 때", "보랏빛 하늘"]
|
||||
assert labels == ["해 져요", "가장 붉을 때", "블루아워"]
|
||||
|
||||
|
||||
def test_reason_names_what_decided_the_score():
|
||||
@@ -65,3 +65,23 @@ def test_sunset_timeline_runs_golden_to_blue():
|
||||
assert [r["kind"] for r in rows] == ["golden", "sun", "peak", "blue"]
|
||||
ats = [datetime.fromisoformat(r["at"]) for r in rows]
|
||||
assert ats == sorted(ats) and 15 <= (ats[1] - ats[0]).total_seconds() / 60 <= 60
|
||||
|
||||
|
||||
def test_situation_follows_reason_order():
|
||||
from common.enums import SkySituation
|
||||
clear, glow = Layers(0, 0, 0), Layers(0, 40, 50)
|
||||
assert situation(clear, clear, clear) is SkySituation.FEW
|
||||
assert situation(glow, glow, clear) is SkySituation.GLOW
|
||||
assert situation(Layers(0, 90, 95), Layers(0, 90, 95), clear) is SkySituation.THICK
|
||||
assert situation(Layers(80, 0, 0), Layers(70, 0, 0), clear) is SkySituation.LOW_CLOUD
|
||||
assert situation(glow, glow, Layers(70, 0, 0)) is SkySituation.COVERED
|
||||
|
||||
|
||||
def test_ranking_summary_only_when_most_spots_share_a_situation():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import SkySituation
|
||||
from services.sky_service import ranking_summary
|
||||
item = lambda s: SimpleNamespace(score=SimpleNamespace(situation=s.value)) # noqa: E731
|
||||
assert ranking_summary([item(SkySituation.FEW)] * 8 + [item(SkySituation.GLOW)] * 2) == "오늘은 전국이 맑아 대부분 짧게 끝나요"
|
||||
assert ranking_summary([item(SkySituation.FEW)] * 5 + [item(SkySituation.GLOW)] * 5) is None
|
||||
+21
-10
@@ -8,12 +8,12 @@ import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
import services.week_service as week_service
|
||||
from common.database.model.models import Event
|
||||
from common.enums import RainType, Sky
|
||||
from common.enums import EventKind, RainType, Sky
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from router.router import app
|
||||
from services.external.kma import latest_mid_base, mid_word, parse_mid
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
from services.week_service import _status
|
||||
from services.week_service import EventItem, _status, mix_kinds
|
||||
|
||||
REGION = "1144000000"
|
||||
|
||||
@@ -45,6 +45,15 @@ def test_event_status_labels():
|
||||
assert _status(ev(date(2026, 10, 20), date(2026, 10, 21)), today) == ("soon", "D-18")
|
||||
|
||||
|
||||
def test_mix_kinds_rotates_festival_popup_exhibition_concert():
|
||||
item = lambda name, kind: EventItem(event=Event(name=name, kind=kind), status="soon", status_label="", fit=None) # noqa: E731
|
||||
items = [item("연주회1", EventKind.CONCERT), item("연주회2", EventKind.CONCERT), item("전시1", EventKind.EXHIBITION),
|
||||
item("팝업1", EventKind.POPUP), item("연주회3", EventKind.CONCERT), item("축제1", EventKind.FESTIVAL)]
|
||||
assert [e.event.name for e in mix_kinds(items)] == ["축제1", "팝업1", "전시1", "연주회1", "연주회2", "연주회3"]
|
||||
only = [item(f"연주회{i}", EventKind.CONCERT) for i in range(3)]
|
||||
assert [e.event.name for e in mix_kinds(only)] == ["연주회0", "연주회1", "연주회2"]
|
||||
|
||||
|
||||
async def _async(v):
|
||||
return v
|
||||
|
||||
@@ -67,6 +76,11 @@ def _mid(*_):
|
||||
return land, ta
|
||||
|
||||
|
||||
async def _collect(*sidos):
|
||||
for sido in sidos:
|
||||
await week_service.collect_events(sido, now_kst().date())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fakes(monkeypatch):
|
||||
today = now_kst().date()
|
||||
@@ -99,6 +113,7 @@ async def test_week_reaches_mid_forecast_end_with_holiday_and_rain(fakes):
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_events_exclude_long_running_and_add_weather_fit(fakes):
|
||||
await _collect("11")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": REGION})).json()
|
||||
assert [e["name"] for e in body["events"]] == ["가을 축제"]
|
||||
@@ -114,6 +129,7 @@ async def test_events_include_culture_exhibitions_with_their_credit(fakes, monke
|
||||
"seq": "123", "title": "가을 특별전", "place": "테스트 미술관", "startDate": (today + timedelta(days=1)).strftime("%Y%m%d"),
|
||||
"endDate": (today + timedelta(days=20)).strftime("%Y%m%d"), "thumbnail": "http://www.culture.go.kr/x.jpg", "gpsX": "126.97", "gpsY": "37.57",
|
||||
}]))
|
||||
await _collect("11")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": REGION})).json()
|
||||
by_name = {e["name"]: e for e in body["events"]}
|
||||
@@ -129,6 +145,7 @@ async def test_events_keep_tour_festivals_when_culture_api_fails(fakes, monkeypa
|
||||
raise DataGoKrRequestFailed("realm2 30 SERVICE_KEY_IS_NOT_REGISTERED_ERROR")
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_exhibitions", fail)
|
||||
await _collect("11")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": REGION})).json()
|
||||
assert [e["name"] for e in body["events"]] == ["가을 축제"]
|
||||
@@ -145,16 +162,10 @@ async def test_events_pick_within_30km_across_sido(fakes, monkeypatch):
|
||||
"41": [{"contentid": "41", "title": "연천 축제", "addr1": "경기 연천군", "mapy": "38.0963", "mapx": "127.0750", **span},
|
||||
{"contentid": "42", "title": "좌표 없는 경기 축제", "addr1": "경기", **span}],
|
||||
}
|
||||
asked = []
|
||||
|
||||
def festivals(client, sido, since):
|
||||
asked.append(sido)
|
||||
return _async(by_sido.get(sido, []))
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", festivals)
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda client, sido, since: _async(by_sido.get(sido, [])))
|
||||
await _collect("11", "41")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": "4113500000"})).json()
|
||||
assert {"11", "41"} <= set(asked) and "26" not in asked
|
||||
assert {e["name"] for e in body["events"]} == {"잠실 축제", "좌표 없는 경기 축제"}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user