랜딩의 "이렇게 나옵니다" 섹션이 걸 그림이 없었다. 발행은 되는데 그 사이트가 어떻게 생겼는지 밖에서 알 방법이 payload 안에만 있었다. ★ 스크린샷이 아니라 그 사이트의 대표 사진(og:image)이다. 헤드리스 브라우저는 봇 탐지 우회 우려로 영구 금지돼 있고(DECISIONS 1-1), 워커(python:slim)· 프리렌더(node:alpine) 어디에도 Chromium 이 없다. - site_thumbnail: 대표 사진을 받아 <prefix>/thumbs/<slug>.<ext> 로 올린다. s/<slug>/ 안에 두지 않는 이유 — _remove_stale_site_files 가 매 발행마다 그 경로를 프리렌더 산출물로 통째로 교체해 조용히 지운다 - site_payload: primary_media()·publish_origin()·region_label() 공개. isPrimary 계산을 한 곳으로 모아 og:image 와 썸네일이 갈릴 수 없게 했다 - build_service: azure publish 직후·IndexNow 전에 저장. 실패해도 발행은 그대로 (payload 와 같은 원칙). thumbnail_url 은 발행 상태 전이 UPDATE 에 합쳐 1회 - GET /v1/showcase: 인증 없음. 발행된 사이트만, place_id·전화·상세주소는 안 나간다 - conftest: fake_renderer 가 늘 ok=True 라 NO_UNIQUE_CONTENT 되짚기 경로가 통째로 안 돌고 있었다(기존에 깨져 있던 테스트 4건 포함 수정) 전체 562 passed
173 lines
7.9 KiB
Python
173 lines
7.9 KiB
Python
"""발행 썸네일 — 사이트의 대표 사진을 Azure Blob 으로 옮긴다.
|
|
|
|
★ 스크린샷이 아니다(헤드리스 브라우저는 영구 금지, docs/DECISIONS.md 1-1).
|
|
그래서 여기서 볼 것은 "무엇을 대표로 고르는가"와 "무엇을 받지 않는가" 두 가지다.
|
|
|
|
이 경로가 절대 하면 안 되는 것:
|
|
- 썸네일 실패로 발행을 되돌리는 것 — 정적 파일은 이미 올라갔다.
|
|
- 이미지가 아닌 응답을 그대로 올리는 것 — 카드가 깨진 그림이 된다.
|
|
- 사이트 디렉터리(`s/<slug>/`) 안에 두는 것 — 다음 발행이 통째로 지운다.
|
|
"""
|
|
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):
|
|
"""검증: 승인 사진이 객실 전용뿐이라 대표가 없다.
|
|
기대결과: None 을 돌려주고 업로드하지 않는다(예외를 올리지 않는다)."""
|
|
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(오류 페이지)을 돌려준다.
|
|
기대결과: 거부하고 None. 깨진 그림을 쇼케이스에 올리지 않는다."""
|
|
_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):
|
|
"""검증: 대표 사진을 받아 업로드한다.
|
|
기대결과: `<prefix>/thumbs/<slug>.<ext>` — `s/<slug>/` 안이 아니다.
|
|
★ 사이트 경로는 매 발행마다 프리렌더 산출물로 통째로 교체된다
|
|
(azure_static._remove_stale_site_files) — 그 안에 두면 다음 발행에서 조용히 사라진다."""
|
|
_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)
|
|
|
|
assert url == "https://w4ai.o2o.kr/thumbs/butter.jpg"
|
|
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_발행하면_사이트에_썸네일_주소가_남는다(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):
|
|
return f"https://w4ai.o2o.kr/thumbs/{slug}.jpg"
|
|
|
|
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/")
|
|
|
|
|
|
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):
|
|
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
|