test_product_mem.py•8.75 kB
#!/usr/bin/env python3
"""
ProductMemory功能测试脚本
测试商品记忆管理模块的各项功能
"""
import sys
from pathlib import Path
# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
from product_memory import ProductMemory, create_product_memory
def test_product_memory_basic():
"""测试ProductMemory基本功能"""
print("🧪 测试ProductMemory基本功能...")
pm = create_product_memory(verbose=True)
# 测试添加商品
print("\n1. 测试添加商品")
success1 = pm.add_product(
sku="SKU-001",
attributes={
"name": "华为Mate60 Pro",
"price": 6999,
"category": "智能手机",
"brand": "华为",
"storage": "512GB",
"color": "雅川青"
},
selling_points=["麒麟9000S芯片", "卫星通话", "昆仑玻璃", "5000mAh大电池", "100W快充"],
relationships=[
{"type": "series", "target": "Mate系列"},
{"type": "competitor", "target": "iPhone15 Pro"}
]
)
success2 = pm.add_product(
sku="SKU-002",
attributes={
"name": "iPhone 15 Pro",
"price": 7999,
"category": "智能手机",
"brand": "苹果",
"storage": "256GB",
"color": "深空黑色"
},
selling_points=["A17 Pro芯片", "钛金属边框", "Action Button", "ProRAW拍摄", "USB-C接口"],
relationships=[
{"type": "series", "target": "iPhone系列"},
{"type": "competitor", "target": "SKU-001"}
]
)
success3 = pm.add_product(
sku="SKU-003",
attributes={
"name": "小米14 Ultra",
"price": 5999,
"category": "智能手机",
"brand": "小米",
"storage": "512GB",
"color": "钛金属灰"
},
selling_points=["骁龙8 Gen3", "徕卡影像", "2K屏幕", "90W快充", "IP68防水"],
relationships=[
{"type": "series", "target": "小米数字系列"}
]
)
print(f"添加结果: SKU-001={success1}, SKU-002={success2}, SKU-003={success3}")
if not all([success1, success2, success3]):
print("❌ 商品添加失败")
return False
return True
def test_product_search():
"""测试商品搜索功能"""
print("\n🧪 测试商品搜索功能...")
pm = create_product_memory(verbose=True)
# 测试不同类型的搜索
test_queries = [
"华为",
"智能手机",
"SKU-001",
"麒麟芯片",
"快充",
"iPhone",
"徕卡"
]
for query in test_queries:
print(f"\n搜索: '{query}'")
results = pm.search_product(query, limit=3)
if results:
for i, result in enumerate(results):
print(f" 结果{i+1}: {result['sku']} - {result['attributes'].get('name', '未知')}")
print(f" 卖点: {', '.join(result['selling_points'][:2])}...")
else:
print(" 无结果")
return True
def test_product_management():
"""测试商品管理功能"""
print("\n🧪 测试商品管理功能...")
pm = create_product_memory(verbose=True)
# 测试根据SKU获取商品
print("\n1. 测试根据SKU获取商品")
product = pm.get_product_by_sku("SKU-001")
if product:
print(f"✅ 找到商品: {product['attributes']['name']}")
print(f" 价格: {product['attributes']['price']}")
print(f" 卖点数量: {len(product['selling_points'])}")
else:
print("❌ 未找到商品")
return False
# 测试更新商品
print("\n2. 测试更新商品")
update_success = pm.update_product(
sku="SKU-001",
attributes={"price": 6499, "promotion": "限时优惠"},
selling_points=["麒麟9000S芯片", "卫星通话", "昆仑玻璃", "5000mAh大电池", "100W快充", "HarmonyOS 4.0"]
)
if update_success:
print("✅ 商品更新成功")
# 验证更新
updated_product = pm.get_product_by_sku("SKU-001")
if updated_product and updated_product['attributes']['price'] == 6499:
print("✅ 价格更新验证成功")
else:
print("❌ 价格更新验证失败")
return False
else:
print("❌ 商品更新失败")
return False
# 测试列出所有商品
print("\n3. 测试列出所有商品")
all_products = pm.list_all_products()
print(f"✅ 共有 {len(all_products)} 个商品")
for product in all_products:
print(f" - {product['sku']}: {product['attributes'].get('name', '未知')}")
# 测试统计信息
print("\n4. 测试统计信息")
stats = pm.get_stats()
print(f"✅ 统计信息:")
print(f" 总商品数: {stats.get('total_products', 0)}")
print(f" 品牌数: {len(stats.get('brands', []))}")
print(f" 分类数: {len(stats.get('categories', []))}")
print(f" 品牌: {', '.join(stats.get('brands', []))}")
print(f" 分类: {', '.join(stats.get('categories', []))}")
return True
def test_product_relationships():
"""测试商品关系功能"""
print("\n🧪 测试商品关系功能...")
pm = create_product_memory(verbose=True)
# 搜索竞争对手关系
print("\n1. 搜索竞争对手关系")
results = pm.search_product("competitor", limit=5)
competitor_pairs = []
for result in results:
sku = result['sku']
relationships = result['relationships']
for rel in relationships:
if rel.get('type') == 'competitor':
competitor_pairs.append((sku, rel.get('target')))
print(f"✅ 找到 {len(competitor_pairs)} 对竞争关系:")
for pair in competitor_pairs:
print(f" {pair[0]} ↔ {pair[1]}")
# 搜索系列关系
print("\n2. 搜索系列关系")
results = pm.search_product("series", limit=5)
series_info = {}
for result in results:
sku = result['sku']
name = result['attributes'].get('name', '未知')
relationships = result['relationships']
for rel in relationships:
if rel.get('type') == 'series':
series = rel.get('target')
if series not in series_info:
series_info[series] = []
series_info[series].append(f"{sku}({name})")
print(f"✅ 找到 {len(series_info)} 个产品系列:")
for series, products in series_info.items():
print(f" {series}: {', '.join(products)}")
return True
def main():
"""主测试函数"""
print("🚀 ProductMemory功能测试套件")
print("=" * 60)
tests = [
("基本功能", test_product_memory_basic),
("搜索功能", test_product_search),
("管理功能", test_product_management),
("关系功能", test_product_relationships),
]
passed = 0
total = len(tests)
for test_name, test_func in tests:
print(f"\n{'='*20} {test_name} {'='*20}")
try:
if test_func():
passed += 1
print(f"✅ {test_name} 测试通过")
else:
print(f"❌ {test_name} 测试失败")
except Exception as e:
print(f"❌ {test_name} 测试异常: {e}")
print(f"\n{'='*60}")
print(f"📊 测试结果: {passed}/{total} 测试通过")
if passed == total:
print("🎉 所有测试通过!ProductMemory功能正常")
print("\n📋 功能验证:")
print("✅ 商品数据存储 - 支持属性、卖点、关系的结构化存储")
print("✅ 商品搜索 - 支持SKU、名称、属性、卖点的模糊搜索")
print("✅ 商品管理 - 支持添加、更新、查询、列表功能")
print("✅ 关系管理 - 支持竞争对手、产品系列等关系存储和查询")
print("✅ 统计信息 - 提供商品数量、品牌、分类等统计")
print("\n🔧 使用示例:")
print("from product_memory import create_product_memory")
print("pm = create_product_memory(verbose=True)")
print("pm.add_product('SKU-001', {...}, [...])")
print("results = pm.search_product('华为')")
else:
print("⚠️ 部分测试失败,请检查问题")
return passed == total
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)