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

350 lines
17 KiB
Python

"""facts 도메인 e2e — 생성 / 업데이트(재수집) / 수정 세 프로세스."""
from common.enums import ErrorType, FactStatus, FactWriteOutcome, PlaceCategory, SourceType
from services.external import gemini_text as gt
OTA = "https://ota.test/room/1"
async def _verified_place(client, headers, category=PlaceCategory.LODGING, kakao="999"):
r = await client.post("/v1/place", headers=headers, json={"name": "테스트업소", "category": category.value})
pid = r.json()["place"]["place_id"]
await client.post(f"/v1/place/{pid}/verify", headers=headers, json={"external_place_id": kakao})
return pid
async def _crawl(client, headers, pid, key, value, source=SourceType.CRAWL):
return (await client.post(f"/v1/place/{pid}/fact", headers=headers, json={
"key": key, "value": value, "source_type": source.value, "source_url": OTA,
})).json()
async def _own(client, headers, pid, key, value):
return (await client.post(f"/v1/place/{pid}/fact", headers=headers, json={
"key": key, "value": value, "source_type": SourceType.OWNER.value,
})).json()
async def _facts(client, headers, pid, **params):
return (await client.get(f"/v1/place/{pid}/fact/list", headers=headers, params=params)).json()
# ── 입력 검증 ────────────────────────────────────────────────────────────
async def test_schema_endpoint_returns_category_fields(auth_headers, client):
"""검증: 숙박 사업장의 fact 스키마 조회."""
h = await auth_headers("u1")
pid = await _verified_place(client, h)
body = (await client.get(f"/v1/place/{pid}/fact/schema", headers=h)).json()
assert body["category"] == "lodging"
check_in = next(f for f in body["fields"] if f["key"] == "check_in_time")
assert check_in["critical"] is True
assert check_in["allow_llm"] is False
async def test_key_outside_category_schema_is_rejected(auth_headers, client):
"""검증: 카페 사업장에 숙박 전용 key(check_in_time)를 기록한다."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, PlaceCategory.CAFE, kakao="c1")
body = await _own(client, h, pid, "check_in_time", "15:00")
assert body["result"]["code"] == ErrorType.FACT_INVALID_KEY.value
async def test_non_owner_source_requires_source_url(auth_headers, client):
"""검증: crawl 출처인데 source_url 없이 기록한다."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="s1")
r = await client.post(f"/v1/place/{pid}/fact", headers=h, json={
"key": "check_in_time", "value": "15:00", "source_type": SourceType.CRAWL.value})
assert r.json()["result"]["code"] == ErrorType.FACT_SOURCE_REQUIRED.value
async def test_llm_cannot_write_non_sentence_fields(auth_headers, client):
"""검증: LLM 출처로 체크인시간(allow_llm=False)을 기록한다."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="l1")
body = await _crawl(client, h, pid, "check_in_time", "15:00", SourceType.LLM)
assert body["result"]["code"] == ErrorType.FACT_INVALID_KEY.value
body = await _crawl(client, h, pid, "intro", "조용한 숙소입니다.", SourceType.LLM)
assert body["result"]["success"] is True
async def test_llm_sentence_is_published_without_approval(auth_headers, client):
"""검증: LLM 이 소개문(allow_llm)을 기록한다."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="l2")
body = await _crawl(client, h, pid, "intro", "조용한 숙소입니다.", SourceType.LLM)
assert body["fact"]["status"] == FactStatus.VERIFIED.value
assert body["outcome"] != FactWriteOutcome.CANDIDATE_CREATED.value
# 사이트 빌드가 보는 집합에 바로 들어간다.
facts = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json()
assert facts["publishable"] >= 1
async def test_llm_cannot_overwrite_corrected_sentence(auth_headers, client):
"""검증: 사장님이 고친 소개문(CORRECTED)을 LLM 이 다시 쓴다."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="l3")
await _crawl(client, h, pid, "intro", "생성된 첫 문장입니다.", SourceType.LLM)
facts = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json()
fact_id = next(f["fact_id"] for f in facts["facts"] if f["key"] == "intro")
r = await client.post(f"/v1/place/{pid}/fact/{fact_id}/transition", headers=h, json={
"status": FactStatus.CORRECTED.value, "value": "사장님이 고친 문장입니다."})
assert r.json()["result"]["success"] is True
body = await _crawl(client, h, pid, "intro", "생성기가 다시 쓴 문장입니다.", SourceType.LLM)
assert body["outcome"] == FactWriteOutcome.CANDIDATE_CREATED.value
facts = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json()
published = [f for f in facts["facts"]
if f["key"] == "intro" and f["status"] == FactStatus.CORRECTED.value]
assert published and published[0]["value"] == "사장님이 고친 문장입니다."
# ── 생성 프로세스 ─────────────────────────────────────────────────────────
async def test_crawled_fact_publishes_immediately(auth_headers, client):
"""검증: 크롤링으로 처음 들어온 값."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="p1")
body = await _crawl(client, h, pid, "check_in_time", "15:00")
assert body["outcome"] == FactWriteOutcome.PUBLISHED_CREATED.value
assert body["fact"]["status"] == FactStatus.VERIFIED.value
# 응답에서 None 필드는 지워져 나간다(RemoveNoneResponse) — 없는 것이 곧 비어 있다는 뜻이다.
assert body["fact"].get("verified_by") is None, "★ 자동 노출을 사람 승인으로 위장하면 안 된다"
listed = await _facts(client, h, pid)
assert listed["publishable"] == 1
assert (await _facts(client, h, pid, publishable_only=True))["facts"][0]["value"] == "15:00"
async def test_approving_candidate_publishes_it(auth_headers, client):
"""검증: 후보를 VERIFIED 로 승인한다."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="p2")
await _own(client, h, pid, "check_in_time", "15:00")
fid = (await _crawl(client, h, pid, "check_in_time", "16:00"))["fact"]["fact_id"]
body = (await client.post(f"/v1/place/{pid}/fact/{fid}/transition", headers=h,
json={"status": FactStatus.VERIFIED.value})).json()
assert body["result"]["success"] is True
assert body["fact"]["status"] == FactStatus.VERIFIED.value
assert body["fact"]["verified_at"] is not None
assert (await _facts(client, h, pid))["publishable"] == 1
async def test_illegal_transition_is_rejected(auth_headers, client):
"""검증: UNVERIFIED → CORRECTED 처럼 전이표에 없는 이동."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="p3")
fid = (await _crawl(client, h, pid, "check_in_time", "15:00", SourceType.API))["fact"]["fact_id"]
r = await client.post(f"/v1/place/{pid}/fact/{fid}/transition", headers=h,
json={"status": FactStatus.CORRECTED.value, "value": "16:00"})
assert r.json()["result"]["code"] == ErrorType.FACT_INVALID_TRANSITION.value
# ── 업데이트(재수집) 프로세스 ★ ───────────────────────────────────────────
async def test_recrawl_same_value_keeps_verification(auth_headers, client):
"""검증: 확인된 값과 똑같은 값을 재수집한다."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="r1")
fid = (await _crawl(client, h, pid, "check_in_time", "15:00"))["fact"]["fact_id"]
await client.post(f"/v1/place/{pid}/fact/{fid}/transition", headers=h, json={"status": FactStatus.VERIFIED.value})
assert (await _facts(client, h, pid))["publishable"] == 1
body = await _crawl(client, h, pid, "check_in_time", "15:00")
assert body["outcome"] == FactWriteOutcome.REFRESHED.value
assert body["fact"]["status"] == FactStatus.VERIFIED.value
assert (await _facts(client, h, pid))["publishable"] == 1, "★ 재수집이 검증을 초기화하면 안 된다"
async def test_recrawl_changed_value_keeps_site_and_queues_candidate(auth_headers, client):
"""검증: 사장님이 넣은 값과 다른 값을 재수집한다(OTA 가 바뀐 경우)."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="r2")
await _own(client, h, pid, "check_in_time", "15:00")
body = await _crawl(client, h, pid, "check_in_time", "16:00")
assert body["outcome"] == FactWriteOutcome.CANDIDATE_CREATED.value
assert body["fact"]["status"] == FactStatus.PENDING_OWNER.value
listed = await _facts(client, h, pid)
assert listed["publishable"] == 1, "★ 재수집 중에도 사이트에는 확인된 값이 계속 나가야 한다"
assert listed["pending_review"] == 1
published = (await _facts(client, h, pid, publishable_only=True))["facts"]
assert published[0]["value"] == "15:00"
async def test_approving_candidate_replaces_published_value(auth_headers, client):
"""검증: 쌓인 후보를 사람이 승인한다(업데이트의 마지막 단계)."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="r3")
await _own(client, h, pid, "check_in_time", "15:00")
new = (await _crawl(client, h, pid, "check_in_time", "16:00"))["fact"]["fact_id"]
body = (await client.post(f"/v1/place/{pid}/fact/{new}/transition", headers=h,
json={"status": FactStatus.VERIFIED.value})).json()
assert body["result"]["success"] is True
assert body["outcome"] == FactWriteOutcome.PUBLISHED_REPLACED.value
published = (await _facts(client, h, pid, publishable_only=True))["facts"]
assert len(published) == 1 and published[0]["value"] == "16:00"
assert (await _facts(client, h, pid))["pending_review"] == 0
async def test_repeated_recrawl_does_not_pile_up_candidates(auth_headers, client):
"""검증: 같은 출처로 재수집을 세 번 반복한다."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="r4")
await _own(client, h, pid, "check_in_time", "15:00")
await _crawl(client, h, pid, "check_in_time", "16:00")
body = await _crawl(client, h, pid, "check_in_time", "17:00")
assert body["outcome"] == FactWriteOutcome.CANDIDATE_UPDATED.value
listed = await _facts(client, h, pid)
assert listed["pending_review"] == 1
candidate = next(f for f in listed["facts"] if f["status"] == FactStatus.PENDING_OWNER.value)
assert candidate["value"] == "17:00"
async def test_recrawl_cannot_overwrite_corrected_value(auth_headers, client):
"""검증: 사람이 정정한 값(CORRECTED)에 다른 값이 재수집된다."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="r5")
fid = (await _crawl(client, h, pid, "check_in_time", "15:00"))["fact"]["fact_id"]
await client.post(f"/v1/place/{pid}/fact/{fid}/transition", headers=h, json={"status": FactStatus.VERIFIED.value})
await client.post(f"/v1/place/{pid}/fact/{fid}/transition", headers=h,
json={"status": FactStatus.CORRECTED.value, "value": "16:00"})
body = await _crawl(client, h, pid, "check_in_time", "15:00")
assert body["result"]["success"] is True
assert body["fact"]["status"] == FactStatus.PENDING_OWNER.value
published = (await _facts(client, h, pid, publishable_only=True))["facts"]
assert len(published) == 1
assert published[0]["value"] == "16:00", "★ 자동 수집이 사람 정정본을 덮어쓰면 안 된다"
assert published[0]["status"] == FactStatus.CORRECTED.value
# OTA 가 아직 15:00 이라는 사실은 후보로 남아 있어야 한다(신호를 버리지 않는다).
assert (await _facts(client, h, pid))["pending_review"] == 1
# ── 수정 프로세스 ────────────────────────────────────────────────────────
async def test_owner_input_publishes_immediately(auth_headers, client):
"""검증: 사람이 직접 값을 넣는다."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="o1")
body = await _own(client, h, pid, "check_in_time", "15:00")
assert body["outcome"] == FactWriteOutcome.PUBLISHED_CREATED.value
assert body["fact"]["status"] == FactStatus.VERIFIED.value
assert (await _facts(client, h, pid))["publishable"] == 1
async def test_owner_can_overwrite_own_value(auth_headers, client):
"""검증: 사람이 자기가 넣은 값을 다시 고친다."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="o2")
await _own(client, h, pid, "check_in_time", "15:00")
body = await _own(client, h, pid, "check_in_time", "17:00")
assert body["outcome"] == FactWriteOutcome.PUBLISHED_REPLACED.value
published = (await _facts(client, h, pid, publishable_only=True))["facts"]
assert len(published) == 1 and published[0]["value"] == "17:00"
async def test_publishing_marks_place_for_rebuild(auth_headers, client):
"""검증: 노출값이 바뀐 뒤 사업장의 content_updated_at."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="o3")
assert (await client.get(f"/v1/place/{pid}", headers=h)).json()["place"].get("content_updated_at") is None
await _own(client, h, pid, "check_in_time", "15:00")
place = (await client.get(f"/v1/place/{pid}", headers=h)).json()["place"]
assert place["content_updated_at"] is not None
async def test_crawl_only_does_not_mark_rebuild(auth_headers, client):
"""검증: 크롤링이 후보만 쌓았을 때 재빌드 표시."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="o4")
await _own(client, h, pid, "check_in_time", "15:00")
before = (await client.get(f"/v1/place/{pid}", headers=h)).json()["place"].get("content_updated_at")
await _crawl(client, h, pid, "check_in_time", "16:00")
place = (await client.get(f"/v1/place/{pid}", headers=h)).json()["place"]
assert place.get("content_updated_at") == before, "후보만 쌓였는데 재빌드 대상이 됐다"
async def test_facts_are_scoped_to_owner(auth_headers, client):
"""검증: 다른 사장님 계정으로 남의 사업장 fact 를 조회한다."""
h1 = await auth_headers("o1")
pid = await _verified_place(client, h1, kakao="p6")
h2 = await auth_headers("o2")
r = await client.get(f"/v1/place/{pid}/fact/list", headers=h2)
assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value
# ── 캔버스 미리보기 요약 ────────────────────────────────────────────────────
async def test_long_intro_gets_ai_summary_in_list(auth_headers, client, monkeypatch):
"""검증: intro 가 요약 임계치(200자)를 넘는다."""
async def _fake_summarize(text, **_kwargs):
return "축약된 소개문입니다."
monkeypatch.setattr(gt, "summarize_text", _fake_summarize)
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="sum1")
long_intro = "조용한 숙소입니다. " * 30 # 200자 초과
await _crawl(client, h, pid, "intro", long_intro, SourceType.LLM)
facts = await _facts(client, h, pid)
fact = next(f for f in facts["facts"] if f["key"] == "intro")
assert fact["value"] == long_intro
assert fact["summary"] == "축약된 소개문입니다."
async def test_short_intro_has_no_summary(auth_headers, client, monkeypatch):
"""검증: intro 가 임계치보다 짧다."""
calls = []
async def _fake_summarize(text, **_kwargs):
calls.append(text)
return "호출되면 안 된다"
monkeypatch.setattr(gt, "summarize_text", _fake_summarize)
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="sum2")
await _crawl(client, h, pid, "intro", "조용한 숙소입니다.", SourceType.LLM)
facts = await _facts(client, h, pid)
fact = next(f for f in facts["facts"] if f["key"] == "intro")
assert fact.get("summary") is None
assert calls == [], "짧은 문장인데 요약 API 를 불렀다"
async def test_non_intro_fact_never_gets_summary(auth_headers, client, monkeypatch):
"""검증: 길어도 intro/room_intro 가 아닌 key(예: cancel_policy)."""
calls = []
async def _fake_summarize(text, **_kwargs):
calls.append(text)
return "호출되면 안 된다"
monkeypatch.setattr(gt, "summarize_text", _fake_summarize)
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="sum3")
await _own(client, h, pid, "cancel_policy", "환불 규정 안내입니다. " * 30)
facts = await _facts(client, h, pid)
fact = next(f for f in facts["facts"] if f["key"] == "cancel_policy")
assert fact.get("summary") is None
assert calls == []