o2o-site-AEO/solution/backend/tests/test_site_thumbnail.py
Mina Choi 11d30bb3d1 [chore] solution,admin,ontology: 코드 주석을 한 줄로 — 히스토리 주석 삭제
여러 줄 주석이 설명보다 경위(예전·실측·지적)를 적고 있어 읽는 사람이 결론을 찾기 어려웠다.

- ts·tsx·js·mjs·css·py 478개: 여러 줄 주석은 첫 문장 한 줄로, 과거형·날짜 문장은 삭제
- 주석 위치는 TypeScript 파서·파이썬 tokenize/ast 로 찾는다 — 문자열 안의 # · /* 는 건드리지 않는다
- eslint·ts·noqa·type: ignore 같은 지시 주석은 그대로 둔다

파이썬 275개 정리 전후 AST 동일, TS 298개 주석 뺀 토큰 동일(빈 JSX 주석 10곳만 차이).
site·frontend·admin tsc, site vitest 105 passed

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 16:05:19 +09:00

167 lines
7.1 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_발행하면_사이트에_썸네일_주소가_남는다(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