o2o-negosium-original/agent/tests/test_p7_apis.py
hbyang 1682481b01 [feat] agent: 협상 고도화 — LLM 표현/이해층 + 카드 전술 실행계층 + ktcommerce 정리
카드 재설계("멘트 카드 → 전술 카드"):
- tactics.py 신설: 카드번호→전술(카운터 산식) 레지스트리, min(counter,target) 클램프
- 카운터 수락=즉시 타결(pending_counter_price 일반화, 구 offer_1pct 흡수)
- 목표가 초과 타결 금지(성공스텝 진입 가드) + "카드 소진=실패" 폐지→종결 국면
- 선택형 와일드카드(WC-*) 발동 + card.wild_cards 멘트 DB 어댑터

LLM 계층:
- Phase 2 표현층 ScriptNaturalizer(카드 멘트 자연화, 마커·치환자·숫자 보존 검증)
- Phase 3 이해층 InputInterpreter(자유발화 NLU→기대입력, 한국어 가격 파서)
- OPENAI_API_KEY env override(server_configs) + 전역 자격증명 게이트

결정 스택(Phase 1):
- 협상 규칙 데이터화(negotiation.wildcard_*_ratio/max_counter_rounds)
- 선택카드 우선순위 prior(UCB 방문수 감쇠, Q-table 오염 없음)

버그픽스:
- 인하율 음수 표기 제거 + 인상/동일/인하 구분(discount_phrase)
- 자연화 강조마커 보존(볼드/색 소실 시 원본 폴백)
- 카드 시드 가격변수(prev_partner_price·target_mid_price·middle_price 등) 치환

정리:
- ktcommerce 테넌트 삭제 + 테스트 21파일 imarketkorea/_base 로 마이그레이션
- 실 LLM 호출 차단 conftest 가드

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 13:37:36 +09:00

115 lines
4.9 KiB
Python

"""P7 — 14개 API 보존 스모크 (tenant 헤더 격리).
Chat_server 14개 API 대응: health, chat, invalidate-session, card-update, card-search,
reset-learning, reset-all, q-table/{versions,switch,current}, experience-logs, train, verification-report.
모두 X-Tenant-ID 헤더 필요(누락 400). 동작 + company_id 격리 확인.
"""
import pytest
H = {"X-Tenant-ID": "imarketkorea"}
@pytest.mark.asyncio
async def test_health_no_tenant(client):
assert (await client.get("/v1/health")).status_code == 200
@pytest.mark.asyncio
async def test_tenant_header_required_on_management(client):
for path in ["/v1/q-table/versions", "/v1/experience-logs", "/v1/card-search"]:
r = await client.get(path)
assert r.status_code == 400, path
@pytest.mark.asyncio
async def test_qtable_lifecycle_and_logs(client, db_engine):
# 활성 버전 없음 → current 빈 상태
r = await client.get("/v1/q-table/current", headers=H)
assert r.status_code == 200
# /chat 한 번 돌려 학습 데이터 생성 (가격협상까지)
sid = None
for ui in [None, "확인", "예", "확인", "11000", "예", "10200", "예", "9800", "예",
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."]:
cr = await client.post("/v1/chat", headers=H, json={"session_id": sid, "user_input": ui, "rq_type": "재협상"})
sid = cr.json()["session_id"]
if cr.json().get("chat_end"):
break
# 버전 생성됨 + 활성
versions = (await client.get("/v1/q-table/versions", headers=H)).json()
assert versions["versions"] and any(v["is_active"] for v in versions["versions"])
cur = (await client.get("/v1/q-table/current", headers=H)).json()
assert cur["active_version"] is not None and cur["q_value_rows"] >= 1
# 경험 로그
logs = (await client.get("/v1/experience-logs?limit=10", headers=H)).json()
assert logs["total"] >= 1 and len(logs["logs"]) >= 1
# 검증 리포트
rep = (await client.get("/v1/verification-report", headers=H)).json()
assert rep["experience_total"] >= 1
# 오프라인 학습
tr = (await client.post("/v1/train", headers=H, json={"epochs": 2})).json()
assert tr["success"] and tr["trained_transitions"] >= 1
@pytest.mark.asyncio
async def test_card_update_search(client, db_engine):
up = (await client.post("/v1/card-update", headers=H, json={"action_id": 0, "card_id": "CUSTOM-X"})).json()
assert up["success"]
s = (await client.get("/v1/card-search?card_id=CUSTOM-X", headers=H)).json()
assert s["found"] and 0 in s["action_ids"]
allm = (await client.get("/v1/card-search", headers=H)).json()
assert any(m["card_id"] == "CUSTOM-X" for m in allm["mapping"])
@pytest.mark.asyncio
async def test_catalog_refresh(client, db_engine):
# 카탈로그 발행 후 엔진 재조립 트리거 — 성공 + action_space 반환. 헤더 없으면 400.
r = await client.post("/v1/catalog-refresh", headers=H)
assert r.status_code == 200
body = r.json()
assert body["success"] and body["action_space_size"] >= 1
r2 = await client.post("/v1/catalog-refresh")
assert r2.status_code == 400
@pytest.mark.asyncio
async def test_catalog_refresh_all_no_tenant_header(client, db_engine):
# 공용 카탈로그 전역 반영 — 테넌트 헤더 없이도 200(화이트리스트) + 캐시 클리어.
await client.post("/v1/catalog-refresh", headers=H) # 엔진 하나 캐시
r = await client.post("/v1/catalog-refresh-all") # 헤더 없음
assert r.status_code == 200
assert r.json()["success"] is True
@pytest.mark.asyncio
async def test_invalidate_and_reset_scoped(client, db_engine):
# 가격협상 카드선택이 일어나는 긴 경로(850→900→990)로 양 테넌트 데이터 생성
convo = [None, "확인", "예", "확인", "11000", "예", "10200", "예", "9800", "예",
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."]
sid = None
for ui in convo:
cr = await client.post("/v1/chat", headers=H, json={"session_id": sid, "user_input": ui})
sid = cr.json()["session_id"]
if cr.json().get("chat_end"):
break
H2 = {"X-Tenant-ID": "00000000-0000-0000-0000-0000000000b2"} # 실고객사 모사(자동 온보딩)
sid2 = None
for ui in convo:
cr = await client.post("/v1/chat", headers=H2, json={"session_id": sid2, "user_input": ui})
sid2 = cr.json()["session_id"]
if cr.json().get("chat_end"):
break
before2 = (await client.get("/v1/experience-logs", headers=H2)).json()["total"]
assert before2 >= 1
# imarketkorea reset-all → 타테넌트(H2) 무영향
assert (await client.post("/v1/reset-all", headers=H)).json()["success"]
assert (await client.get("/v1/experience-logs", headers=H)).json()["total"] == 0
assert (await client.get("/v1/experience-logs", headers=H2)).json()["total"] == before2