linebot_pydantic_fastapi / test_search_orders.py
mickeywu520's picture
修正訂單查詢問題
68c8519
"""
測試 /search 訂單查詢功能 - 基於實際銷售訂單資料
"""
import requests
import json
def test_search_api_orders():
"""測試 /search API 的訂單查詢功能"""
base_url = "http://localhost:7860"
print("🔍 測試 /search API 訂單查詢功能")
print("=" * 60)
# 測試案例基於您的實際銷售訂單資料
test_cases = [
{
"name": "查詢特定訂單編號",
"message": "查詢訂單 SO-20250706-001",
"expected": "應該找到 2025-07-06 的已交付訂單"
},
{
"name": "查詢另一個訂單編號",
"message": "SO-20250708-001 狀態如何?",
"expected": "應該找到 2025-07-08 的已出貨訂單"
},
{
"name": "查詢已交付訂單",
"message": "查詢已交付的訂單",
"expected": "應該找到狀態為 DELIVERED 的訂單"
},
{
"name": "查詢已出貨訂單",
"message": "已出貨訂單有哪些?",
"expected": "應該找到狀態為 SHIPPED 的訂單"
},
{
"name": "一般訂單查詢",
"message": "我的訂單",
"expected": "應該顯示所有訂單"
},
{
"name": "訂單狀態查詢",
"message": "訂單狀態查詢",
"expected": "應該顯示訂單列表"
},
{
"name": "使用日期格式編號",
"message": "20250706-001 這個訂單",
"expected": "應該找到對應的 SO- 訂單"
}
]
for i, test_case in enumerate(test_cases, 1):
print(f"\n{i}. {test_case['name']}")
print(f" 查詢: '{test_case['message']}'")
print(f" 預期: {test_case['expected']}")
try:
payload = {
"message": test_case["message"],
"user_id": "test_user_search"
}
response = requests.post(
f"{base_url}/search",
json=payload,
timeout=30,
headers={"Content-Type": "application/json"}
)
print(f" 狀態碼: {response.status_code}")
if response.status_code == 200:
result = response.json()
print(f" 成功: {result.get('success', False)}")
# 顯示回應內容
response_text = result.get('text', 'No response')
if len(response_text) > 200:
print(f" 回應: {response_text[:200]}...")
else:
print(f" 回應: {response_text}")
# 檢查是否包含訂單相關資訊
if any(keyword in response_text for keyword in ['SO-', '訂單', '狀態', '已交付', '已出貨']):
print(f" ✅ 包含訂單相關資訊")
else:
print(f" ❌ 未包含預期的訂單資訊")
else:
print(f" ❌ API 錯誤: {response.text}")
except Exception as e:
print(f" ❌ 請求失敗: {str(e)}")
print("-" * 60)
def test_route_api_orders():
"""測試 /route API 對訂單查詢的路由"""
base_url = "http://localhost:7860"
print(f"\n🔄 測試 /route API 訂單查詢路由")
print("=" * 60)
# 測試訂單查詢是否被正確路由
order_queries = [
"查詢訂單 SO-20250706-001",
"我的訂單狀態",
"已交付的訂單",
"訂單編號 SO-20250708-001"
]
for i, query in enumerate(order_queries, 1):
print(f"\n{i}. 路由測試: '{query}'")
try:
payload = {
"message": query,
"user_id": "test_user_route"
}
response = requests.post(
f"{base_url}/route",
json=payload,
timeout=30,
headers={"Content-Type": "application/json"}
)
print(f" 狀態碼: {response.status_code}")
if response.status_code == 200:
result = response.json()
mode = result.get('mode', 'unknown')
success = result.get('success', False)
print(f" 路由模式: {mode}")
print(f" 成功: {success}")
# 檢查是否路由到正確的模式
if mode == "search":
print(f" ✅ 正確路由到搜尋模式")
elif mode == "product_query":
print(f" ⚠️ 路由到商品查詢模式(可能需要調整)")
else:
print(f" ❌ 路由到非預期模式: {mode}")
# 顯示部分回應
response_text = result.get('text', 'No response')
if len(response_text) > 100:
print(f" 回應: {response_text[:100]}...")
else:
print(f" 回應: {response_text}")
else:
print(f" ❌ API 錯誤: {response.text}")
except Exception as e:
print(f" ❌ 請求失敗: {str(e)}")
def test_order_query_patterns():
"""測試訂單查詢模式識別"""
print(f"\n🤖 測試訂單查詢模式識別")
print("=" * 60)
def analyze_order_query_intent(message: str):
"""簡化版訂單查詢意圖分析"""
message_lower = message.lower()
# 訂單查詢關鍵字
order_keywords = ['訂單', '訂購', '購買', 'so-', 'order']
# 狀態關鍵字
status_keywords = ['狀態', '已交付', '已出貨', '處理中', '取消', 'delivered', 'shipped']
# 查詢動作關鍵字
action_keywords = ['查詢', '搜尋', '找', '看', '檢查']
has_order_keyword = any(keyword in message_lower for keyword in order_keywords)
has_status_keyword = any(keyword in message_lower for keyword in status_keywords)
has_action_keyword = any(keyword in message_lower for keyword in action_keywords)
# 計算信心度
confidence = 0.0
if has_order_keyword:
confidence += 0.5
if has_status_keyword:
confidence += 0.3
if has_action_keyword:
confidence += 0.2
return {
"is_order_query": has_order_keyword,
"has_status": has_status_keyword,
"has_action": has_action_keyword,
"confidence": min(confidence, 1.0),
"should_route_to_search": has_order_keyword and confidence > 0.5
}
test_messages = [
"查詢訂單 SO-20250706-001",
"我的訂單狀態如何?",
"已交付的訂單有哪些?",
"SO-20250708-001 出貨了嗎?",
"訂單編號查詢",
"購買記錄",
"今天天氣如何?", # 非訂單查詢
"是否有推薦貓砂?" # 商品查詢
]
for message in test_messages:
print(f"\n訊息: '{message}'")
analysis = analyze_order_query_intent(message)
print(f" 訂單查詢: {analysis['is_order_query']}")
print(f" 包含狀態: {analysis['has_status']}")
print(f" 包含動作: {analysis['has_action']}")
print(f" 信心度: {analysis['confidence']:.2f}")
print(f" 建議路由: {'搜尋模式' if analysis['should_route_to_search'] else '其他模式'}")
def main():
"""主函數"""
print("🚀 開始 /search 訂單查詢功能測試\n")
# 檢查 API 服務是否運行
try:
response = requests.get("http://localhost:7860/health", timeout=5)
if response.status_code == 200:
print("✅ API 服務運行正常\n")
else:
print("❌ API 服務狀態異常\n")
return
except Exception as e:
print(f"❌ 無法連接到 API 服務: {str(e)}")
print("請確保 LineBot 服務正在運行在 localhost:7860\n")
# 仍然執行模式識別測試
test_order_query_patterns()
return
# 執行 API 測試
test_search_api_orders()
test_route_api_orders()
test_order_query_patterns()
print("\n" + "=" * 60)
print("✅ 測試完成!")
print("\n💡 測試總結:")
print("1. /search API 應該能正確處理訂單查詢")
print("2. 支援 SO- 格式訂單編號查詢")
print("3. 支援狀態篩選(已交付、已出貨等)")
print("4. 路由系統應該將訂單查詢導向搜尋模式")
if __name__ == "__main__":
main()