o2o-site-AEO/solution/backend/tests/test_build_publish.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

351 lines
16 KiB
Python

"""정적 빌드 + 발행 — 상호명에서 발행까지 한 바퀴."""
import uuid
from sqlalchemy import text
from common.enums import (
BuildStatus,
ErrorType,
FactStatus,
JobStatus,
MediaStatus,
PublishAction,
PublishRejectReason,
SiteStatus,
SourceType,
)
from crud.job_crud import JobQueue
from worker.handlers import build_handler
from worker.runner import Worker
REQUIRED = {
"check_in_time": "15:00", "check_out_time": "11:00",
"cancel_policy": "이용 7일 전 100% 환불, 3일 전 50% 환불",
"cooking_allowed": "true", "pet_allowed": "false",
}
async def _run():
assert await Worker("w", JobQueue(), build_handler(), job_deadline_sec=60).process_one() is True
async def _place(client, h, name="빌드펜션"):
pid = (await client.post("/v1/place", headers=h, json={"name": name, "category": 1})).json()["place"]["place_id"]
await client.post(f"/v1/place/{pid}/verify", headers=h, json={
"source": 2, "road_address": f"강원특별자치도 양양군 현북면 하조대3길 {uuid.uuid4().hex[:3]}",
"phone": "033-672-0000", "latitude": "38.0219217", "longitude": "128.7221449",
})
return pid
async def _verified_facts(client, h, pid, extra=None):
"""필수 항목을 넣고 전부 승인 상태로 만든다(사람이 직접 입력 = 즉시 노출값)."""
for k, v in {**REQUIRED, **(extra or {})}.items():
await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": v})
async def _approved_media(db_engine, pid, alt="2층 목조 건물 외관"):
async with db_engine.begin() as c:
await c.execute(
text("INSERT INTO place_photos (media_id, place_id, url, origin_url, source_type, status, alt_text, label, sort_order) "
"VALUES (:m,:p,:u,:u,:s,:st,:a,:l,0)"),
{"m": uuid.uuid4(), "p": uuid.UUID(pid), "u": f"https://cdn.test/{uuid.uuid4().hex[:6]}.jpg",
"s": SourceType.CRAWL.value, "st": MediaStatus.APPROVED.value, "a": alt, "l": "외관"},
)
async def test_full_build_and_publish(auth_headers, client, db_engine):
"""검증: 필수 fact + 승인 사진이 갖춰진 사업장을 빌드·발행한다."""
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()
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
assert job["status"] == JobStatus.DONE.value, job.get("last_error")
r = job["result"]
assert r["gate"]["passed"] is True, r["gate"]
assert r["build_status"] == "BUILT"
assert r["published"] is True
assert r["unique_content_count"] > 0
# 백엔드는 HTML 을 굽지 않는다.
assert r["payload_path"], "렌더러에 넘길 payload 가 없다"
assert r["routes"] > 0, "렌더러가 페이지를 하나도 굽지 않았다"
site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()
assert site["site"]["status"] == SiteStatus.PUBLISHED.value
assert site["current_version"]["build_status"] == BuildStatus.BUILT.value
async def test_unverified_fact_blocks_publish(auth_headers, client, db_engine):
"""검증: 미검증 fact 가 섞인 채로 빌드한다."""
h = await auth_headers("u1")
pid = await _place(client, h, "미검증펜션")
# 공식 API 로 들어온 값 = 후보 상태(UNVERIFIED)
for k, v in REQUIRED.items():
await client.post(f"/v1/place/{pid}/fact", headers=h, json={
"key": k, "value": v, "source_type": SourceType.API.value, "source_url": "https://api.test/1"})
job_id = (await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})).json()["job_id"]
await _run()
r = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]["result"]
assert r["gate"]["passed"] is False
assert r["gate"]["reason"] == PublishRejectReason.NO_UNIQUE_CONTENT.name
assert r["build_status"] == "FAILED"
assert r.get("published") is None
site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()
assert site["site"]["status"] == SiteStatus.DRAFT.value, "★ 게이트를 막았는데 발행됐다"
async def test_no_unique_content_blocks_publish(auth_headers, client):
"""검증: 필수 항목은 다 채웠지만 값이 전부 짧은 정형값이고 소개문·FAQ·사진이 없다."""
h = await auth_headers("u1")
pid = await _place(client, h, "빈껍데기펜션")
# 취소 규정을 한 글자로 — 형식은 갖췄지만 이 가게만의 내용이 없다.
for k, v in {**REQUIRED, "cancel_policy": "X"}.items():
await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": v})
job_id = (await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})).json()["job_id"]
await _run()
r = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]["result"]
assert r["gate"]["passed"] is False
assert r["gate"]["reason"] == PublishRejectReason.NO_UNIQUE_CONTENT.name
async def test_owner_written_intro_counts_as_unique_content(auth_headers, client):
h = await auth_headers("owner-intro")
pid = await _place(client, h, "직접소개펜션")
for k, v in {**REQUIRED, "cancel_policy": "X"}.items():
await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": v})
await client.post(f"/v1/place/{pid}/site/theme", headers=h, json={"theme": {"sections": [{
"id": "intro", "name": "소개", "enabled": True, "locked": False,
"body": "하조대의 아침 바다를 조용히 바라볼 수 있는 작은 숙소입니다.",
}]}})
job_id = (await client.post(
f"/v1/place/{pid}/site/build", headers=h, json={"publish": True}
)).json()["job_id"]
await _run()
r = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]["result"]
assert r["gate"]["passed"] is True
assert r["unique_content_count"] == 1
assert r["published"] is True
async def test_missing_required_field_warns_but_publishes(auth_headers, client, db_engine):
"""검증: 취소 규정 없이 빌드한다."""
h = await auth_headers("u1")
pid = await _place(client, h, "규정없는펜션")
partial = {k: v for k, v in REQUIRED.items() if k != "cancel_policy"}
for k, v in partial.items():
await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": v})
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()
r = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]["result"]
assert r["gate"]["passed"] is True, "필수 항목 누락은 더 이상 발행을 막지 않는다"
assert r["gate"]["warning"] == PublishRejectReason.REQUIRED_FACT_MISSING.name
assert "cancel_policy" in r["gate"]["missing"], "무엇이 비었는지는 계속 알려줘야 한다"
assert r["build_status"] == "BUILT"
site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()
assert site["site"]["status"] == SiteStatus.PUBLISHED.value
async def test_rejected_build_is_logged_with_reason(auth_headers, client):
"""검증: 게이트가 막은 뒤 발행 기록."""
h = await auth_headers("u1")
pid = await _place(client, h, "기록펜션")
for k, v in {**REQUIRED, "cancel_policy": "X"}.items():
await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": v})
await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})
await _run()
logs = (await client.get(f"/v1/place/{pid}/site/log/list", headers=h)).json()["logs"]
assert logs
assert logs[0]["reject_reason"] == PublishRejectReason.NO_UNIQUE_CONTENT.value
assert logs[0]["detail"]["reason"] == "NO_UNIQUE_CONTENT"
async def test_build_requires_verified_place(auth_headers, client):
"""검증: 동일 업소 검증 전에 빌드한다."""
h = await auth_headers("u1")
pid = (await client.post("/v1/place", headers=h, json={"name": "미검증", "category": 1})).json()["place"]["place_id"]
r = await client.post(f"/v1/place/{pid}/site/build", headers=h, json={})
assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_VERIFIED.value
async def test_needs_rebuild_after_content_change(auth_headers, client, db_engine):
"""검증: 발행 후 노출값을 바꾼다."""
h = await auth_headers("u1")
pid = await _place(client, h, "재빌드펜션")
await _verified_facts(client, h, pid, {"intro": "조용한 펜션입니다."})
await _approved_media(db_engine, pid)
await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})
await _run()
assert (await client.get(f"/v1/place/{pid}/site", headers=h)).json()["needs_rebuild"] is False
await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": "check_in_time", "value": "16:00"})
assert (await client.get(f"/v1/place/{pid}/site", headers=h)).json()["needs_rebuild"] is True
async def test_suspend_is_state_transition_not_delete(auth_headers, client, db_engine):
"""검증: 발행된 사이트를 중지하고 다시 재개한다."""
h = await auth_headers("u1")
pid = await _place(client, h, "해지펜션")
await _verified_facts(client, h, pid, {"intro": "펜션 소개문입니다."})
await _approved_media(db_engine, pid)
await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})
await _run()
version_id = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()["current_version"]["site_version_id"]
body = (await client.post(f"/v1/place/{pid}/site/status", headers=h,
json={"action": PublishAction.SUSPEND.value})).json()
assert body["site"]["status"] == SiteStatus.SUSPENDED.value
assert body["current_version"]["site_version_id"] == version_id, "★ 중지가 버전을 지웠다"
body = (await client.post(f"/v1/place/{pid}/site/status", headers=h,
json={"action": PublishAction.RESUME.value})).json()
assert body["site"]["status"] == SiteStatus.PUBLISHED.value
async def test_versions_accumulate(auth_headers, client, db_engine):
"""검증: 두 번 빌드한다."""
h = await auth_headers("u1")
pid = await _place(client, h, "버전펜션")
await _verified_facts(client, h, pid, {"intro": "펜션 소개문입니다."})
await _approved_media(db_engine, pid)
await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})
await _run()
await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})
await _run()
versions = (await client.get(f"/v1/place/{pid}/site/version/list", headers=h)).json()["versions"]
assert [v["version"] for v in versions] == [2, 1]
async def test_site_is_scoped_to_owner(auth_headers, client):
"""검증: 다른 사장님 계정으로 남의 사이트를 본다."""
h1 = await auth_headers("o1")
pid = await _place(client, h1, "스코프펜션")
h2 = await auth_headers("o2")
r = await client.get(f"/v1/place/{pid}/site", headers=h2)
assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value
# ── 렌더 결과 기반 게이트 ────────────────────────────────────────────────────
async def _built_place(client, h, db_engine):
pid = await _place(client, h)
await _verified_facts(client, h, pid, {"intro": "하조대 해변 도보 3분 거리의 펜션입니다."})
await _approved_media(db_engine, pid)
return pid
async def _build(client, h, pid, publish=True):
job_id = (await client.post(f"/v1/place/{pid}/site/build", headers=h,
json={"publish": publish})).json()["job_id"]
await _run()
return (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]["result"]
async def test_렌더가_실패하면_발행하지_않는다(auth_headers, client, db_engine, monkeypatch):
from services import render_service
async def _broken(payload_path, site_version, timeout_sec):
return {"schemaVersion": 1, "slug": "t", "siteId": "", "placeId": "",
"siteVersion": site_version, "ok": False, "renderedAt": "2026-01-01T00:00:00Z",
"routes": 0, "bundle": "t.js", "uniqueContentCount": 5, "jsonld": [],
"mismatches": [], "error": "번들이 없다"}
h = await auth_headers("u1")
pid = await _built_place(client, h, db_engine)
monkeypatch.setattr(render_service, "render_site", _broken)
r = await _build(client, h, pid)
assert r["build_status"] == "FAILED"
assert r.get("published") is not True
assert "번들이 없다" in r["error"]
# 게이트 반려가 아닌 진짜 실패(렌더·인프라)는 알린다 — services/alert_service.
async with db_engine.begin() as c:
rows = (await c.execute(text("SELECT kind FROM alert_outbox WHERE kind = 'build_failed'"))).all()
assert len(rows) == 1
site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()
assert site["site"]["status"] != SiteStatus.PUBLISHED.value
async def test_구조화데이터가_화면과_다르면_발행하지_않는다(auth_headers, client, db_engine, monkeypatch):
"""검증: 렌더러가 JSON-LD 불일치를 보고한다."""
from services import render_service
async def _mismatch(payload_path, site_version, timeout_sec):
return {"schemaVersion": 1, "slug": "t", "siteId": "", "placeId": "",
"siteVersion": site_version, "ok": False, "renderedAt": "2026-01-01T00:00:00Z",
"routes": 0, "bundle": "t.js", "uniqueContentCount": 5, "jsonld": [],
"mismatches": ["telephone: '02-0000-0000' 이 화면에 없다"],
"error": "구조화 데이터가 화면 값과 다릅니다(1건)"}
h = await auth_headers("u1")
pid = await _built_place(client, h, db_engine)
monkeypatch.setattr(render_service, "render_site", _mismatch)
r = await _build(client, h, pid)
assert r["build_status"] == "FAILED"
# 사유가 "렌더 실패"로 뭉뚱그려지면 운영자가 손댈 곳을 알 수 없다.
assert r["gate"]["reason"] == PublishRejectReason.JSONLD_MISMATCH.name
assert r["mismatches"]
# 게이트 반려는 알리지 않는다 — 사장님 쪽 문제를 운영자에게 알리면 안 된다.
async with db_engine.begin() as c:
rows = (await c.execute(text("SELECT kind FROM alert_outbox"))).all()
assert rows == []
async def test_렌더_결과가_안_오면_발행하지_않는다(auth_headers, client, db_engine, monkeypatch):
"""검증: 렌더러가 죽어 보고서가 오지 않는다(타임아웃)."""
from services import render_service
async def _timeout(payload_path, site_version, timeout_sec):
raise render_service.RenderFailed("렌더 결과를 받지 못했다 — 렌더러가 도는지 확인이 필요하다")
h = await auth_headers("u1")
pid = await _built_place(client, h, db_engine)
monkeypatch.setattr(render_service, "render_site", _timeout)
r = await _build(client, h, pid)
assert r["build_status"] == "FAILED"
assert r.get("published") is not True
assert "렌더 결과" in r["error"]
async def test_렌더_보고서의_값이_그대로_박제된다(auth_headers, client, db_engine):
"""검증: site_versions 에 남는 jsonld·고유콘텐츠 수의 출처."""
h = await auth_headers("u1")
pid = await _built_place(client, h, db_engine)
r = await _build(client, h, pid)
assert r["build_status"] == "BUILT"
async with db_engine.begin() as c:
row = (await c.execute(
text("SELECT jsonld, unique_content_count FROM site_versions WHERE site_version_id = :v"),
{"v": uuid.UUID(r["site_version_id"])},
)).mappings().first()
assert row["unique_content_count"] == r["unique_content_count"]
assert row["jsonld"], "렌더러가 내보낸 JSON-LD 가 박제되지 않았다"
# 렌더러 대역이 내보낸 노드가 그대로 들어와야 한다(백엔드가 다시 만들지 않는다).
assert row["jsonld"][0]["@type"] == "LodgingBusiness"