o2o-site-AEO/solution/backend/tests/test_site_thumbnail.py
Mina Choi 378ad55b5b [feat] solution/backend: 발행·재발행마다 사이트 화면을 찍어 썸네일로 — 실패하면 대표 사진
썸네일이 대표 사진 한 장이라 재발행해도 쇼케이스·목록 카드가 사이트 모습과 달랐다.

- site_thumbnail: Playwright(워커 이미지에 이미 있음)로 /s/<slug> 1280×800 촬영, 실패 시 대표 사진
- THUMBNAIL_CAPTURE=0 이면 촬영을 끈다 — conftest 기본값 0(테스트에서 외부 주소를 열지 않게)

테스트 2건 추가(test_site_thumbnail)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:34:21 +09:00

200 lines
8.4 KiB
Python

"""발행 썸네일 — 사이트의 대표 사진을 Azure Blob 으로 옮긴다."""
from types import SimpleNamespace
import httpx
import pytest
from services import azure_static, site_payload, site_thumbnail
def _snapshot(*rows):
return {"media": list(rows)}
def _transport(monkeypatch, handler):
"""사진을 내려주는 CDN 대역."""
real = httpx.AsyncClient
def factory(**kwargs):
return real(transport=httpx.MockTransport(handler), **kwargs)
monkeypatch.setattr(site_thumbnail.httpx, "AsyncClient", factory)
class FakeContainer:
def __init__(self):
self.uploads = {}
def upload_blob(self, name, data, **options):
self.uploads[name] = {"body": data, **options}
@pytest.fixture
def blob(monkeypatch):
container = FakeContainer()
service = SimpleNamespace(get_container_client=lambda name: container)
monkeypatch.setattr(
site_thumbnail.BlobServiceClient, "from_connection_string", lambda value: service
)
monkeypatch.setenv("AZURE_STORAGE_CONNECTION_STRING", "UseDevelopmentStorage=true")
monkeypatch.delenv("AZURE_STORAGE_PREFIX", raising=False)
return container
def test_대표사진은_객실전용이_아닌_첫장이다():
# og:image 선정(site_payload)과 같은 함수를 쓴다 — 두 벌이면 검색 결과와 카드가 갈린다.
snapshot = _snapshot(
{"media_id": "m1", "url": "https://cdn.test/room.jpg", "unit_id": "u1"},
{"media_id": "m2", "url": "https://cdn.test/front.jpg", "unit_id": None},
{"media_id": "m3", "url": "https://cdn.test/back.jpg", "unit_id": None},
)
assert site_payload.primary_media(snapshot)["media_id"] == "m2"
def test_설정이_없으면_아무것도_하지_않는다(monkeypatch):
monkeypatch.delenv("AZURE_STORAGE_CONNECTION_STRING", raising=False)
assert site_thumbnail.is_configured() is False
async def test_대표사진이_없으면_None_이고_발행은_그대로(blob):
"""검증: 승인 사진이 객실 전용뿐이라 대표가 없다."""
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/room.jpg", "unit_id": "u1"})
assert await site_thumbnail.store("butter", snapshot) is None
assert blob.uploads == {}
async def test_이미지가_아니면_받지_않는다(blob, monkeypatch):
"""검증: 사진 URL 이 HTML(오류 페이지)을 돌려준다."""
_transport(monkeypatch, lambda req: httpx.Response(200, headers={"content-type": "text/html"}, content=b"<html>"))
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/front.jpg", "unit_id": None})
assert await site_thumbnail.store("butter", snapshot) is None
assert blob.uploads == {}
async def test_상한을_넘는_사진은_받지_않는다(blob, monkeypatch):
body = b"x" * (site_thumbnail.MAX_BYTES + 1)
_transport(monkeypatch, lambda req: httpx.Response(200, headers={"content-type": "image/jpeg"}, content=body))
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/huge.jpg", "unit_id": None})
assert await site_thumbnail.store("butter", snapshot) is None
assert blob.uploads == {}
async def test_네트워크_실패는_삼킨다(blob, monkeypatch):
def _boom(request):
raise httpx.ConnectTimeout("timed out", request=request)
_transport(monkeypatch, _boom)
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/front.jpg", "unit_id": None})
assert await site_thumbnail.store("butter", snapshot) is None
async def test_사이트_디렉터리_밖의_thumbs_에_올린다(blob, monkeypatch):
"""검증: 대표 사진을 받아 업로드한다."""
_transport(monkeypatch, lambda req: httpx.Response(200, headers={"content-type": "image/jpeg"}, content=b"jpegbytes"))
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/front.jpg", "unit_id": None})
url = await site_thumbnail.store("butter", snapshot, 3)
# `?v=` 는 캐시 무효화다.
from services import site_payload
assert url == f"{site_payload.publish_origin()}/thumbs/butter.jpg?v=3"
name = f"{azure_static.DEFAULT_PREFIX}/thumbs/butter.jpg"
assert set(blob.uploads) == {name}
assert not name.startswith(f"{azure_static.DEFAULT_PREFIX}/{azure_static.SITE_ROOT_DIR}/")
uploaded = blob.uploads[name]
assert uploaded["body"] == b"jpegbytes"
settings = uploaded["content_settings"]
assert settings.content_type == "image/jpeg"
# 썸네일은 재발행마다 바뀌는데 주소는 그대로다 — 길게 캐시하면 옛 그림이 계속 뜬다.
assert settings.cache_control == site_thumbnail.CACHE_CONTROL
# ── 발행 경로와의 배선 ──────────────────────────────────────────────────── 아래 두 건은 "발행이 썸네일에 매달리지 않는가" 를 본다.
async def test_발행된_화면을_찍어_올린다(blob, monkeypatch):
shots = []
async def _capture(url):
shots.append(url)
return b"shot", "image/jpeg", "jpg"
monkeypatch.setenv(site_thumbnail.CAPTURE_ENV, "1")
monkeypatch.setattr(site_thumbnail, "_capture", _capture)
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/front.jpg", "unit_id": None})
await site_thumbnail.store("butter", snapshot, 4)
from services import site_payload
assert shots == [f"{site_payload.publish_origin()}/s/butter"]
assert blob.uploads[f"{azure_static.DEFAULT_PREFIX}/thumbs/butter.jpg"]["body"] == b"shot"
async def test_촬영에_실패하면_대표_사진을_쓴다(blob, monkeypatch):
async def _capture(url):
return None
monkeypatch.setenv(site_thumbnail.CAPTURE_ENV, "1")
monkeypatch.setattr(site_thumbnail, "_capture", _capture)
_transport(monkeypatch, lambda req: httpx.Response(200, headers={"content-type": "image/jpeg"}, content=b"photo"))
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/front.jpg", "unit_id": None})
await site_thumbnail.store("butter", snapshot, 5)
assert blob.uploads[f"{azure_static.DEFAULT_PREFIX}/thumbs/butter.jpg"]["body"] == b"photo"
async def test_발행하면_사이트에_썸네일_주소가_남는다(auth_headers, client, db_engine, monkeypatch):
from services import build_service
from tests.test_build_publish import _approved_media, _place, _run, _verified_facts
async def _store(slug, snapshot, version=None):
return f"https://w4ai.o2o.kr/thumbs/{slug}.jpg?v={version}"
monkeypatch.setattr(build_service.site_thumbnail, "store", _store)
h = await auth_headers("u1")
pid = await _place(client, h, "썸네일펜션")
await _verified_facts(client, h, pid, {"intro": "하조대 해변 도보 3분 거리의 펜션입니다."})
await _approved_media(db_engine, pid)
await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})
await _run()
site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()["site"]
assert site["thumbnail_url"].startswith("https://w4ai.o2o.kr/thumbs/")
assert site["thumbnail_url"].endswith("?v=1")
# 재발행하면 주소가 바뀌어야 한다.
await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})
await _run()
again = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()["site"]
assert again["thumbnail_url"].endswith("?v=2")
assert again["thumbnail_url"] != site["thumbnail_url"]
async def test_썸네일을_못_만들어도_발행은_성공한다(auth_headers, client, db_engine, monkeypatch):
from services import build_service
from tests.test_build_publish import _approved_media, _place, _run, _verified_facts
async def _store(slug, snapshot, version=None):
return None
monkeypatch.setattr(build_service.site_thumbnail, "store", _store)
h = await auth_headers("u1")
pid = await _place(client, h, "그림없는펜션")
await _verified_facts(client, h, pid, {"intro": "하조대 해변 도보 3분 거리의 펜션입니다."})
await _approved_media(db_engine, pid)
job_id = (await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})).json()["job_id"]
await _run()
assert (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]["result"]["published"] is True
site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()["site"]
assert "thumbnail_url" not in site