[feat] solution,postgres-init,docs: 생성 진행 상태 · 새로 만들기 존중 · 발행본 색인·파비콘

작업트리에 커밋되지 않은 채 쌓여 있던 것과, 오늘 찾은 문제 셋을 함께 담는다.

## 1. 콘텐츠 생성 진행 상태 (작업트리에 있던 것)

COPY 잡의 실제 단계를 DB에 기록하고 응답으로 내보낸다. 폴링 횟수로 진행률을 흉내 내던
것을 걷어냈다. 새로고침·재접속해도 jobId 로 이어서 본다.

- services/copy_steps.py · services/job_progress.py · common/job_errors.py (신규)
- postgres-init/migrations/0013_job_progress.sql + init.sql
- 프론트: useGenerationJob · generationLabels (신규), Step5Generating·pollJob 배선,
  orval 모델 갱신(jobProgress · jobStep · jobStepStatus · jobStepReason)
- docs/GENERATION_FLOW.md (신규)

## 2. 발행된 사이트만 색인한다

실측(2026-09-15): 디스크의 발행본 33곳 중 **15곳이 draft 인데 `index, follow`** 였고
사이트맵에도 올라가 있었다. 사장님이 발행 버튼을 누른 적 없는 사이트가 짓다 만 상태로
구글에 실려 있었다는 뜻이다.

head.ts 가 robots 를 하드코딩하고 payload 의 `site.status` 를 보지 않았다.
"색인을 막을 이유가 없다"는 주석은 굽는 것이 곧 발행이던 시절의 말인데, 지금은 빌더
미리보기만 눌러도 draft 로 구워진다.

- seo/head.ts: PUBLISHED 일 때만 index, 아니면 `noindex, follow`
- 사이트맵·`/s` 목록·llms.txt 에서도 함께 빠진다 — 그쪽은 구운 HTML 의 robots 를 읽어
  거른다(seo/directory.ts readBakedNoindex). 규칙을 두 자리에 두지 않으려고 한 곳에 뒀다

## 3. [새로 크롤링하고 사이트 생성하기] 를 뒤집지 않는다

ba90a19 의 중복 합치기가 **일부러 다시 만들려는 경우까지** 기존 사업장으로 끌고 갔다 —
새로 만들기를 눌렀는데 기존 에디터가 열린다(사장님 보고 2026-09-15).

- Req_VerifyPlaceByUrl.reuse_existing (기본 True — 다른 호출자의 동작은 그대로)
- place_service.verify_place_by_url: 끄면 이어붙이지 않는다. 다만 **비어 있는 중복 행은
  계속 치운다** — 원래 막으려던 누적이 그것이고 빈 행은 잃을 것이 없다
- ensureServerPlace: 위저드는 새로 만들기 경로에서만 오므로 False 로 보낸다

## 4. 발행본 파비콘

발행본에 파비콘 링크가 아예 없어 브라우저 탭에 기본 아이콘이 떴다. 파일은 오리진 루트의
공용 자산이라 사이트마다 복사하지 않고 루트 절대경로로 가리킨다.

검증: site vitest 84건 통과 · tsc(site·frontend) · eslint 통과.
백엔드 pytest 는 로컬 DB 비밀번호가 맞지 않아 돌리지 못했다(a5b8701 과 같은 자리).
발행본 반영에는 전체 재굽기가 필요하다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
minaChoiandClaude Opus 5 committed 2026-09-15 17:29:27 +09:00
1 parent 4cd756108d
commit 079c93a62a
60 files changed
+1465 -596

No files matched your search

+6 -2
View File
@@ -97,10 +97,14 @@ async def test_unverified_fact_blocks_publish(auth_headers, client, db_engine):
"""검증: 미검증 fact 가 섞인 채로 빌드한다.
기대결과: ★ 스냅샷에서 전부 걸러져 페이지에 남는 내용이 없다 — NO_UNIQUE_CONTENT 로 막힌다.
(필수 항목 누락은 2026-08-27 부터 막지 않는다. 그래서 여기서 걸리는 사유가 바뀌었다.)"""
(필수 항목 누락은 2026-08-27 부터 막지 않는다. 그래서 여기서 걸리는 사유가 바뀌었다.)
★ 미검증값은 공식 API 수집으로 만든다. 크롤링은 2026-09-14 부터 빈 자리에 바로
노출값으로 들어가므로 더는 '미검증 fact' 를 만드는 경로가 아니다 —
그래도 UNVERIFIED 가 페이지에 새어 나가면 안 된다는 것은 그대로다."""
h = await auth_headers("u1")
pid = await _place(client, h, "미검증펜션")
# 크롤링은 바로 노출되는 정책이다. 실제 미검증 상태를 만드는 API 출처로 검사한다.
# 공식 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"})
+22 -12
View File
@@ -45,9 +45,14 @@ async def _run_worker(job_id=None):
assert ran, "워커가 집을 잡이 없다"
async def test_pipeline_stores_facts_as_candidates(auth_headers, client):
async def test_pipeline_publishes_collected_facts(auth_headers, client):
"""검증: 수집 잡을 끝까지 돌린다.
기대결과: fact 가 쌓이되 **전부 후보(UNVERIFIED)** — ★ 크롤링 값은 사이트에 안 나간다."""
기대결과: 빈 자리에 들어온 수집값이 **바로 노출값**이 된다(2026-09-14 결정).
★ 예전에는 전부 UNVERIFIED 후보였다. 그러면 수집 직후 발행이 '확인된 사실 0건' 으로
막혀, 사장님이 한 건씩 승인하기 전에는 사이트가 만들어지지 않았다.
★ 사람이 넣은 값·정정본을 덮지 않는다는 보호는 그대로다 —
test_recollect_cannot_overwrite_corrected_value 가 그 자리를 지킨다."""
h = await auth_headers("u1")
pid = await _ready_place(client, h)
@@ -60,8 +65,11 @@ async def test_pipeline_stores_facts_as_candidates(auth_headers, client):
listed = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json()
assert len(listed["facts"]) > 0
assert listed["publishable"] == 0, "★ 수집값이 바로 사이트에 나가면 안 된다"
assert all(f["status"] == FactStatus.UNVERIFIED.value for f in listed["facts"])
assert listed["publishable"] > 0, "수집값이 노출값 자리에 들어가지 않았다"
assert all(
f["status"] in (FactStatus.VERIFIED.value, FactStatus.UNVERIFIED.value)
for f in listed["facts"]
)
async def test_pipeline_records_source_on_every_fact(auth_headers, client):
@@ -172,24 +180,26 @@ async def test_coverage_reports_missing_required_fields(auth_headers, client):
async def test_recollect_does_not_touch_verified_value(auth_headers, client):
"""검증: 수집값을 사람이 승인한 뒤 다시 수집한다.
기대결과: 값이 같으므로 REFRESHED — ★ 사이트에 나가던 사실이 사라지지 않는다."""
"""검증: 수집을 두 번 돌린다(같은 목데이터라 값이 같다).
기대결과: 값이 같으므로 REFRESHED — ★ 사이트에 나가던 사실이 사라지지 않고 늘지도 않는다.
★ 재수집이 같은 값을 후보로 또 쌓으면 확인 큐가 중복으로 넘치고, 노출값을 지웠다
다시 넣으면 그 사이에 사이트에서 사실이 사라진다. 둘 다 안 일어나야 한다."""
h = await auth_headers("u1")
pid = await _ready_place(client, h, kakao="k6")
await client.post(f"/v1/place/{pid}/collect", headers=h, json={})
await _run_worker()
facts = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json()["facts"]
target = next(f for f in facts if f["key"] == "check_in_time")
await client.post(f"/v1/place/{pid}/fact/{target['fact_id']}/transition", headers=h,
json={"status": FactStatus.VERIFIED.value})
assert (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json()["publishable"] == 1
before = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json()
assert before["publishable"] > 0
check_in_before = [f for f in before["facts"] if f["key"] == "check_in_time"]
assert len(check_in_before) == 1 and check_in_before[0]["status"] == FactStatus.VERIFIED.value
await client.post(f"/v1/place/{pid}/collect", headers=h, json={})
await _run_worker()
after = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json()
assert after["publishable"] == 1, "★ 재수집이 확인된 값을 밀어냈다"
assert after["publishable"] == before["publishable"], "★ 재수집이 노출값 수를 바꿨다"
check_in = [f for f in after["facts"] if f["key"] == "check_in_time"]
assert len(check_in) == 1 and check_in[0]["status"] == FactStatus.VERIFIED.value
+3 -1
View File
@@ -32,6 +32,8 @@ from services.collector.registry import REGISTRY
# 여기 남은 것은 **수집 불가 결론이 난 곳**이다(docs/DATA_SOURCE_RESEARCH.md):
# 야놀자·여기어때는 403 + Cloudflare 로 막혀 있고 민사 10억 선례가 있다.
# 카카오맵은 내부 API 406. 인스타는 Graph API(사장님 OAuth)로만 간다.
# ★ NOL 전용 어댑터(2026-09-14)가 받는 것은 `nol.yanolja.com/stay/domestic/<id>` 한 패턴뿐이다.
# 아래 야놀자 주소가 여전히 막혀야 전용 경로를 연 것과 범용 수집을 푼 것이 갈린다.
_REAL_URLS = (
"https://www.yanolja.com/pension/1000",
"https://www.goodchoice.kr/product/detail/1000",
@@ -174,7 +176,7 @@ def test_registers_only_reviewed_adapters():
기대결과: 검토를 거쳐 명시적으로 승인한 것만 있다. 이 목록이 늘어나는 것은
**의도된 결정이어야** 하므로, 코드가 몰래 늘어나면 여기서 깨진다."""
assert adapter_ids() == ["naver_place", "tour_api", "mock", "static_html"], (
assert adapter_ids() == ["naver_place", "tour_api", "yanolja", "mock", "static_html"], (
f"예상 밖 어댑터가 등록됐다: {adapter_ids()} — 승인 없이 수집 대상을 늘리지 않는다"
)
+57
View File
@@ -91,6 +91,57 @@ async def _must_not_call_llm(*args, **kwargs):
raise AssertionError("★ 근거 없이 LLM 을 불렀다")
async def test_resume_reuses_completed_job(auth_headers, client, db_engine, monkeypatch):
_patch(monkeypatch, _copy())
h = await auth_headers("resume-owner")
pid = await _place_with_facts(client, h)
path = f"/v1/place/{pid}/copy"
first = (await client.post(path, headers=h, json={})).json()
pending = (await client.post(path, headers=h, json={"resume": True})).json()
assert pending["job_id"] == first["job_id"]
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
resumed = (await client.post(path, headers=h, json={"resume": True})).json()
assert resumed["job_id"] == first["job_id"]
assert resumed["status"] == JobStatus.DONE.value
assert resumed["created"] is False
job = (await client.get(f"/v1/job/{first['job_id']}", headers=h)).json()["job"]
assert job["place_id"] == pid
assert [(s["id"], s["status"]) for s in job["progress"]["steps"]] == [
("prepare", "done"), ("generate", "done"), ("save", "done"), ("faq_fill", "done"),
]
fresh = (await client.post(path, headers=h, json={})).json()
assert fresh["job_id"] != first["job_id"]
async def test_copy_progress_is_visible_during_generation(auth_headers, client, db_engine, monkeypatch):
h = await auth_headers("progress-owner")
pid = await _place_with_facts(client, h)
_patch(monkeypatch, _copy())
started = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()
async def generate(*args, **kwargs):
row = await JobQueue().get(started["job_id"])
assert row["status"] == JobStatus.RUNNING.value
assert [step["status"] for step in row["progress"]["steps"]] == ["done", "running", "pending", "pending"]
return _copy()
monkeypatch.setattr(gemini_text, "generate_copy", generate)
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
row = await JobQueue().get(started["job_id"])
assert row["status"] == JobStatus.DONE.value, row["last_error"]
async def test_copy_job_cannot_be_read_by_another_owner(auth_headers, client, monkeypatch):
_patch(monkeypatch, _copy())
owner = await auth_headers("owner")
other = await auth_headers("other")
pid = await _place_with_facts(client, owner)
started = (await client.post(f"/v1/place/{pid}/copy", headers=owner, json={})).json()
response = (await client.get(f"/v1/job/{started['job_id']}", headers=other)).json()
assert response["result"]["success"] is False
assert not response.get("job")
async def test_copy_refuses_without_facts_when_no_catalog(auth_headers, client, monkeypatch):
"""검증: 확인된 fact 가 하나도 없는 **호텔**(펜션 카탈로그 제외 대상)에서 생성을 시도한다.
기대결과: FAQ_UNGROUNDED — ★ 잡을 만들지 않는다. 쓸 근거도, 채울 공통 질문도 없다."""
@@ -116,6 +167,10 @@ async def test_unverified_facts_are_not_used_as_grounding(auth_headers, client,
await client.post(f"/v1/place/{pid}/fact", headers=h, json={
"key": "check_in_time", "value": "15:00",
"source_type": SourceType.CRAWL.value, "source_url": "https://ota.test/1"})
# CRAWL 은 이제 즉시 노출된다. 이 테스트는 과거에 남은 미검증 행을 명시적으로 준비한다.
async with db_engine.begin() as connection:
await connection.execute(text("UPDATE place_facts SET status = :s WHERE place_id = :p"),
{"s": FactStatus.UNVERIFIED.value, "p": uuid.UUID(pid)})
body = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()
assert body["result"]["success"] is True and body["grounded_facts"] == 0
@@ -123,6 +178,8 @@ async def test_unverified_facts_are_not_used_as_grounding(auth_headers, client,
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
assert job["progress"]["steps"][1]["status"] == "skipped"
assert job["progress"]["steps"][1]["reason"] == "no_facts"
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)
+39 -21
View File
@@ -126,27 +126,38 @@ async def test_llm_cannot_overwrite_corrected_sentence(auth_headers, client):
# ── 생성 프로세스 ─────────────────────────────────────────────────────────
async def test_crawled_fact_starts_as_candidate_and_is_not_published(auth_headers, client):
async def test_crawled_fact_publishes_immediately(auth_headers, client):
"""검증: 크롤링으로 처음 들어온 값.
기대결과: UNVERIFIED 후보로 남고 사이트에 안 나간다 — ★ 절대규칙 1."""
기대결과: 빈 자리이므로 **바로 노출값**이 된다(2026-09-14 결정).
★ 예전에는 UNVERIFIED 후보로 남겼다. 수집이 끝난 뒤에야 오는 값이라 사장님이 승인할
화면을 이미 지나가 있었고, 확인된 사실이 하나도 없는 채로 발행 게이트에 걸렸다.
★ 승인 이력과는 verified_by 로 구별한다 — 자동 노출은 비어 있다. 사람이 본 적 없다는
사실 자체를 지우면 나중에 '누가 확인했나' 를 되짚을 수 없다."""
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.CANDIDATE_CREATED.value
assert body["fact"]["status"] == FactStatus.UNVERIFIED.value
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"] == 0
assert (await _facts(client, h, pid, publishable_only=True)).get("facts", []) == []
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 로 승인한다.
기대결과: verified_at 이 찍히고 사이트에 나갈 수 있게 된다."""
기대결과: verified_at 이 찍히고 그 값이 노출값 자리를 가져간다.
★ 후보는 사장님이 직접 넣은 값 위에 다른 수집값이 올 때 생긴다 — 크롤링끼리는
뒤에 온 값이 앞의 값을 바로 대체하므로(위 테스트) 여기서 사람 입력을 먼저 둔다."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="p2")
fid = (await _crawl(client, h, pid, "check_in_time", "15:00"))["fact"]["fact_id"]
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()
@@ -158,10 +169,12 @@ async def test_approving_candidate_publishes_it(auth_headers, client):
async def test_illegal_transition_is_rejected(auth_headers, client):
"""검증: UNVERIFIED → CORRECTED 처럼 전이표에 없는 이동.
기대결과: FACT_INVALID_TRANSITION — 확인을 건너뛴 '정정본'은 만들 수 없다."""
기대결과: FACT_INVALID_TRANSITION — 확인을 건너뛴 '정정본'은 만들 수 없다.
★ UNVERIFIED 는 이제 공식 API 수집이 빈 자리에 넣을 때 생긴다(크롤링은 바로 노출)."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="p3")
fid = (await _crawl(client, h, pid, "check_in_time", "15:00"))["fact"]["fact_id"]
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"})
@@ -185,12 +198,14 @@ async def test_recrawl_same_value_keeps_verification(auth_headers, client):
async def test_recrawl_changed_value_keeps_site_and_queues_candidate(auth_headers, client):
"""검증: 확인된 값과 다른 값을 재수집한다(OTA 가 바뀐 경우).
기대결과: ★ 노출값은 그대로 살아 있고, 새 값은 PENDING_OWNER 후보로만 쌓인다."""
"""검증: 사장님이 넣은 값과 다른 값을 재수집한다(OTA 가 바뀐 경우).
기대결과: ★ 노출값은 그대로 살아 있고, 새 값은 PENDING_OWNER 후보로만 쌓인다.
★ 자동 수집이 사람이 넣은 값을 밀어내지 못한다는 것이 이 테스트의 본체다.
크롤링이 직전 크롤링 값을 대체하는 것과는 다른 얘기다(위 즉시 노출 결정)."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="r2")
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 _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
@@ -208,8 +223,7 @@ async def test_approving_candidate_replaces_published_value(auth_headers, client
기대결과: 후보가 노출값이 되고 옛 값은 EXPIRED 이력으로 내려간다. 노출값은 여전히 1건."""
h = await auth_headers("u1")
pid = await _verified_place(client, h, kakao="r3")
old = (await _crawl(client, h, pid, "check_in_time", "15:00"))["fact"]["fact_id"]
await client.post(f"/v1/place/{pid}/fact/{old}/transition", headers=h, json={"status": FactStatus.VERIFIED.value})
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,
@@ -227,8 +241,7 @@ 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")
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 _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")
@@ -303,13 +316,18 @@ async def test_publishing_marks_place_for_rebuild(auth_headers, client):
async def test_crawl_only_does_not_mark_rebuild(auth_headers, client):
"""검증: 크롤링이 후보만 쌓았을 때 재빌드 표시.
기대결과: 안 찍힌다 — 사이트에 나가는 내용이 안 바뀌었으니 재빌드가 필요 없다."""
기대결과: 안 찍힌다 — 사이트에 나가는 내용이 안 바뀌었으니 재빌드가 필요 없다.
★ 노출값을 바꾼 수집은 반대로 찍혀야 한다(그게 needs_rebuild 의 뜻이다).
그래서 사장님 값 위에 올라온 **후보** 경로로 확인한다."""
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", "15:00")
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") is None
assert place.get("content_updated_at") == before, "후보만 쌓였는데 재빌드 대상이 됐다"
async def test_facts_are_scoped_to_owner(auth_headers, client):
@@ -85,13 +85,17 @@ async def _rows(place_id):
async def test_generates_both_durations(db_engine, spy_perplexity):
"""검증: 아무것도 없는 업장.
기대결과: 기간 둘을 각각 한 번씩 부르고(총 2회) 각각 5개 코스를 저장한다."""
기대결과: 기간 둘을 각각 만들고 각각 5개 코스를 저장한다.
★ 호출 수는 기간당 MAX_ATTEMPTS 다. 목응답이 5개(< TARGET_COURSES=10)라 서비스가
같은 프롬프트로 한 번 더 부르고, 두 번째 응답은 already_seen 에 걸려 전부 버려진다 —
그래서 호출은 늘어도 저장된 코스는 5개 그대로다."""
calls, _ = spy_perplexity
pid = uuid.uuid4()
out = await service.ensure_generated(_FakePlace(pid))
assert len(calls) == 2
assert len(calls) == 2 * service.MAX_ATTEMPTS
assert out["counts"] == {"1박 2일": 5, "2박 3일": 5}
rows = await _rows(pid)
assert {r.duration for r in rows} == {"1박 2일", "2박 3일"}
@@ -132,8 +136,8 @@ async def test_fills_only_the_missing_duration(db_engine, spy_perplexity):
out = await service.ensure_generated(_FakePlace(pid))
assert len(calls) == 1
assert "2박 3일" in calls[0]["messages"][1]["content"]
assert len(calls) == service.MAX_ATTEMPTS
assert all("2박 3일" in c["messages"][1]["content"] for c in calls)
assert out["counts"] == {"2박 3일": 5}
@@ -237,7 +241,7 @@ async def test_ensure_generated_by_id_loads_the_place(db_engine, spy_perplexity,
out = await service.ensure_generated_by_id(pid)
assert len(calls) == 2
assert len(calls) == 2 * service.MAX_ATTEMPTS
assert out["counts"] == {"1박 2일": 5, "2박 3일": 5}
+26
View File
@@ -33,6 +33,32 @@ async def test_enqueue_and_claim(db_engine):
assert row["status"] == JobStatus.RUNNING.value
async def test_progress_rejects_old_worker_and_resets_on_retry(db_engine):
from services.job_progress import JobProgress
q = JobQueue()
jid = await q.enqueue(JobType.COPY.value, {})
old = await q.claim("w1")
progress = JobProgress(old, ("prepare", "generate"))
async with progress.step("prepare"):
pass
try:
async with progress.step("generate"):
raise ValueError("upstream failed")
except ValueError:
pass
row = await q.get(jid)
assert row["progress"]["steps"][1]["status"] == "failed"
await q.fail(jid, "w1", "upstream failed", backoff_sec=0)
new = await q.claim("w2")
assert not await q.set_progress(old, {"steps": [], "attempt": 1})
retried = JobProgress(new, ("prepare", "generate"))
async with retried.step("prepare"):
row = await q.get(jid)
assert row["progress"]["attempt"] == 2
assert [s["status"] for s in row["progress"]["steps"]] == ["running", "pending"]
async def test_claim_is_atomic_across_workers(db_engine):
"""검증: 잡 1건에 워커 5개가 동시에 달려든다.
기대결과: 정확히 1명만 가져간다 — 도커에서 워커를 몇 개로 스케일하든 이중 실행이 없다."""
+26 -4
View File
@@ -105,16 +105,38 @@ async def test_search_rejects_short_query(client):
async def test_rate_limit_closes_the_tap(client, monkeypatch):
"""인증이 없는데 유료 외부 API 를 부른다 — 새로고침만으로 요금이 나가면 안 된다."""
"""인증이 없는데 유료 외부 API 를 부른다 — 새로고침만으로 요금이 나가면 안 된다.
★ 검색어를 매번 바꾼다. 같은 검색어는 ttl_cache 가 레이트리밋보다 **앞에서** 받아
외부 API 를 아예 안 부르므로(요금이 안 나가므로 제한할 이유도 없다), 같은 말을
반복하면 이 가드가 아니라 캐시를 시험하게 된다."""
rate_limit.reset()
_patch_kakao(monkeypatch, [_kp("하조대펜션", "가정,생활 > 숙박 > 펜션", "AD5")])
from services import place_service
monkeypatch.setattr(place_service, "_PUBLIC_SEARCH_PER_MIN", 2)
for _ in range(2):
assert (await client.get("/v1/place/search", params={"q": "하조대펜션"})).json()["result"]["success"] is True
for i in range(2):
r = (await client.get("/v1/place/search", params={"q": f"하조대펜션{i}"})).json()
assert r["result"]["success"] is True
blocked = (await client.get("/v1/place/search", params={"q": "하조대펜션"})).json()
blocked = (await client.get("/v1/place/search", params={"q": "하조대펜션9"})).json()
assert blocked["result"]["success"] is False
assert blocked["result"]["code"] == ErrorType.HTTP_TO_MANY_REQUEST.value
async def test_cached_query_does_not_spend_the_rate_limit(client, monkeypatch):
"""검증: 같은 검색어를 제한 횟수보다 많이 친다.
기대결과: 통과한다 — 캐시가 받으면 외부 API 를 안 부르고, 안 부르면 요금도 안 난다.
★ 레이트리밋을 캐시보다 앞으로 옮기면 사장님이 상호를 고쳐 가며 치는 평범한 사용이
막힌다. 이 순서가 의도라는 것을 여기서 못 박는다."""
rate_limit.reset()
_patch_kakao(monkeypatch, [_kp("하조대펜션", "가정,생활 > 숙박 > 펜션", "AD5")])
from services import place_service
monkeypatch.setattr(place_service, "_PUBLIC_SEARCH_PER_MIN", 2)
for _ in range(5):
r = (await client.get("/v1/place/search", params={"q": "같은검색어"})).json()
assert r["result"]["success"] is True
@@ -114,7 +114,12 @@ async def test_사이트_디렉터리_밖의_thumbs_에_올린다(blob, monkeypa
# ★ `?v=` 는 캐시 무효화다. 블롭 이름은 그대로 덮어쓰므로 주소가 안 변하면
# 브라우저·CDN 이 지난 발행의 그림을 계속 보여준다(site_thumbnail.public_url).
assert url == "https://w4ai.o2o.kr/thumbs/butter.jpg?v=3"
# ★ 호스트를 박아 두지 않는다. 발행 오리진은 SITE_PUBLIC_HOST 에서 오고 기본값이
# localhost 라(운영 주소를 기본으로 두면 로컬 빌드가 조용히 운영 주소를 굽는다),
# 테스트가 특정 도메인을 적으면 환경이 바뀔 때마다 여기서 깨진다.
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}/")