sisi-astrology-api / test_knowledge_endpoints.py
th
🦊 API强化完成:知识库端点+AI个性化解读
9e62548
Raw History Blame Contribute Delete
7.73 kB
#!/usr/bin/env python3
"""
🧪 Test Script for Knowledge Base Endpoints
Run this to verify all 3 new FREE endpoints are working
"""
import sys
sys.path.insert(0, '.')
from knowledge_base import (
get_zodiac_profile,
get_planet_in_sign,
get_planet_in_house,
clear_cache,
ZODIAC_SIGNS,
AVAILABLE_PLANETS_SIGNS,
AVAILABLE_PLANETS_HOUSES
)
import time
def test_zodiac_profiles():
"""Test all 12 zodiac sign profiles"""
print("\n" + "="*80)
print("1️⃣ Testing Zodiac Profiles (12 signs)")
print("="*80)
for sign in ZODIAC_SIGNS:
try:
start = time.time()
result = get_zodiac_profile(sign)
elapsed = (time.time() - start) * 1000
assert result['sign'].lower() == sign
assert result['symbol'] in ['♈', '♉', '♊', '♋', '♌', '♍', '♎', '♏', '♐', '♑', '♒', '♓']
assert result['element'] in ['Fire', 'Earth', 'Air', 'Water']
assert len(result['essence']) > 100
assert len(result['keywords']) > 0
print(f" ✅ {sign.capitalize():12} - {result['symbol']} {result['element']:5} - "
f"{elapsed:5.1f}ms - {len(result['essence'])} chars")
except Exception as e:
print(f" ❌ {sign.capitalize():12} - Error: {e}")
return False
print(f"\n 🎉 All 12 zodiac profiles working!")
return True
def test_planets_in_signs():
"""Test Sun and Moon in all 12 signs"""
print("\n" + "="*80)
print(f"2️⃣ Testing Planets in Signs ({len(AVAILABLE_PLANETS_SIGNS)} planets × 12 signs = {len(AVAILABLE_PLANETS_SIGNS) * 12} combinations)")
print("="*80)
for planet in AVAILABLE_PLANETS_SIGNS:
print(f"\n {planet.upper()} in Signs:")
for sign in ZODIAC_SIGNS:
try:
start = time.time()
result = get_planet_in_sign(planet, sign)
elapsed = (time.time() - start) * 1000
assert result['planet'].lower() == planet
assert result['sign'].lower() == sign
assert len(result['full_content']) > 100
status = "✅"
if result.get('core_traits'):
status += f" ({len(result['core_traits'])} traits)"
print(f" {status:20} {sign.capitalize():12} - {elapsed:5.1f}ms")
except Exception as e:
print(f" ❌ {sign.capitalize():12} - Error: {e}")
return False
print(f"\n 🎉 All 24 planet-in-sign combinations working!")
return True
def test_planets_in_houses():
"""Test Sun in all 12 houses (Moon not yet available)"""
print("\n" + "="*80)
print(f"3️⃣ Testing Planets in Houses ({len(AVAILABLE_PLANETS_HOUSES)} planet × 12 houses = {len(AVAILABLE_PLANETS_HOUSES) * 12} combinations)")
print("="*80)
for planet in AVAILABLE_PLANETS_HOUSES:
print(f"\n {planet.upper()} in Houses:")
for house in range(1, 13):
try:
start = time.time()
result = get_planet_in_house(planet, house)
elapsed = (time.time() - start) * 1000
assert result['planet'].lower() == planet
assert result['house'] == house
assert len(result['full_content']) > 100
assert 'life_focus' in result
ordinal = result['ordinal']
focus = result['life_focus'][:40]
print(f" ✅ House {house:2} ({ordinal:3}) - {elapsed:5.1f}ms - {focus}...")
except Exception as e:
print(f" ❌ House {house:2} - Error: {e}")
return False
print(f"\n 🎉 All {len(AVAILABLE_PLANETS_HOUSES) * 12} planet-in-house combinations working!")
return True
def test_error_handling():
"""Test error cases"""
print("\n" + "="*80)
print("4️⃣ Testing Error Handling")
print("="*80)
tests_passed = 0
tests_total = 4
# Test 1: Invalid zodiac sign
try:
get_zodiac_profile('invalid_sign')
print(" ❌ Should have raised error for invalid sign")
except ValueError:
print(" ✅ Invalid zodiac sign - correctly raised ValueError")
tests_passed += 1
# Test 2: Planet not available
try:
get_planet_in_sign('venus', 'aries')
print(" ❌ Should have raised error for unavailable planet")
except ValueError as e:
if 'not yet available' in str(e):
print(" ✅ Unavailable planet - correctly raised ValueError with helpful message")
tests_passed += 1
# Test 3: Invalid house
try:
get_planet_in_house('sun', 15)
print(" ❌ Should have raised error for invalid house")
except ValueError:
print(" ✅ Invalid house - correctly raised ValueError")
tests_passed += 1
# Test 4: Invalid house (0)
try:
get_planet_in_house('sun', 0)
print(" ❌ Should have raised error for house 0")
except ValueError:
print(" ✅ House 0 - correctly raised ValueError")
tests_passed += 1
print(f"\n 🎉 Error handling: {tests_passed}/{tests_total} tests passed")
return tests_passed == tests_total
def test_caching():
"""Test caching performance"""
print("\n" + "="*80)
print("5️⃣ Testing Cache Performance")
print("="*80)
# Clear cache first
clear_cache()
# First call (should be slower)
start = time.time()
result1 = get_zodiac_profile('aries')
time1 = (time.time() - start) * 1000
# Second call (should be much faster from cache)
start = time.time()
result2 = get_zodiac_profile('aries')
time2 = (time.time() - start) * 1000
# Verify results are identical
assert result1 == result2
speedup = time1 / time2 if time2 > 0 else 0
print(f" First call: {time1:6.2f}ms (file read + parse)")
print(f" Second call: {time2:6.2f}ms (cached)")
print(f" Speedup: {speedup:6.1f}x faster")
if speedup > 5:
print(" ✅ Caching is working excellently!")
return True
elif speedup > 2:
print(" ✅ Caching is working!")
return True
else:
print(" ⚠️ Cache speedup lower than expected")
return False
def main():
"""Run all tests"""
print("\n" + "="*80)
print("🔮 KNOWLEDGE BASE API - COMPREHENSIVE TEST SUITE")
print("="*80)
print("Testing all 3 FREE endpoints with 72+ combinations")
print("="*80)
results = {}
# Run all tests
results['zodiac_profiles'] = test_zodiac_profiles()
results['planets_in_signs'] = test_planets_in_signs()
results['planets_in_houses'] = test_planets_in_houses()
results['error_handling'] = test_error_handling()
results['caching'] = test_caching()
# Summary
print("\n" + "="*80)
print("📊 TEST SUMMARY")
print("="*80)
total = len(results)
passed = sum(1 for v in results.values() if v)
for name, passed_test in results.items():
status = "✅ PASS" if passed_test else "❌ FAIL"
print(f" {status:10} - {name.replace('_', ' ').title()}")
print("\n" + "="*80)
print(f" TOTAL: {passed}/{total} test suites passed")
print("="*80)
if passed == total:
print("\n 🎉 ALL TESTS PASSED! Ready for deployment!")
print(" 💰 Zero AI cost, <100ms response time")
print(" 🚀 Deploy to Hugging Face Spaces now!")
return 0
else:
print("\n ⚠️ Some tests failed. Please review and fix.")
return 1
if __name__ == "__main__":
exit(main())