[feat] solution/backend: 미니 블로그 글을 배정 날짜에 맞는 소재로 만든다

예전에는 소재 목록을 순서대로 뽑아 날짜에 차례로 붙여서, 9월 날짜에
'한겨울' 글이나 끝난 축제 글이 붙을 수 있었다. 이제 날짜를 먼저 정하고
그 날짜에 맞는 소재를 고른다.

- 축제: 시작 14일 전 ~ 종료일 사이만 / 계절: 게시일 절기 하나
  / 날씨: 그 달에 있을 법한 것만(눈 12~2월, 소나기 6~8월) / 주변: 늘 후보
- 프롬프트에 게시일을 넣고, 날씨를 단정하지 않게 문구를 고쳤다
- 계절·날씨·축제 주제 키에 연(월)을 넣어 해마다 다시 쓸 수 있게 했다
- 자동·구간·개별 세 경로가 _compose_for_dates 하나로 만든다

같이 고친 버그: materials 가 스냅샷에 없는 local.festivals·attractions 를
읽어 축제·주변 소재가 늘 비어 있었다. 원문 행(local.contents)을 읽는다.
This commit is contained in:
skkim committed 2026-09-23 09:41:23 +09:00
1 parent be3e43162a
commit 36dbe26c91
4 files changed
+240 -137

No files matched your search

+47 -7
View File
@@ -140,7 +140,7 @@ async def test_deleting_a_post_frees_its_date_for_regeneration(client, db_engine
바로 다시 생성할 수 있어야 한다."""
from services import blog_service
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category):
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category, post_date=None):
return ("새로 만든 문구입니다. " + BODY, "gemini-test-model")
monkeypatch.setattr(blog_service, "generate_one", fake_generate_one)
@@ -201,7 +201,7 @@ async def test_generate_now_creates_posts_for_published_site(client, db_engine,
사장님 지시: "지금 생성하기에서 시작이랑 끝 날짜를 정해야하지 않을까") — 발행된 사이트일 때만."""
from services import blog_service
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category):
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category, post_date=None):
return ("테스트로 만든 문구입니다. " + BODY, "gemini-test-model")
monkeypatch.setattr(blog_service, "generate_one", fake_generate_one)
@@ -241,12 +241,52 @@ async def test_generate_now_creates_posts_for_published_site(client, db_engine,
assert all(start <= d <= end for d in dates)
async def test_generate_now_writes_each_post_for_its_own_date(client, db_engine, auth_headers, monkeypatch):
"""글마다 배정된 날짜를 게시일로 받아 쓰고, 그 날짜의 절기 소재가 붙는다(2026-09-23,
사장님 지시: "날짜에 맞는 글이 생성 되도록")."""
from services import blog_service
calls = []
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category, post_date=None):
calls.append((post_date, topic_kind, material))
return ("테스트로 만든 문구입니다. " + BODY, "gemini-test-model")
monkeypatch.setattr(blog_service, "generate_one", fake_generate_one)
h = await auth_headers("bloggen18")
place_id = await _place(client, h, name="날짜맞춤펜션")
async with db_engine.begin() as conn:
await conn.execute(
text("INSERT INTO sites (site_id, place_id, domain, status) VALUES (:sid, :pid, :dom, :st)"),
{"sid": uuid.uuid4(), "pid": place_id, "dom": f"blog-test-{uuid.uuid4().hex[:8]}", "st": SiteStatus.PUBLISHED.value},
)
winter = date(date.today().year + 1, 1, 10)
res = await client.post(
f"/v1/place/{place_id}/post/generate", headers=h,
params={"start": winter.isoformat(), "end": winter.isoformat()},
)
assert res.json()["created"] == 1
assert calls[0][0] == winter
# 지역 소재가 없는 업장이라 첫 후보는 그 날짜의 절기다.
assert calls[0][1] == PostTopicKind.SEASON.value
assert calls[0][2] == "한겨울"
async with db_engine.begin() as conn:
row = (await conn.execute(
text("SELECT scheduled_date, topic_key FROM place_posts WHERE place_id = :pid"), {"pid": place_id},
)).one()
assert row[0] == winter
assert row[1] == f"season:{winter.year}:한겨울"
async def test_generate_now_does_not_append_a_publish_link(client, db_engine, auth_headers, monkeypatch):
"""미니 블로그에 올라가는 글에는 링크를 붙이지 않는다(2026-09-21, 사장님 지시).
site_payload.publish_url() 자체는 남겨둔다 — 나중에 쓰레드 연동에서 따로 쓸 수 있게."""
from services import blog_service
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category):
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category, post_date=None):
return (f"테스트로 만든 문구입니다. {BODY}", "gemini-test-model")
monkeypatch.setattr(blog_service, "generate_one", fake_generate_one)
@@ -599,7 +639,7 @@ async def test_generate_now_is_noop_for_site_without_domain(client, db_engine, a
실제로 성공하도록 목킹해 둬야 "그냥 LLM 이 설정 안 돼서 0건"과 구분된다."""
from services import blog_service
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category):
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category, post_date=None):
return ("테스트로 만든 문구입니다. " + BODY, "gemini-test-model")
monkeypatch.setattr(blog_service, "generate_one", fake_generate_one)
@@ -720,7 +760,7 @@ async def test_generation_history_counts_by_batch(client, db_engine, auth_header
생성했는지" / "어느 모델썼는지 등등" → JSONB 한 칸(generation_meta)에 담는다)."""
from services import blog_service
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category):
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category, post_date=None):
return ("테스트로 만든 문구입니다. " + BODY, "gemini-test-model")
monkeypatch.setattr(blog_service, "generate_one", fake_generate_one)
@@ -819,7 +859,7 @@ async def test_generate_one_fills_a_specific_empty_date(client, db_engine, auth_
"""사장님 지시: "개별적으로 새로 만들수있게 해줘" — 달력에서 빈 날짜 하나만 콕 집어 채운다."""
from services import blog_service
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category):
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category, post_date=None):
return ("테스트로 만든 문구입니다. " + BODY, "gemini-test-model")
monkeypatch.setattr(blog_service, "generate_one", fake_generate_one)
@@ -847,7 +887,7 @@ async def test_generate_one_fails_when_date_already_taken(client, db_engine, aut
"""이미 그 날짜에 글이 있으면(유니크 충돌) 조용히 덮지 않고 실패로 답한다."""
from services import blog_service
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category):
async def fake_generate_one(*, place_name, region, topic_kind, material, used_topics, place_category, post_date=None):
return ("테스트로 만든 문구입니다. " + BODY, "gemini-test-model")
monkeypatch.setattr(blog_service, "generate_one", fake_generate_one)
+50 -2
View File
@@ -10,11 +10,11 @@
예전처럼 "GET 은 확인 화면만" 을 기대하는 테스트를 두지 않는다.
"""
import uuid
from datetime import timezone
from datetime import date, timezone
from sqlalchemy import text
from common.enums import JobType, PlaceCategory, PostStatus, PostTopicKind, SiteStatus
from common.enums import JobType, LocalContentType, PlaceCategory, PostStatus, PostTopicKind, SiteStatus
from services import blog_service, site_payload
BODY = (
@@ -65,6 +65,54 @@ def test_build_prompt_falls_back_to_stay_wording_for_unmapped_category():
assert "숙소" in restaurant # 음식점 전용 문구가 아직 없어 숙소 문구로 폴백한다
def _snapshot_with(*rows):
return {"local": {"region_code": "52130", "contents": list(rows)}}
def _festival_row(name, start, end):
return {"content_type": LocalContentType.FESTIVAL.value, "title": name,
"body": {"name": name, "eventstartdate": start, "eventenddate": end, "location": "군산 원도심"}}
def test_materials_follow_the_post_date():
"""게시일에 맞는 소재만 나온다(2026-09-23) — 9월 글에 '한겨울'·'눈'·끝난 축제가 붙지 않는다."""
snapshot = _snapshot_with(
_festival_row("시간여행축제", "20261002", "20261004"), # 곧 열린다(9일 뒤)
_festival_row("벚꽃축제", "20260401", "20260405"), # 이미 끝났다
_festival_row("겨울빛축제", "20261220", "20261231"), # 아직 한참 멀다
{"content_type": LocalContentType.ATTRACTION.value, "title": "경암동 철길마을",
"body": {"name": "경암동 철길마을", "description": "철길 옆 골목"}},
)
out = blog_service.materials(snapshot, date(2026, 9, 23))
keys = [key for _kind, key, _material in out]
assert keys[0] == "festival:2026:시간여행축제"
assert "2026.10.02 ~ 2026.10.04" in out[0][2]
assert not any("벚꽃" in k or "겨울빛" in k for k in keys)
assert "season:2026:초가을" in keys
assert not any(k.startswith("season:") and not k.endswith("초가을") for k in keys)
assert "nearby:경암동 철길마을" in keys
assert "weather:2026-09:비" in keys
assert not any(k.endswith(":눈") or k.endswith(":소나기") for k in keys)
def test_materials_allow_snow_in_winter_and_reuse_seasons_each_year():
winter = [key for _k, key, _m in blog_service.materials(_snapshot_with(), date(2027, 1, 10))]
assert "weather:2027-01:눈" in winter
assert "season:2027:한겨울" in winter
def test_build_prompt_tells_the_post_date():
prompt = blog_service.build_prompt(
place_name="테스트펜션", region="군산", topic_kind=PostTopicKind.SEASON.value,
material="초가을", used_topics=[], post_date=date(2026, 9, 23),
)
assert "게시일: 2026년 9월 23일(수) · 초가을" in prompt
async def test_generate_one_forwards_place_category_into_the_prompt(monkeypatch):
"""generate_one 은 place_category 를 build_prompt 로 그대로 넘긴다 — 링크는 여기서
붙이지 않는다(호출부의 길이 게이트가 이 반환값에 그대로 걸리기 때문에, 붙이면