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