-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api.py
More file actions
203 lines (176 loc) Β· 6.63 KB
/
Copy pathtest_api.py
File metadata and controls
203 lines (176 loc) Β· 6.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
"""
Test script for the FastAPI PDF Legal Q&A API
Tests basic functionality of all endpoints
"""
import requests
import json
import time
import os
BASE_URL = "http://localhost:8000"
def test_health():
"""Test the health endpoint"""
print("π₯ Testing health endpoint...")
try:
response = requests.get(f"{BASE_URL}/health")
if response.status_code == 200:
data = response.json()
print(f"β
Health check passed: {data['message']}")
print(f" - Ollama available: {data['ollama_available']}")
print(f" - PDF loaded: {data['pdf_loaded']}")
return True
else:
print(f"β Health check failed: {response.status_code}")
return False
except Exception as e:
print(f"β Health check error: {str(e)}")
return False
def test_upload_pdf():
"""Test PDF upload - requires a PDF file in the current directory"""
print("π Testing PDF upload...")
# Look for PDF files in current directory
pdf_files = [f for f in os.listdir(".") if f.endswith(".pdf")]
if not pdf_files:
print("β οΈ No PDF files found in current directory. Skipping upload test.")
return False
pdf_file = pdf_files[0]
print(f" Using PDF: {pdf_file}")
try:
with open(pdf_file, 'rb') as f:
files = {'file': (pdf_file, f, 'application/pdf')}
response = requests.post(f"{BASE_URL}/upload-pdf", files=files)
if response.status_code == 200:
data = response.json()
print(f"β
PDF upload successful: {data['message']}")
if data.get('pdf_info'):
info = data['pdf_info']
print(f" - Chunks: {info['chunks_count']}")
print(f" - Characters: {info['total_characters']}")
return True
else:
print(f"β PDF upload failed: {response.status_code}")
print(f" Response: {response.text}")
return False
except Exception as e:
print(f"β PDF upload error: {str(e)}")
return False
def test_pdf_info():
"""Test getting PDF info"""
print("βΉοΈ Testing PDF info endpoint...")
try:
response = requests.get(f"{BASE_URL}/pdf-info")
if response.status_code == 200:
data = response.json()
print(f"β
PDF info retrieved")
print(f" - Filename: {data.get('filename', 'N/A')}")
print(f" - Upload time: {data.get('upload_time', 'N/A')}")
return True
elif response.status_code == 404:
print("β οΈ No PDF loaded")
return False
else:
print(f"β PDF info failed: {response.status_code}")
return False
except Exception as e:
print(f"β PDF info error: {str(e)}")
return False
def test_ask_question():
"""Test asking a question"""
print("β Testing question endpoint...")
test_questions = [
"What is this document about?",
"Can you summarize the main points?",
"What are the key legal requirements mentioned?"
]
for question in test_questions:
print(f" Asking: {question}")
try:
payload = {
"question": question,
"use_enhanced_reasoning": True
}
response = requests.post(f"{BASE_URL}/ask", json=payload)
if response.status_code == 200:
data = response.json()
print(f"β
Question answered")
print(f" - Answer length: {len(data['answer'])} characters")
print(f" - Processing time: {data.get('processing_time', 'N/A')} seconds")
return True
else:
print(f"β Question failed: {response.status_code}")
print(f" Response: {response.text}")
continue
except Exception as e:
print(f"β Question error: {str(e)}")
continue
return False
def test_models():
"""Test Ollama models endpoint"""
print("π€ Testing models endpoint...")
try:
response = requests.get(f"{BASE_URL}/models")
if response.status_code == 200:
data = response.json()
print(f"β
Models retrieved")
if 'models' in data:
models = data['models']
print(f" - Found {len(models.get('models', []))} models")
return True
else:
print(f"β Models failed: {response.status_code}")
return False
except Exception as e:
print(f"β Models error: {str(e)}")
return False
def test_ollama():
"""Test Ollama connection"""
print("π¦ Testing Ollama connection...")
try:
response = requests.post(f"{BASE_URL}/test-ollama")
if response.status_code == 200:
data = response.json()
print(f"β
Ollama test passed: {data['message']}")
print(f" - Response: {data.get('response', 'N/A')}")
return True
else:
print(f"β Ollama test failed: {response.status_code}")
print(f" Response: {response.text}")
return False
except Exception as e:
print(f"β Ollama test error: {str(e)}")
return False
def main():
"""Run all tests"""
print("π Starting FastAPI PDF Legal Q&A API Tests")
print("=" * 50)
# Give the server time to start if just launched
print("β³ Waiting 3 seconds for server to be ready...")
time.sleep(3)
tests = [
("Health Check", test_health),
("Ollama Connection", test_ollama),
("Models List", test_models),
("PDF Upload", test_upload_pdf),
("PDF Info", test_pdf_info),
("Ask Question", test_ask_question),
]
results = {}
for test_name, test_func in tests:
print(f"\n--- {test_name} ---")
results[test_name] = test_func()
print("\n" + "=" * 50)
print("π Test Results Summary:")
passed = 0
for test_name, result in results.items():
status = "β
PASS" if result else "β FAIL"
print(f" {test_name}: {status}")
if result:
passed += 1
print(f"\nπ― Overall: {passed}/{len(tests)} tests passed")
if passed == len(tests):
print("π All tests passed! API is working correctly.")
elif passed > len(tests) // 2:
print("β οΈ Most tests passed. Check failed tests above.")
else:
print("β Many tests failed. Check server status and dependencies.")
if __name__ == "__main__":
main()