Merge branch 'main' into feature/crawler
This commit is contained in:
commit
dd3ad86715
160 files changed
+111240
-202
No files matched your search
@@ -52,7 +52,8 @@ async def _place_with_facts(client, h, n_verified=5):
|
||||
async def _faq_rows(db_engine, pid):
|
||||
async with db_engine.begin() as c:
|
||||
return (await c.execute(
|
||||
text("SELECT question, answer, source_fact_ids, status FROM place_faqs WHERE place_id = :p ORDER BY sort_order"),
|
||||
text("SELECT question, answer, source_fact_ids, status, generated_by FROM place_faqs "
|
||||
"WHERE place_id = :p ORDER BY sort_order"),
|
||||
{"p": uuid.UUID(pid)},
|
||||
)).all()
|
||||
|
||||
@@ -86,22 +87,29 @@ async def test_copy_generates_intro_and_faq_as_published(auth_headers, client, d
|
||||
assert intro[0]["source_type"] == SourceType.LLM.value
|
||||
|
||||
|
||||
async def test_copy_refuses_without_verified_facts(auth_headers, client, monkeypatch):
|
||||
"""검증: 확인된 fact 가 하나도 없는 사업장에서 생성을 시도한다.
|
||||
기대결과: FAQ_UNGROUNDED — ★ 잡을 만들지 않는다. 근거 없이 쓰면 환각이고 유료 호출만 낭비다."""
|
||||
async def _must_not_call_llm(*args, **kwargs):
|
||||
raise AssertionError("★ 근거 없이 LLM 을 불렀다")
|
||||
|
||||
|
||||
async def test_copy_refuses_without_facts_when_no_catalog(auth_headers, client, monkeypatch):
|
||||
"""검증: 확인된 fact 가 하나도 없는 **호텔**(펜션 카탈로그 제외 대상)에서 생성을 시도한다.
|
||||
기대결과: FAQ_UNGROUNDED — ★ 잡을 만들지 않는다. 쓸 근거도, 채울 공통 질문도 없다."""
|
||||
monkeypatch.setattr(gemini_text, "is_configured", lambda: True)
|
||||
h = await auth_headers("u1")
|
||||
pid = (await client.post("/v1/place", headers=h, json={"name": "빈펜션", "category": 1})).json()["place"]["place_id"]
|
||||
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": "빈주소"})
|
||||
pid = (await client.post("/v1/place", headers=h, json={"name": "빈호텔", "category": 1})).json()["place"]["place_id"]
|
||||
await client.post(f"/v1/place/{pid}/verify", headers=h,
|
||||
json={"source": 2, "road_address": "빈호텔주소", "category_name": "호텔"})
|
||||
|
||||
r = await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
|
||||
assert r.json()["result"]["code"] == ErrorType.FAQ_UNGROUNDED.value
|
||||
|
||||
|
||||
async def test_unverified_facts_are_not_used_as_grounding(auth_headers, client, monkeypatch):
|
||||
"""검증: 크롤링으로 들어온 미검증 fact 만 있는 사업장.
|
||||
기대결과: 근거로 안 쳐서 FAQ_UNGROUNDED — 미검증 값으로 쓴 문장도 미검증이다."""
|
||||
async def test_unverified_facts_are_not_used_as_grounding(auth_headers, client, db_engine, monkeypatch):
|
||||
"""검증: 크롤링으로 들어온 미검증 fact 만 있는 펜션.
|
||||
기대결과: ★ 근거 0건으로 친다 — LLM 을 부르지 않는다(미검증 값으로 쓴 문장도 미검증이다).
|
||||
FAQ 는 문의 안내로 20개를 채우고, 미검증인 체크인도 '답이 있는 주제' 로 치지 않는다."""
|
||||
monkeypatch.setattr(gemini_text, "is_configured", lambda: True)
|
||||
monkeypatch.setattr(gemini_text, "generate_copy", _must_not_call_llm)
|
||||
h = await auth_headers("u1")
|
||||
pid = (await client.post("/v1/place", headers=h, json={"name": "미검증펜션", "category": 1})).json()["place"]["place_id"]
|
||||
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": "미검증주소"})
|
||||
@@ -109,8 +117,36 @@ async def test_unverified_facts_are_not_used_as_grounding(auth_headers, client,
|
||||
"key": "check_in_time", "value": "15:00",
|
||||
"source_type": SourceType.CRAWL.value, "source_url": "https://ota.test/1"})
|
||||
|
||||
r = await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
|
||||
assert r.json()["result"]["code"] == ErrorType.FAQ_UNGROUNDED.value
|
||||
body = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()
|
||||
assert body["result"]["success"] is True and body["grounded_facts"] == 0
|
||||
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
|
||||
job = (await client.get(f"/v1/job/{body['job_id']}", headers=h)).json()["job"]
|
||||
assert job["status"] == JobStatus.DONE.value, job.get("last_error")
|
||||
assert job["result"]["faqs"] == 0 and job["result"]["faq_fill"] == 20
|
||||
|
||||
live = [r for r in await _faq_rows(db_engine, pid) if r[3] in _PUBLISHABLE]
|
||||
assert len(live) == 20 and all(r[4] == SourceType.TEMPLATE.value for r in live)
|
||||
assert any("체크인" in r[0] for r in live)
|
||||
|
||||
|
||||
async def test_zero_facts_still_fill_twenty_without_api_key(auth_headers, client, db_engine, monkeypatch):
|
||||
"""검증: fact 0건 · GEMINI 키 없음인 펜션(분류 없음 — 스테이머뭄처럼).
|
||||
기대결과: ★ 잡이 만들어지고 FAQ 가 정확히 20건 — 채우기는 LLM 을 안 쓰므로 키가 필요 없다."""
|
||||
monkeypatch.setattr(gemini_text, "is_configured", lambda: False)
|
||||
monkeypatch.setattr(gemini_text, "generate_copy", _must_not_call_llm)
|
||||
h = await auth_headers("u1")
|
||||
pid = (await client.post("/v1/place", headers=h, json={"name": "무근거펜션", "category": 1})).json()["place"]["place_id"]
|
||||
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": "무근거주소"})
|
||||
|
||||
body = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()
|
||||
assert body["result"]["success"] is True, body["result"]
|
||||
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
|
||||
job = (await client.get(f"/v1/job/{body['job_id']}", headers=h)).json()["job"]
|
||||
assert job["status"] == JobStatus.DONE.value, job.get("last_error")
|
||||
assert job["result"]["faq_fill"] == 20
|
||||
|
||||
live = [r for r in await _faq_rows(db_engine, pid) if r[3] in _PUBLISHABLE]
|
||||
assert len(live) == 20 and len({r[0] for r in live}) == 20
|
||||
|
||||
|
||||
async def test_faq_without_grounding_is_dropped(auth_headers, client, db_engine, monkeypatch):
|
||||
@@ -128,7 +164,10 @@ async def test_faq_without_grounding_is_dropped(auth_headers, client, db_engine,
|
||||
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
|
||||
assert job["result"]["faqs"] == 1
|
||||
assert any("수영장" in str(r) for r in job["result"]["rejected"])
|
||||
assert len(await _faq_rows(db_engine, pid)) == 1
|
||||
rows = await _faq_rows(db_engine, pid)
|
||||
assert len([r for r in rows if r[4] == SourceType.LLM.value]) == 1
|
||||
# 채우기가 넣은 문의 안내에도 '수영장 있나요?' 의 거짓 답("네 있습니다")은 없다.
|
||||
assert not any("있습니다" in r[1] for r in rows if r[4] == SourceType.TEMPLATE.value)
|
||||
|
||||
|
||||
async def test_rejected_sentences_are_reported(auth_headers, client, monkeypatch):
|
||||
@@ -161,9 +200,10 @@ async def test_regeneration_keeps_faq_the_owner_corrected(auth_headers, client,
|
||||
# 사장님이 문구를 고쳐 승인 — 잠긴 상태(CORRECTED)가 되고 책임 주체가 사람으로 넘어온다.
|
||||
async with db_engine.begin() as c:
|
||||
await c.execute(
|
||||
text("UPDATE place_faqs SET status = :s, generated_by = :g, question = :q WHERE place_id = :p"),
|
||||
text("UPDATE place_faqs SET status = :s, generated_by = :g, question = :q "
|
||||
"WHERE place_id = :p AND generated_by = :llm"),
|
||||
{"s": FactStatus.CORRECTED.value, "g": SourceType.OWNER.value,
|
||||
"q": "체크인 시간이 어떻게 되나요?", "p": uuid.UUID(pid)},
|
||||
"q": "체크인 시간이 어떻게 되나요?", "p": uuid.UUID(pid), "llm": SourceType.LLM.value},
|
||||
)
|
||||
|
||||
_patch(monkeypatch, _copy(faqs=[gemini_text.GeneratedFaq("새 질문?", "새 답변", ["check_in_time"])]))
|
||||
@@ -177,6 +217,55 @@ async def test_regeneration_keeps_faq_the_owner_corrected(auth_headers, client,
|
||||
assert any(r[0] == "새 질문?" and r[3] == FactStatus.VERIFIED.value for r in rows)
|
||||
|
||||
|
||||
_PUBLISHABLE = (FactStatus.VERIFIED.value, FactStatus.CORRECTED.value)
|
||||
|
||||
|
||||
async def test_copy_fills_faqs_to_target_without_duplicates(auth_headers, client, db_engine, monkeypatch):
|
||||
"""검증: 생성된 FAQ 가 1건뿐이고, 사장님이 직접 쓴 FAQ 가 1건 있다.
|
||||
기대결과: 노출 중 FAQ 가 정확히 20건 —
|
||||
· 모자란 만큼은 문의 안내(TEMPLATE)로 채운다
|
||||
· fact 로 답할 수 있는 주제(체크인·체크아웃·취소·취사·반려동물)에는 문의 안내를 붙이지 않는다
|
||||
· 사장님이 이미 쓴 주제(보증금)도 다시 넣지 않는다"""
|
||||
_patch(monkeypatch, _copy())
|
||||
h = await auth_headers("u1")
|
||||
pid = await _place_with_facts(client, h)
|
||||
owner = await client.post(f"/v1/place/{pid}/faq", headers=h, json={"question": "보증금이 있나요?", "answer": "없습니다."})
|
||||
assert owner.json()["result"]["success"] is True
|
||||
|
||||
job_id = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()["job_id"]
|
||||
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
|
||||
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
|
||||
assert job["status"] == JobStatus.DONE.value, job.get("last_error")
|
||||
assert job["result"]["faqs"] == 1
|
||||
assert job["result"]["faq_fill"] == 18
|
||||
|
||||
live = [r for r in await _faq_rows(db_engine, pid) if r[3] in _PUBLISHABLE]
|
||||
assert len(live) == 20
|
||||
assert len({r[0] for r in live}) == 20, "같은 질문이 두 번 들어갔다"
|
||||
|
||||
fills = [r for r in live if r[4] == SourceType.TEMPLATE.value]
|
||||
assert len(fills) == 18
|
||||
fill_text = " ".join(r[0] for r in fills)
|
||||
for topic in ("체크인", "체크아웃", "취소", "요리", "반려동물", "보증금"):
|
||||
assert topic not in fill_text, f"★ 이미 답이 있는 주제 '{topic}' 에 문의 안내가 붙었다"
|
||||
assert all("문의" in r[1] or "확인" in r[1] for r in fills), "문의 안내가 아닌 답이 섞였다"
|
||||
|
||||
|
||||
async def test_regeneration_replaces_fill_faqs(auth_headers, client, db_engine, monkeypatch):
|
||||
"""검증: 생성을 두 번 돌린다.
|
||||
기대결과: 노출 중 FAQ 는 여전히 20건 — 옛 문의 안내는 내려가고 다시 고른다(쌓이지 않는다)."""
|
||||
_patch(monkeypatch, _copy())
|
||||
h = await auth_headers("u1")
|
||||
pid = await _place_with_facts(client, h)
|
||||
for _ in range(2):
|
||||
await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
|
||||
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
|
||||
|
||||
live = [r for r in await _faq_rows(db_engine, pid) if r[3] in _PUBLISHABLE]
|
||||
assert len(live) == 20
|
||||
assert len({r[0] for r in live}) == 20
|
||||
|
||||
|
||||
async def test_copy_requires_api_key(auth_headers, client, monkeypatch):
|
||||
"""검증: GEMINI_API_KEY 없이 생성을 시도한다.
|
||||
기대결과: GENERATOR_NOT_CONFIGURED — 잡을 만들지 않는다."""
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""FAQ 목표 수 채우기 — ★ 공통 답은 문의 안내뿐이고, 이미 다룬 주제는 다시 넣지 않는다.
|
||||
|
||||
이 기능이 절대 하면 안 되는 것:
|
||||
- 공통 답에 값·가능 여부를 적는 것 (가게마다 다르다 — 틀리면 예약 클레임)
|
||||
- fact 로 답할 수 있는 질문에 "문의 부탁드립니다" 를 붙이는 것 (아는 것을 숨긴다)
|
||||
- 기존 FAQ 와 같은 주제를 다시 넣는 것
|
||||
"""
|
||||
import re
|
||||
|
||||
from common.enums import ErrorType, PlaceCategory
|
||||
from common.faq_catalog import find_catalog
|
||||
from services import faq_fill
|
||||
from services.faq_fill import ExistingFaq
|
||||
|
||||
|
||||
def _pension():
|
||||
catalog = find_catalog(PlaceCategory.LODGING.value, "펜션")
|
||||
assert catalog is not None
|
||||
return catalog
|
||||
|
||||
|
||||
def _ids(picks):
|
||||
return {p.catalog_id for p in picks}
|
||||
|
||||
|
||||
def test_pension_catalog_has_thirty_questions():
|
||||
"""검증: 카탈로그 로드. fact_keys 가 업종 스키마에 없으면 로더가 예외를 던진다."""
|
||||
catalog = _pension()
|
||||
assert len(catalog.items) == 30
|
||||
assert len({item.id for item in catalog.items}) == 30
|
||||
|
||||
|
||||
def test_catalog_scope():
|
||||
"""검증: 호텔·카페에는 펜션 질문을 붙이지 않는다. 분류가 비어 있는 숙박업(스테이머뭄)에는 붙인다."""
|
||||
assert find_catalog(PlaceCategory.LODGING.value, "호텔") is None
|
||||
assert find_catalog(PlaceCategory.CAFE.value, None) is None
|
||||
assert find_catalog(PlaceCategory.LODGING.value, None) is not None
|
||||
|
||||
|
||||
def test_fills_only_the_shortfall():
|
||||
"""검증: 기존 FAQ 5건(카탈로그와 무관한 질문). 기대결과: 15건만 고른다. 20건이면 0건."""
|
||||
catalog = _pension()
|
||||
picks = faq_fill.pick_fill_faqs(catalog, [ExistingFaq(f"기타 질문 {i}") for i in range(5)], set())
|
||||
assert len(picks) == 15 and len(_ids(picks)) == 15
|
||||
assert faq_fill.pick_fill_faqs(catalog, [ExistingFaq(f"질문 {i}") for i in range(20)], set()) == []
|
||||
|
||||
|
||||
def test_skips_topics_answerable_by_facts():
|
||||
"""검증: 체크인·반려동물 fact 가 있다(객실 fact 는 'A동:max_capacity' 로 적힌다).
|
||||
기대결과: 그 질문들은 문의 안내로 채우지 않는다 — LLM 이 fact 로 답할 자리다."""
|
||||
picks = faq_fill.pick_fill_faqs(_pension(), [], {"check_in_time", "pet_allowed", "A동:max_capacity"}, target=30)
|
||||
assert not _ids(picks) & {"check_in", "pet", "capacity"}
|
||||
|
||||
|
||||
def test_skips_topics_already_asked_by_keyword():
|
||||
"""검증: 사장님이 근거 key 없이 쓴 FAQ 가 있다. 기대결과: 질문 낱말로 같은 주제를 알아본다."""
|
||||
existing = [ExistingFaq("반려견 데려가도 되나요?"), ExistingFaq("주차 되나요?")]
|
||||
picks = faq_fill.pick_fill_faqs(_pension(), existing, set(), target=30)
|
||||
assert not _ids(picks) & {"pet", "parking"}
|
||||
|
||||
|
||||
def test_skips_topics_covered_by_source_fact_keys():
|
||||
"""검증: LLM FAQ 의 질문에는 키워드가 없지만 근거 key 가 [wifi, A동:max_capacity] 다.
|
||||
기대결과: 와이파이·인원 질문을 넣지 않는다 — LLM 은 두 주제를 한 문항에 묶기도 한다."""
|
||||
existing = [ExistingFaq("편의 안내가 궁금해요", ["wifi", "A동:max_capacity"])]
|
||||
picks = faq_fill.pick_fill_faqs(_pension(), existing, set(), target=30)
|
||||
assert not _ids(picks) & {"wifi", "capacity"}
|
||||
|
||||
|
||||
def test_answers_are_inquiry_only():
|
||||
"""검증: 공통 답 문구.
|
||||
기대결과: ★ 연락처가 없으면 숫자가 하나도 없다(가격·시각을 지어내지 않는다). 연락처가 있으면 그 번호만 들어간다."""
|
||||
catalog = _pension()
|
||||
for pick in faq_fill.pick_fill_faqs(catalog, [], set(), target=30):
|
||||
assert not re.search(r"\d", pick.answer), pick.answer
|
||||
assert "숙소" in pick.answer
|
||||
for pick in faq_fill.pick_fill_faqs(catalog, [], set(), phone="010-1234-5678", target=30):
|
||||
assert "전화(010-1234-5678)로" in pick.answer
|
||||
assert not re.search(r"\d", pick.answer.replace("010-1234-5678", "")), pick.answer
|
||||
|
||||
|
||||
def test_answer_particle_and_rotation():
|
||||
"""검증: 주제 뒤 조사(은/는)와 문구 돌려쓰기."""
|
||||
catalog = _pension()
|
||||
assert faq_fill.fallback_answer(catalog, 0, "보증금 여부", None).startswith("보증금 여부는 ")
|
||||
assert faq_fill.fallback_answer(catalog, 0, "주변 편의시설", None).startswith("주변 편의시설은 ")
|
||||
assert len({faq_fill.fallback_answer(catalog, i, "주제", None) for i in range(3)}) == 3
|
||||
|
||||
|
||||
def test_suggested_questions_are_the_answerable_ones():
|
||||
"""검증: 프롬프트에 실을 질문 = fact 로 답할 수 있는 카탈로그 질문."""
|
||||
questions = faq_fill.suggested_questions(_pension(), {"parking", "check_out_time"})
|
||||
assert questions == ["체크아웃은 몇 시까지인가요?", "주차할 수 있나요? 몇 대까지 가능한가요?"]
|
||||
|
||||
|
||||
async def test_template_source_cannot_write_fact(auth_headers, client):
|
||||
"""검증: fact 를 TEMPLATE 출처로 쓴다.
|
||||
기대결과: INVALID_REQUEST_DATA — 막지 않으면 사람 입력처럼 바로 노출값이 된다(fact_service 규칙 4)."""
|
||||
h = await auth_headers("u1")
|
||||
pid = (await client.post("/v1/place", headers=h, json={"name": "틀펜션", "category": 1})).json()["place"]["place_id"]
|
||||
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": "틀주소"})
|
||||
r = await client.post(f"/v1/place/{pid}/fact", headers=h, json={
|
||||
"key": "check_in_time", "value": "15:00", "source_type": 5, "source_url": "template:test"})
|
||||
assert r.json()["result"]["code"] == ErrorType.INVALID_REQUEST_DATA.value
|
||||
@@ -0,0 +1,321 @@
|
||||
"""발행 사이트 메타 태그 키워드(SiteOntology).
|
||||
|
||||
이 경로가 절대 하면 안 되는 것:
|
||||
- 이 가게 자료에 없는 낱말이 든 키워드를 메타 태그·제목에 싣는 것
|
||||
(확인 안 된 시설 · 다른 권역 · 가격 주장)
|
||||
- SiteOntology 실패로 발행을 막는 것 — 키워드는 곁들이다
|
||||
- 해석되지 않은 업체의 추천(입력 문자열로 검색한 결과)을 쓰는 것
|
||||
- 숙박이 아닌 업종에 펜션 키워드를 붙이는 것
|
||||
|
||||
★ MATCH 의 matches 1~10 · byLane 은 실제 응답에서 옮겼다 — 2026-09-14 로컬 SiteOntology(:3100) 에
|
||||
스테이머뭄 프로필(features 독채·프라이빗, audiences 커플·가족, nearby 말랭이마을·동국사)을 보낸 결과.
|
||||
11~13 은 같은 사전에 실제로 있는 단어로, 거르기 규칙을 보려고 붙였다.
|
||||
"""
|
||||
import json
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.enums import JobStatus, LocalContentType, MediaStatus, PlaceCategory, SiteStatus, SourceType
|
||||
from crud.job_crud import JobQueue
|
||||
from services import seo_keywords
|
||||
from services.external import site_ontology
|
||||
from worker.handlers import build_handler
|
||||
from worker.runner import Worker
|
||||
|
||||
|
||||
def _kw(canonical, category, intent="local", status="ok"):
|
||||
return {"canonical": canonical, "category": category, "intent": intent, "kind": "keyword", "status": status}
|
||||
|
||||
|
||||
MATCH = {
|
||||
"mode": "fusion",
|
||||
"matches": [
|
||||
_kw("군산 펜션 독채", "시설"),
|
||||
_kw("군산 독채펜션", "코어"),
|
||||
_kw("군산 독채 마당 펜션", "롱테일"),
|
||||
_kw("군산 독채 복층 펜션", "롱테일"),
|
||||
_kw("군산 커플 프라이빗 펜션", "롱테일"),
|
||||
_kw("군산 독채펜션 예약", "코어", intent="transactional"),
|
||||
_kw("군산에 독채 펜션 있나요", "질문형", intent="informational"),
|
||||
_kw("군산 가족 독채펜션", "동반자"),
|
||||
_kw("말랭이마을 근처 숙소", "관광지"),
|
||||
_kw("군산 프라이빗한 독채", "분위기"),
|
||||
_kw("선유도 독채펜션", "권역"),
|
||||
_kw("군산 펜션 최저가", "의도", intent="transactional"),
|
||||
_kw("군산 주차 펜션", "시설", status="hold"),
|
||||
],
|
||||
"byLane": [
|
||||
{"key": "type", "label": "유형", "items": [
|
||||
_kw("군산 펜션 독채", "시설"),
|
||||
_kw("군산 독채펜션", "코어"),
|
||||
_kw("군산 독채 마당 펜션", "롱테일"),
|
||||
]},
|
||||
{"key": "place", "label": "위치", "items": [_kw("말랭이마을 근처 숙소", "관광지")]},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _fact(key, value, unit_id=None):
|
||||
return {"key": key, "value": value, "scope": "unit" if unit_id else "place", "unit_id": unit_id, "status": 3}
|
||||
|
||||
|
||||
def _snapshot(**place):
|
||||
return {
|
||||
"place": {
|
||||
"name": "스테이,머뭄", "category": PlaceCategory.LODGING.value,
|
||||
"road_address": "전북특별자치도 군산시 절골길 18", "address": None, **place,
|
||||
},
|
||||
"facts": [
|
||||
_fact("intro", "군산 원도심 말랭이마을 옆 독채 스테이.\n두 번째 문단은 싣지 않는다."),
|
||||
_fact("bbq_available", "false"),
|
||||
_fact("parking", "true"),
|
||||
_fact("room_type", "독채", unit_id="u1"),
|
||||
_fact("max_capacity", "4", unit_id="u1"),
|
||||
_fact("max_capacity", "2", unit_id="u2"),
|
||||
],
|
||||
"local": {"contents": [
|
||||
{"content_type": LocalContentType.ATTRACTION.value, "title": "말랭이마을", "body": {"name": "말랭이마을"}},
|
||||
{"content_type": LocalContentType.RESTAURANT.value, "title": "이성당", "body": {"name": "이성당"}},
|
||||
{"content_type": LocalContentType.ATTRACTION.value, "title": "동국사", "body": {}},
|
||||
]},
|
||||
}
|
||||
|
||||
|
||||
# ── 요청 만들기 ─────────────────────────────────────────────────────────────
|
||||
def test_스냅샷으로_업체_프로필을_만든다():
|
||||
"""검증: 확인된 fact·지역 정보가 든 숙박 스냅샷.
|
||||
기대결과: 있음(true)은 features, 모름(fact 없음)은 unverified, 없음(false)은 어디에도 없다."""
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
|
||||
assert merchant == {
|
||||
"externalId": "place-1",
|
||||
"name": "스테이,머뭄",
|
||||
"industryId": "stay.pension",
|
||||
"regionId": "kr.jeonbuk.gunsan",
|
||||
"description": "군산 원도심 말랭이마을 옆 독채 스테이.",
|
||||
"profile": {
|
||||
"address": "전북특별자치도 군산시 절골길 18",
|
||||
"capacity": {"max": 4},
|
||||
"features": ["주차", "독채"],
|
||||
# 음식점(이성당)은 주변 관광지가 아니다.
|
||||
"nearby": ["말랭이마을", "동국사"],
|
||||
# ★ 바베큐는 false(없음)라 여기 없다 — 넣으면 SiteOntology 가 배제 대신 보류한다.
|
||||
"unverified": ["애견동반", "조식"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_숙박이_아니면_부르지_않는다():
|
||||
assert seo_keywords.build_merchant("place-1", _snapshot(category=PlaceCategory.CAFE.value)) is None
|
||||
|
||||
|
||||
def test_표에_없는_지역은_지역을_비운다():
|
||||
"""검증: SiteOntology 지역 표(54개)에 없는 시·군.
|
||||
기대결과: 지어내지 않고 None — 없는 키를 보내면 SiteOntology 가 500 이다."""
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot(road_address="서울특별시 강남구 테헤란로 1"))
|
||||
assert merchant["regionId"] is None
|
||||
|
||||
|
||||
def test_같은_이름의_시군은_시도로_가른다():
|
||||
assert seo_keywords.region_key("강원특별자치도 고성군 토성면 1") == "kr.gangwon.goseong"
|
||||
assert seo_keywords.region_key("경상남도 고성군 고성읍 1") is None
|
||||
|
||||
|
||||
# ── 거르기 ─────────────────────────────────────────────────────────────────
|
||||
def test_자료가_뒷받침하는_키워드만_남긴다():
|
||||
"""검증: 실제 추천 결과를 이 가게 자료(주차·독채·원도심·말랭이마을·동국사)로 거른다.
|
||||
기대결과: 마당·복층·커플·가족·프라이빗(확인 안 됨), 선유도(다른 권역), 최저가(가격 주장),
|
||||
질문형, 보류(hold)가 모두 빠진다. 순위는 SiteOntology 순서 그대로."""
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
seo = seo_keywords.select(MATCH, merchant)
|
||||
|
||||
assert seo["keywords"] == ["군산 펜션 독채", "군산 독채펜션", "군산 독채펜션 예약", "말랭이마을 근처 숙소"]
|
||||
|
||||
|
||||
def test_제목_키워드는_유형_레인의_코어를_고른다():
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
assert seo_keywords.select(MATCH, merchant)["titleKeyword"] == "군산 독채펜션"
|
||||
|
||||
|
||||
def test_제목에는_예약_추천과_지역_없는_단어를_쓰지_않는다():
|
||||
"""검증: 유형 레인 코어가 `… 예약` 이고, 지역명이 없는 태그가 섞였다.
|
||||
기대결과: 둘을 건너뛰고 `군산 펜션 독채` — 상호 옆에서 광고 문구가 되거나 지역 신호를 잃지 않는다."""
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
result = {"matches": [], "byLane": [{"key": "type", "items": [
|
||||
_kw("군산 독채펜션 예약", "코어", intent="transactional"),
|
||||
_kw("독채펜션", "태그"),
|
||||
_kw("군산 펜션 독채", "시설"),
|
||||
]}]}
|
||||
assert seo_keywords.select(result, merchant) == {"keywords": [], "titleKeyword": "군산 펜션 독채"}
|
||||
|
||||
|
||||
def test_업종어뿐인_단어는_싣지_않는다():
|
||||
"""검증: 낱말이 전부 업종어·"근처" 류인 추천(실측: 실제 발행에서 `숙소` 가 메타 한 칸을 차지했다).
|
||||
기대결과: 뺀다 — 어느 가게에나 붙는 단어라 이 가게를 설명하지 못한다. 자료 낱말이 섞이면 남긴다."""
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
result = {"matches": [_kw("숙소", "태그"), _kw("펜션 예약", "의도"), _kw("원도심", "태그")], "byLane": []}
|
||||
assert seo_keywords.select(result, merchant)["keywords"] == ["원도심"]
|
||||
|
||||
|
||||
def test_표기만_다른_중복은_하나로():
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
result = {"matches": [_kw("군산 독채펜션", "코어"), _kw("군산 독채 펜션", "태그")], "byLane": []}
|
||||
assert seo_keywords.select(result, merchant)["keywords"] == ["군산 독채펜션"]
|
||||
|
||||
|
||||
# ── 클라이언트 ────────────────────────────────────────────────────────────
|
||||
def _response(status, body, url):
|
||||
return httpx.Response(status, json=body, request=httpx.Request("POST", url))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ontology_url(monkeypatch):
|
||||
monkeypatch.setattr(site_ontology.external_api_config, "site_ontology_url", "http://onto.test/")
|
||||
|
||||
|
||||
def _fake_ontology(sent, *, reject_region=False, resolve=True):
|
||||
async def fake_post(self, url, json=None, **kwargs):
|
||||
sent.append((url, json))
|
||||
if url.endswith(site_ontology.PUBLISH_PATH):
|
||||
if reject_region and json.get("regionId"):
|
||||
# 실측: region 표에 없는 키 → 외래키 위반 → 500
|
||||
return _response(500, {"statusCode": 500, "message": "Internal server error"}, url)
|
||||
return _response(201, {"merchant": {"external_id": json["externalId"]}, "generation": "skipped"}, url)
|
||||
resolved = {"externalId": json["query"]} if resolve else None
|
||||
return _response(201, {**MATCH, "resolved": resolved}, url)
|
||||
|
||||
return fake_post
|
||||
|
||||
|
||||
async def test_업체를_저장한_뒤_그_업체로_추천을_받는다(ontology_url, monkeypatch):
|
||||
sent = []
|
||||
monkeypatch.setattr(httpx.AsyncClient, "post", _fake_ontology(sent))
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
|
||||
await site_ontology.match_for_merchant(merchant)
|
||||
|
||||
assert [url for url, _ in sent] == ["http://onto.test/v1/merchants/publish", "http://onto.test/v1/match"]
|
||||
# ★ generate:false 가 빠지면 SiteOntology 가 LLM 키워드 생성을 큐에 넣는다.
|
||||
assert sent[0][1] == {**merchant, "generate": False}
|
||||
assert sent[1][1] == {"query": "place-1", "limit": site_ontology.DEFAULT_LIMIT}
|
||||
|
||||
|
||||
async def test_지역_키가_거절되면_지역_없이_다시_보낸다(ontology_url, monkeypatch):
|
||||
sent = []
|
||||
monkeypatch.setattr(httpx.AsyncClient, "post", _fake_ontology(sent, reject_region=True))
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
|
||||
await site_ontology.match_for_merchant(merchant)
|
||||
|
||||
publishes = [body for url, body in sent if url.endswith(site_ontology.PUBLISH_PATH)]
|
||||
assert [b["regionId"] for b in publishes] == ["kr.jeonbuk.gunsan", None]
|
||||
assert sent[-1][0].endswith(site_ontology.MATCH_PATH)
|
||||
|
||||
|
||||
async def test_업체가_해석되지_않은_추천은_쓰지_않는다(ontology_url, monkeypatch):
|
||||
"""검증: match 가 resolved=null 로 201 을 준다(입력 문자열로 검색한 결과).
|
||||
기대결과: 실패로 본다 — 그 결과는 남의 동네 단어다(실측: `나운동 숙소`)."""
|
||||
monkeypatch.setattr(httpx.AsyncClient, "post", _fake_ontology([], resolve=False))
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
|
||||
with pytest.raises(site_ontology.SiteOntologyError):
|
||||
await site_ontology.match_for_merchant(merchant)
|
||||
assert await seo_keywords.fetch("place-1", _snapshot()) is None
|
||||
|
||||
|
||||
async def test_주소가_비면_부르지_않는다(monkeypatch):
|
||||
monkeypatch.setattr(site_ontology.external_api_config, "site_ontology_url", "")
|
||||
|
||||
async def boom(self, url, json=None, **kwargs):
|
||||
raise AssertionError("설정이 비었는데 SiteOntology 를 불렀다")
|
||||
|
||||
monkeypatch.setattr(httpx.AsyncClient, "post", boom)
|
||||
assert await seo_keywords.fetch("place-1", _snapshot()) is None
|
||||
|
||||
|
||||
async def test_연결이_안_되면_예외를_올리지_않는다(ontology_url, monkeypatch):
|
||||
async def refused(self, url, json=None, **kwargs):
|
||||
raise httpx.ConnectError("connection refused", request=httpx.Request("POST", url))
|
||||
|
||||
monkeypatch.setattr(httpx.AsyncClient, "post", refused)
|
||||
assert await seo_keywords.fetch("place-1", _snapshot()) is None
|
||||
|
||||
|
||||
# ── 발행 한 바퀴 ───────────────────────────────────────────────────────────
|
||||
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 _published_place(client, h, db_engine):
|
||||
pid = (await client.post("/v1/place", headers=h, json={"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",
|
||||
})
|
||||
for k, v in {**REQUIRED, "intro": "하조대 해변 도보 3분 거리의 독채 펜션입니다.", "facilities": "독채"}.items():
|
||||
await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": v})
|
||||
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": "2층 목조 건물 외관", "l": "외관"},
|
||||
)
|
||||
return pid
|
||||
|
||||
|
||||
async def _build(client, h, pid) -> dict:
|
||||
job_id = (await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})).json()["job_id"]
|
||||
assert await Worker("w", JobQueue(), build_handler(), job_deadline_sec=60).process_one() is True
|
||||
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
|
||||
assert job["status"] == JobStatus.DONE.value, job.get("last_error")
|
||||
return job["result"]
|
||||
|
||||
|
||||
async def test_발행_payload_에_키워드가_실린다(auth_headers, client, db_engine, ontology_url, monkeypatch):
|
||||
"""검증: SiteOntology 가 켜진 채로 숙박 사업장을 발행한다.
|
||||
기대결과: 스냅샷으로 만든 프로필이 나가고, 거른 키워드가 payload.seo 로 실린다."""
|
||||
h = await auth_headers("u1")
|
||||
pid = await _published_place(client, h, db_engine)
|
||||
sent = []
|
||||
|
||||
async def fake_match(merchant, limit=site_ontology.DEFAULT_LIMIT):
|
||||
sent.append(merchant)
|
||||
return {"resolved": {"externalId": merchant["externalId"]},
|
||||
"matches": [_kw("양양 독채펜션", "코어"), _kw("양양 독채 마당 펜션", "롱테일")],
|
||||
"byLane": [{"key": "type", "items": [_kw("양양 독채펜션", "코어")]}]}
|
||||
|
||||
monkeypatch.setattr(site_ontology, "match_for_merchant", fake_match)
|
||||
r = await _build(client, h, pid)
|
||||
|
||||
assert r["published"] is True
|
||||
assert sent[0]["externalId"] == pid
|
||||
assert sent[0]["regionId"] == "kr.gangwon.yangyang"
|
||||
assert "독채" in sent[0]["profile"]["features"]
|
||||
payload = json.loads(open(r["payload_path"], encoding="utf-8").read())
|
||||
assert payload["seo"] == {"keywords": ["양양 독채펜션"], "titleKeyword": "양양 독채펜션"}
|
||||
assert r["seo"] == payload["seo"]
|
||||
|
||||
|
||||
async def test_SiteOntology_가_죽어도_발행된다(auth_headers, client, db_engine, ontology_url, monkeypatch):
|
||||
h = await auth_headers("u1")
|
||||
pid = await _published_place(client, h, db_engine)
|
||||
|
||||
async def down(merchant, limit=site_ontology.DEFAULT_LIMIT):
|
||||
raise site_ontology.SiteOntologyError("ConnectError: connection refused")
|
||||
|
||||
monkeypatch.setattr(site_ontology, "match_for_merchant", down)
|
||||
r = await _build(client, h, pid)
|
||||
|
||||
assert r["published"] is True
|
||||
assert "seo" not in r
|
||||
site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()
|
||||
assert site["site"]["status"] == SiteStatus.PUBLISHED.value
|
||||
payload = json.loads(open(r["payload_path"], encoding="utf-8").read())
|
||||
assert "seo" not in payload
|
||||
Reference in new issue
Block a user