import base64 import pytest from httpx import ASGITransport, AsyncClient from common.enums import CardStatus, PostType from config.settings import settings from router.router import app SEOUL, BUSAN = "1111000000", "2611000000" KEY = "test-admin-key" # 가장 작은 JPEG 머리 (서버는 JPEG 시작 바이트만 본다) JPEG = base64.b64encode(b"\xff\xd8\xff\xe0" + b"0" * 64).decode() def client(): return AsyncClient(transport=ASGITransport(app=app), base_url="http://test") def body(**kw): return {"template": "tarot", "topic": "연애 썸", "title": "오늘의 썸 타로", "caption": "한 장 골라 보세요", "texts": {"n1": "컵 2"}, "images": [JPEG, JPEG, JPEG], **kw} @pytest.fixture def admin_key(monkeypatch): monkeypatch.setattr(settings, "admin_api_key", KEY) return {"X-Admin-Key": KEY} @pytest.mark.anyio async def test_admin_api_needs_key(monkeypatch): async with client() as c: monkeypatch.setattr(settings, "admin_api_key", "") assert (await c.post("/v1/card", json=body(), headers={"X-Admin-Key": ""})).status_code == 401 monkeypatch.setattr(settings, "admin_api_key", KEY) assert (await c.post("/v1/card", json=body())).status_code == 401 assert (await c.post("/v1/card", json=body(), headers={"X-Admin-Key": "wrong"})).status_code == 401 assert (await c.post("/v1/card/1/publish", headers={"X-Admin-Key": "wrong"})).status_code == 401 @pytest.mark.anyio async def test_rejects_non_jpeg(admin_key): async with client() as c: res = await c.post("/v1/card", json=body(images=[base64.b64encode(b"not a jpeg").decode()]), headers=admin_key) assert res.status_code == 400 @pytest.mark.anyio async def test_waiting_card_not_in_feed_until_published(offline, admin_key): async with client() as c: made = (await c.post("/v1/card", json=body(), headers=admin_key)).json() assert made["status"] == CardStatus.WAITING.value and len(made["image_urls"]) == 3 feed = (await c.get("/v1/feed", params={"region": SEOUL})).json() assert not [p for p in feed["posts"] if p["post_type"] == PostType.CARD.value] published = (await c.post(f"/v1/card/{made['card_id']}/publish", headers=admin_key)).json() assert published["status"] == CardStatus.PUBLISHED.value and published["post_id"] # 게시하면 피드 캐시를 지워 바로 보인다. 전국 카드라 다른 시도에서도 같은 포스트 seoul, busan = [(await c.get("/v1/feed", params={"region": r})).json() for r in (SEOUL, BUSAN)] image = await c.get(made["image_urls"][0]) for feed in (seoul, busan): card = next(p for p in feed["posts"] if p["post_type"] == PostType.CARD.value) assert card["post_id"] == published["post_id"] and card["title"] == "오늘의 썸 타로" assert [s["kind"] for s in card["slides"]] == ["image"] * 3 and card["slides"][0]["url"] == made["image_urls"][0] # 날씨 바로 아래 types = [p["post_type"] for p in seoul["posts"]] assert types.index(PostType.CARD.value) <= 2 assert image.status_code == 200 and image.headers["content-type"] == "image/jpeg" and image.content.startswith(b"\xff\xd8") @pytest.mark.anyio async def test_publish_twice_keeps_one_post_and_reject(offline, admin_key): async with client() as c: made = (await c.post("/v1/card", json=body(publish=True), headers=admin_key)).json() again = (await c.post(f"/v1/card/{made['card_id']}/publish", headers=admin_key)).json() assert made["status"] == CardStatus.PUBLISHED.value and again["post_id"] == made["post_id"] second = (await c.post("/v1/card", json=body(title="두 번째"), headers=admin_key)).json() rejected = (await c.post(f"/v1/card/{second['card_id']}/reject", headers=admin_key)).json() assert rejected["status"] == CardStatus.REJECTED.value missing = await c.get("/v1/card/999999/1.jpg") assert missing.status_code == 404 @pytest.mark.anyio async def test_list_cards_newest_first_with_image_urls(offline, admin_key): async with client() as c: a = (await c.post("/v1/card", json=body(title="첫 카드"), headers=admin_key)).json() b = (await c.post("/v1/card", json=body(title="둘째 카드", publish=True), headers=admin_key)).json() assert (await c.get("/v1/card")).status_code == 401 res = (await c.get("/v1/card", headers=admin_key)).json() ids = [x["card_id"] for x in res["items"]] assert ids[:2] == [b["card_id"], a["card_id"]] first = res["items"][0] assert first["title"] == "둘째 카드" and first["status"] == CardStatus.PUBLISHED.value and first["post_id"] and len(first["image_urls"]) == 3 assert res["items"][1]["status"] == CardStatus.WAITING.value and res["items"][1].get("published_at") is None @pytest.mark.anyio async def test_instagram_publish_carousel_and_store_media_id(offline, admin_key, monkeypatch): import httpx from services.external import instagram monkeypatch.setattr(settings, "instagram_access_token", "tok") monkeypatch.setattr(settings, "instagram_user_id", "1789") monkeypatch.setattr(settings, "public_base_url", "https://weather.example") calls: list[tuple[str, dict]] = [] def handler(request: httpx.Request) -> httpx.Response: data = dict(httpx.QueryParams(request.content.decode())) if request.method == "POST" else dict(request.url.params) calls.append((request.url.path, data)) assert data["access_token"] == "tok" if request.url.path.endswith("/1789/media"): if data.get("media_type") == "CAROUSEL": assert data["children"] == "c1,c2,c3" and data["caption"] == "오늘의 썸 타로\n\n한 장 골라 보세요\n\n#날씨각 #날씨타로" return httpx.Response(200, json={"id": "car"}) assert data["image_url"].startswith("https://weather.example/v1/card/") and data["is_carousel_item"] == "true" return httpx.Response(200, json={"id": f"c{len([c for c in calls if 'is_carousel_item' in c[1]])}"}) if request.url.path.endswith("/car"): return httpx.Response(200, json={"status_code": "FINISHED"}) if request.url.path.endswith("/media_publish"): assert data["creation_id"] == "car" return httpx.Response(200, json={"id": "media99"}) return httpx.Response(404, json={"error": {"message": "no"}}) real = httpx.AsyncClient monkeypatch.setattr(instagram.httpx, "AsyncClient", lambda **kw: real(transport=httpx.MockTransport(handler))) async with client() as c: made = (await c.post("/v1/card", json=body(publish=True, hashtags="#날씨각 #날씨타로"), headers=admin_key)).json() res = (await c.post(f"/v1/card/{made['card_id']}/instagram", headers=admin_key)).json() again = (await c.post(f"/v1/card/{made['card_id']}/instagram", headers=admin_key)).json() listed = (await c.get("/v1/card", headers=admin_key)).json()["items"][0] assert res["result"]["success"] and res["ig_media_id"] == "media99" assert again["ig_media_id"] == "media99" and len([p for p, _ in calls if p.endswith("/media_publish")]) == 1 assert listed["ig_media_id"] == "media99" @pytest.mark.anyio async def test_instagram_requires_token(offline, admin_key, monkeypatch): monkeypatch.setattr(settings, "instagram_access_token", "") async with client() as c: made = (await c.post("/v1/card", json=body(), headers=admin_key)).json() res = (await c.post(f"/v1/card/{made['card_id']}/instagram", headers=admin_key)).json() assert res["result"]["success"] is False and "INSTAGRAM" in res["msg"] @pytest.mark.anyio async def test_latest_card_by_template_is_public(offline, admin_key): async with client() as c: assert "post_id" not in (await c.get("/v1/card/latest", params={"template": "ootd"})).json() ootd = (await c.post("/v1/card", json=body(template="ootd", title="오늘 코디", publish=True), headers=admin_key)).json() await c.post("/v1/card", json=body(template="ootd", title="승인 대기 코디"), headers=admin_key) await c.post("/v1/card", json=body(publish=True), headers=admin_key) # 그 틀로 피드에 올린 것 중 가장 최근 (승인 대기·다른 틀은 빼고) latest = (await c.get("/v1/card/latest", params={"template": "ootd"})).json() assert latest["post_id"] == ootd["post_id"] and latest["published_at"] assert (await c.get("/v1/card/latest", params={"template": "../x"})).status_code == 422