Files
o2o-weather/backend/tests/test_reel.py

104 lines
5.0 KiB
Python

import base64
import pytest
from httpx import ASGITransport, AsyncClient
from config.settings import settings
from router.router import app
KEY = "test-admin-key"
# 가장 작은 mp4 머리 (서버는 'ftyp' 상자만 본다)
MP4_BYTES = b"\x00\x00\x00\x18ftypisom" + b"0" * 200
MP4 = base64.b64encode(MP4_BYTES).decode()
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 {"title": "날씨각이 뭐예요?", "caption": "오늘 날씨에 맞는 할 일을 점수로", "hashtags": "#날씨각 #릴스", "video": MP4, **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_reel_needs_key_and_mp4(admin_key):
async with client() as c:
assert (await c.post("/v1/reel", json=body())).status_code == 401
bad = await c.post("/v1/reel", json=body(video=JPEG), headers=admin_key)
assert bad.status_code == 400
@pytest.mark.anyio
async def test_reel_saved_and_served_with_range(admin_key):
async with client() as c:
made = (await c.post("/v1/reel", json=body(cover=JPEG), headers=admin_key)).json()
assert made["result"]["success"] and made["video_url"] == f"/v1/reel/{made['reel_id']}.mp4" and made["cover_url"].endswith("/cover.jpg")
full = await c.get(made["video_url"])
assert full.status_code == 200 and full.headers["content-type"] == "video/mp4" and full.content == MP4_BYTES
part = await c.get(made["video_url"], headers={"Range": "bytes=4-7"})
assert part.status_code == 206 and part.content == b"ftyp" and part.headers["content-range"] == f"bytes 4-7/{len(MP4_BYTES)}"
cover = await c.get(made["cover_url"])
assert cover.status_code == 200 and cover.headers["content-type"] == "image/jpeg"
listed = (await c.get("/v1/reel", headers=admin_key)).json()["items"]
assert listed[0]["reel_id"] == made["reel_id"] and "video" not in listed[0]
assert (await c.get("/v1/reel/999999.mp4")).status_code == 404
@pytest.mark.anyio
async def test_reel_instagram_publish_and_store_media_id(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")
monkeypatch.setattr(instagram, "VIDEO_STATUS_WAIT_SEC", 0.0)
calls: list[tuple[str, dict]] = []
polls = {"n": 0}
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"):
assert data["media_type"] == "REELS" and data["share_to_feed"] == "true"
assert data["video_url"].startswith("https://weather.example/v1/reel/") and data["video_url"].endswith(".mp4")
assert data["cover_url"].endswith("/cover.jpg")
assert data["caption"] == "날씨각이 뭐예요?\n\n오늘 날씨에 맞는 할 일을 점수로\n\n#날씨각 #릴스"
return httpx.Response(200, json={"id": "vid"})
if request.url.path.endswith("/vid"):
polls["n"] += 1
return httpx.Response(200, json={"status_code": "IN_PROGRESS" if polls["n"] < 3 else "FINISHED"})
if request.url.path.endswith("/media_publish"):
assert data["creation_id"] == "vid"
return httpx.Response(200, json={"id": "reel77"})
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/reel", json=body(cover=JPEG), headers=admin_key)).json()
res = (await c.post(f"/v1/reel/{made['reel_id']}/instagram", headers=admin_key)).json()
again = (await c.post(f"/v1/reel/{made['reel_id']}/instagram", headers=admin_key)).json()
listed = (await c.get("/v1/reel", headers=admin_key)).json()["items"][0]
assert res["result"]["success"] and res["ig_media_id"] == "reel77" and polls["n"] == 3
assert again["ig_media_id"] == "reel77" and len([p for p, _ in calls if p.endswith("/media_publish")]) == 1
assert listed["ig_media_id"] == "reel77"
@pytest.mark.anyio
async def test_reel_instagram_requires_token(admin_key, monkeypatch):
monkeypatch.setattr(settings, "instagram_access_token", "")
async with client() as c:
made = (await c.post("/v1/reel", json=body(), headers=admin_key)).json()
res = (await c.post(f"/v1/reel/{made['reel_id']}/instagram", headers=admin_key)).json()
assert res["result"]["success"] is False and "INSTAGRAM" in res["msg"]