feat(chat): agent 연동 정리 — mock 제거·DB 데이터 연동·표현 passthrough
- MockAgentClient/use_mock 분기와 mock 전용 turn/count_bot_messages 제거 (항상 HttpAgentClient 위임) - agent RL state 입력을 실 DB 로 연동: anchor_price=quotation_settings.anchoring_value 기반 계산, partner_count=견적당 세션 수 (quotation_settings 모델 추가) - 재견적 배송형태(delivery_type) 캡처: 배송형태선택 단계 선택값을 summaryCM 요약에 반영 (DeliveryType enum 추가) - 표현 계약 passthrough: agent 응답의 bot_chat_type/indicator_value 를 우선 사용하고 없으면 step+qt_type 으로 폴백, indicator_value 컬럼 영속/전달 - 턴당 중복 조회 제거: item/last_price 를 1회 로드해 재사용 - 관련 테스트 추가(배송형태 캡처, passthrough) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
6fcb4d4e8c
commit
8f070e362b
7 files changed
+375
-141
No files matched your search
+126
-1
@@ -1,21 +1,106 @@
|
||||
"""채팅(chat) 도메인 e2e 테스트 — init / messages(오프닝 seed) / send(협상 진행~종료).
|
||||
|
||||
agent 는 config.use_mock=true 로 내장 MockAgentClient 를 쓴다(결정론적 플로우).
|
||||
실제 agent(9500) 대신, 결정론적 테스트 더블(_FakeAgentClient)을 FastAPI 의존성 오버라이드로 주입한다.
|
||||
(프로덕션 코드에는 mock 이 없다 — 테스트 전용 double 이다.) 더블은 backend 가 매 턴 보내는
|
||||
client_step(직전 봇 step)과 user_input 으로 단계를 진행한다.
|
||||
dev negosium_db 를 그대로 쓰므로 전용 테스트 행만 시드/정리한다.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
|
||||
import bcrypt
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import text
|
||||
|
||||
from services.agent_client import AgentTurn, IAgentClient, get_agent_client
|
||||
|
||||
TEST_LOGIN_ID = "pytest_chat_user"
|
||||
TEST_PW = "pytest1234"
|
||||
TEST_SUPPLIER_NAME = "파이테스트채팅공급사"
|
||||
MARK = "PYTESTCHAT-"
|
||||
|
||||
|
||||
def _parse_price(text_):
|
||||
if not text_:
|
||||
return None
|
||||
digits = "".join(ch for ch in text_ if ch.isdigit())
|
||||
return int(digits) if digits else None
|
||||
|
||||
|
||||
class _FakeAgentClient(IAgentClient):
|
||||
"""결정론적 테스트 더블. ctx.client_step(직전 봇 step)+user_input 으로 단계를 진행한다.
|
||||
|
||||
플로우: (오프닝)서비스안내 → 협상품목안내 → 가격협상 → 가격제시 시 목표가 이하면 성공 종료.
|
||||
'포기'/'거부' 입력은 언제든 실패 종료.
|
||||
"""
|
||||
|
||||
async def chat(self, session_id, user_input, ctx) -> AgentTurn:
|
||||
sid = session_id or "fake-session"
|
||||
if user_input and ("포기" in user_input or "거부" in user_input):
|
||||
return AgentTurn(
|
||||
session_id=sid, step="협상종료", client_step="협상종료",
|
||||
script="협상이 종료되었습니다.", chat_end=True, outcome="failure",
|
||||
)
|
||||
if user_input is None: # 오프닝(턴0) — 양쪽 공통
|
||||
return AgentTurn(session_id=sid, step="서비스안내", client_step="서비스안내",
|
||||
script="협상에 참여해 주셔서 감사합니다. 시작하시겠어요?",
|
||||
input_mode="confirm", input_options=["네, 시작할게요"])
|
||||
if ctx.rq_type == "재견적":
|
||||
return self._requote(sid, user_input, ctx)
|
||||
return self._renego(sid, user_input, ctx)
|
||||
|
||||
def _renego(self, sid, user_input, ctx) -> AgentTurn:
|
||||
if ctx.client_step == "서비스안내":
|
||||
return AgentTurn(session_id=sid, step="협상품목안내", client_step="협상품목안내",
|
||||
script="협상 품목을 확인해 주세요. 가격 협상을 진행할까요?",
|
||||
input_mode="confirm", input_options=["가격 협상 진행"])
|
||||
if ctx.client_step == "협상품목안내":
|
||||
return AgentTurn(session_id=sid, step="가격협상", client_step="가격협상",
|
||||
script="희망 공급가를 입력해 주세요.", input_mode="price")
|
||||
# 가격협상 단계: 목표가 이하면 합의 종료, 아니면 한 번 더 요청
|
||||
price = _parse_price(user_input)
|
||||
if price is not None and ctx.target_price and price <= ctx.target_price:
|
||||
return AgentTurn(session_id=sid, step="협상종료", client_step="협상종료",
|
||||
script=f"제안하신 {price:,}원으로 합의되었습니다. 감사합니다.",
|
||||
chat_end=True, outcome="success", indicator_value=99.0)
|
||||
return AgentTurn(session_id=sid, step="가격협상", client_step="가격협상",
|
||||
script="조금 더 조정된 가격을 제안해 주시겠어요?", input_mode="price",
|
||||
indicator_value=50.0)
|
||||
|
||||
def _requote(self, sid, user_input, ctx) -> AgentTurn:
|
||||
# 서비스안내 → 가격제안 → 배송형태선택 → 가격협상_입력 → 결과안내(summaryCM)
|
||||
if ctx.client_step == "서비스안내":
|
||||
return AgentTurn(session_id=sid, step="가격제안", client_step="가격제안",
|
||||
script="제시 목표가로 진행하시겠어요?", input_mode="yes_no",
|
||||
input_options=["예", "아니오"])
|
||||
if ctx.client_step == "가격제안":
|
||||
return AgentTurn(session_id=sid, step="배송형태선택", client_step="배송형태선택",
|
||||
script="배송형태를 선택해 주세요.", input_mode="delivery_type",
|
||||
input_options=["협력사배송", "지정택배배송", "픽업배송"])
|
||||
if ctx.client_step == "배송형태선택":
|
||||
return AgentTurn(session_id=sid, step="가격협상_입력", client_step="가격협상_입력",
|
||||
script="희망 공급가를 입력해 주세요.", input_mode="price")
|
||||
if ctx.client_step == "가격협상_입력":
|
||||
return AgentTurn(session_id=sid, step="결과안내", client_step="결과안내",
|
||||
script="투찰 결과를 확인해 주세요.", input_mode="yes_no",
|
||||
input_options=["투찰확정", "정보수정"])
|
||||
# 결과안내 "투찰확정" → 결과제출 → 협상종료
|
||||
return AgentTurn(session_id=sid, step="협상종료", client_step="협상종료",
|
||||
script="투찰이 확정되었습니다. 감사합니다.",
|
||||
chat_end=True, outcome="success")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fake_agent():
|
||||
"""모든 chat 테스트에서 실제 agent 대신 결정론적 더블을 주입(의존성 오버라이드)."""
|
||||
from router.router import app
|
||||
|
||||
app.dependency_overrides[get_agent_client] = lambda: _FakeAgentClient()
|
||||
yield
|
||||
app.dependency_overrides.pop(get_agent_client, None)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def chat_seed(db_engine):
|
||||
"""공급사 + 유저 + 세션 2건(본인: 협상중 P / 협상생성 C) + 1건(타 공급사 X) 시드."""
|
||||
@@ -28,6 +113,7 @@ async def chat_seed(db_engine):
|
||||
("P", 2, 1, 2, 2, supplier_id), # 협상중 / 재협상 / +2h / 견적진행중
|
||||
("C", 1, 1, 2, 1, supplier_id), # 협상생성 / 재협상 / +2h / 견적생성
|
||||
("X", 2, 1, 2, 2, other_supplier_id), # 타 공급사 → 차단
|
||||
("Q", 2, 2, 2, 2, supplier_id), # 협상중 / 재견적 / +2h / 견적진행중
|
||||
]
|
||||
sids, qids = {}, {}
|
||||
|
||||
@@ -174,6 +260,45 @@ async def test_send_flow_to_completion(client, chat_seed, db_engine):
|
||||
assert await _session_bid(db_engine, sid) == 90000 # 입찰가 확정
|
||||
|
||||
|
||||
async def test_requote_summary_captures_delivery_type(client, chat_seed):
|
||||
"""재견적: 배송형태선택에서 고른 값이 summaryCM 요약(delivery_type)에 담긴다."""
|
||||
token = await _login_token(client)
|
||||
sid = chat_seed["sids"]["Q"]
|
||||
await _messages(client, token, sid) # 오프닝(서비스안내)
|
||||
await _send(client, token, sid, "네, 시작할게요") # → 가격제안
|
||||
await _send(client, token, sid, "예") # → 배송형태선택
|
||||
await _send(client, token, sid, "협력사배송") # → 가격협상_입력
|
||||
r = (await _send(client, token, sid, "90000", user_input_type="price")).json() # → 결과안내(summaryCM)
|
||||
assert r["result"]["success"] is True
|
||||
msg = r["message"]
|
||||
assert msg["bot_chat_type"] == "summaryCM"
|
||||
assert msg["summary"]["delivery_type"] == "협력사배송"
|
||||
|
||||
|
||||
async def test_agent_provided_bot_chat_type_and_indicator_passthrough(client, chat_seed):
|
||||
"""agent 가 bot_chat_type/indicator_value 를 직접 주면 backend 는 step 추측 없이 그대로 전달한다."""
|
||||
from router.router import app
|
||||
|
||||
class _T(IAgentClient):
|
||||
async def chat(self, session_id, user_input, ctx):
|
||||
if user_input is None:
|
||||
return AgentTurn(session_id=session_id, step="서비스안내", client_step="서비스안내",
|
||||
script="안녕하세요", input_mode="confirm", input_options=["확인"])
|
||||
return AgentTurn(session_id=session_id, step="가격협상", client_step="가격협상",
|
||||
script="지표를 확인하세요", input_mode="price",
|
||||
indicator_value=55.0, bot_chat_type="indicator")
|
||||
|
||||
app.dependency_overrides[get_agent_client] = lambda: _T()
|
||||
token = await _login_token(client)
|
||||
sid = chat_seed["sids"]["P"]
|
||||
await _messages(client, token, sid) # 오프닝
|
||||
r = (await _send(client, token, sid, "확인")).json() # → 가격협상(indicator)
|
||||
assert r["result"]["success"] is True
|
||||
msg = r["message"]
|
||||
assert msg["bot_chat_type"] == "indicator" # agent 값 그대로
|
||||
assert msg["indicator_value"] == 55.0 # 지표 전달
|
||||
|
||||
|
||||
async def test_send_price_out_of_range(client, chat_seed):
|
||||
token = await _login_token(client)
|
||||
sid = chat_seed["sids"]["P"]
|
||||
|
||||
Reference in new issue
Block a user