Files
o2o-weather/backend/tests/test_culture_api.py
T
minaChoi 997a366e76 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, 문서 파일 이름 정리 등)도 함께 담김.
2026-10-07 12:03:48 +09:00

103 lines
5.4 KiB
Python

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 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>
<place>테스트 미술관</place><realmName>전시</realmName><area>서울</area><sigungu>종로구</sigungu><thumbnail>{thumb}</thumbnail>
<gpsX>126.97689</gpsX><gpsY>37.57592</gpsY></item>"""
def _page(items: list[str], total: int) -> str:
return (f"<?xml version='1.0' encoding='UTF-8'?><response><header><resultCode>00</resultCode><resultMsg>NORMAL SERVICE.</resultMsg></header>"
f"<body><items>{''.join(items)}</items><numOfrows>2</numOfrows><PageNo>1</PageNo><totalCount>{total}</totalCount></body></response>")
@pytest.fixture
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:
return httpx.AsyncClient(transport=httpx.MockTransport(handler))
@pytest.mark.anyio
async def test_fetch_exhibitions_pages_through_xml(key):
seen = []
def handler(req: httpx.Request) -> httpx.Response:
seen.append(dict(req.url.params))
page = int(req.url.params["PageNo"])
items = [_ITEM.format(seq=page * 10 + i, title=f"전시{page}-{i}", start="20261001", end="20261130", thumb="") for i in range(2 if page == 1 else 1)]
return httpx.Response(200, text=_page(items, 3), headers={"content-type": "application/xml"})
async with _client(handler) as client:
items = await fetch_exhibitions(client, "11", date(2026, 10, 6), 30)
assert [it["title"] for it in items] == ["전시1-0", "전시1-1", "전시2-0"]
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>"
"<returnAuthMsg>등록되지 않은 서비스키</returnAuthMsg><returnReasonCode>30</returnReasonCode></cmmMsgHeader></OpenAPI_ServiceResponse>")
async with _client(lambda req: httpx.Response(403, text=body)) as client:
with pytest.raises(DataGoKrRequestFailed, match="30 SERVICE_KEY_IS_NOT_REGISTERED_ERROR"):
await fetch_exhibitions(client, "11", date(2026, 10, 6), 30)
@pytest.mark.anyio
async def test_fetch_exhibitions_skips_unknown_sido(key):
async with _client(lambda req: pytest.fail("호출하면 안 된다")) as client:
assert await fetch_exhibitions(client, "99", date(2026, 10, 6), 30) == []
def test_parse_exhibitions_maps_fields_and_drops_ended_or_duplicate():
items = [
{"seq": "501", "title": "가을 특별전", "place": "테스트 미술관", "startDate": "20261001", "endDate": "2026-11-30",
"thumbnail": "http://www.culture.go.kr/upload/a.jpg", "gpsX": "126.97689", "gpsY": "37.57592"},
{"seq": "501", "title": "가을 특별전", "place": "테스트 미술관", "startDate": "20261001", "endDate": "20261130", "thumbnail": "", "gpsX": "", "gpsY": ""},
{"seq": "502", "title": "끝난 전시", "place": "테스트 박물관", "startDate": "20260101", "endDate": "20261005"},
{"seq": "503", "title": "날짜 없음", "place": "테스트 박물관", "startDate": "", "endDate": ""},
{"seq": "504", "title": "좌표 뒤바뀜", "place": "테스트 박물관", "startDate": "20261001", "endDate": "20261010", "gpsX": "37.5", "gpsY": "127.0"},
]
rows = parse_exhibitions(items, "11", date(2026, 10, 6))
assert [r["source_id"] for r in rows] == ["kcis:501", "kcis:504"]
assert rows[0]["end_date"] == date(2026, 11, 30)
assert rows[1]["lat"] == 37.5 and rows[1]["lon"] == 127.0
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": "테스트 콘서트 &lt;가을밤&gt;", "place": "테스트 홀 &amp; 라운지", "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"