SanadLLM / tests /test_api.py
Hydra-Bolt
restructured
eef2a73
#!/usr/bin/env python3
"""
Test script for SanadCheck API endpoints.
"""
import asyncio
import json
from typing import Dict, Any
import httpx
class SanadCheckTester:
"""Test client for SanadCheck API."""
def __init__(self, base_url: str = "http://localhost:8000"):
self.base_url = base_url
async def test_health_check(self) -> Dict[str, Any]:
"""Test the health check endpoint."""
async with httpx.AsyncClient() as client:
response = await client.get(f"{self.base_url}/api/v1/health")
return {
"status_code": response.status_code,
"response": response.json()
}
async def test_extract_narrators(self) -> Dict[str, Any]:
"""Test the narrator extraction endpoint."""
sample_hadith = """
حدثنا محمد بن إسماعيل قال حدثنا عبد الله بن موسى قال أخبرنا إسرائيل عن أبي إسحاق عن البراء قال:
قال رسول الله صلى الله عليه وسلم: إذا أتيت مضجعك فتوضأ وضوءك للصلاة ثم اضطجع على شقك الأيمن
"""
payload = {"hadith_text": sample_hadith.strip()}
async with httpx.AsyncClient() as client:
response = await client.post(
f"{self.base_url}/api/v1/extract-narrators",
json=payload,
timeout=30.0
)
return {
"status_code": response.status_code,
"response": response.json() if response.status_code == 200 else response.text
}
async def test_analyze_narrator(self) -> Dict[str, Any]:
"""Test the narrator analysis endpoint."""
payload = {
"narrator_name": "عُبَيْدِ اللَّهِ بْنِ أَبِي رَافِعٍ"
}
async with httpx.AsyncClient() as client:
response = await client.post(
f"{self.base_url}/api/v1/analyze-narrator",
json=payload,
timeout=30.0
)
return {
"status_code": response.status_code,
"response": response.json() if response.status_code == 200 else response.text
}
async def run_tests():
"""Run all tests."""
tester = SanadCheckTester()
print("🔍 Testing SanadCheck API")
print("=" * 50)
# Test health check
print("\n1. Testing Health Check...")
health_result = await tester.test_health_check()
print(f"Status: {health_result['status_code']}")
print(f"Response: {json.dumps(health_result['response'], indent=2, ensure_ascii=False)}")
# Test narrator extraction
print("\n2. Testing Narrator Extraction...")
extract_result = await tester.test_extract_narrators()
print(f"Status: {extract_result['status_code']}")
if extract_result['status_code'] == 200:
print(f"Response: {json.dumps(extract_result['response'], indent=2, ensure_ascii=False)}")
else:
print(f"Error: {extract_result['response']}")
# Test narrator analysis
print("\n3. Testing Narrator Analysis...")
analysis_result = await tester.test_analyze_narrator()
print(f"Status: {analysis_result['status_code']}")
if analysis_result['status_code'] == 200:
print(f"Response: {json.dumps(analysis_result['response'], indent=2, ensure_ascii=False)}")
else:
print(f"Error: {analysis_result['response']}")
print("\n" + "=" * 50)
print("✅ Tests completed!")
if __name__ == "__main__":
try:
asyncio.run(run_tests())
except KeyboardInterrupt:
print("\n❌ Tests interrupted by user")
except Exception as e:
print(f"\n❌ Test failed with error: {e}")