-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_fastapi.py
More file actions
174 lines (147 loc) Β· 5.99 KB
/
test_fastapi.py
File metadata and controls
174 lines (147 loc) Β· 5.99 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
"""
Test script for FloatChat FastAPI application
============================================
This script tests the FastAPI endpoints to ensure they work correctly.
"""
import requests
import time
import json
from pathlib import Path
# API base URL
BASE_URL = "http://localhost:8001"
def test_health_endpoint():
"""Test the health check endpoint."""
print("π Testing health endpoint...")
try:
response = requests.get(f"{BASE_URL}/health")
if response.status_code == 200:
health_data = response.json()
print(f"β Health check passed: {health_data['status']}")
print(f" Services: {health_data['services']}")
return True
else:
print(f"β Health check failed: {response.status_code}")
return False
except Exception as e:
print(f"β Health check error: {e}")
return False
def test_root_endpoint():
"""Test the root endpoint."""
print("π Testing root endpoint...")
try:
response = requests.get(f"{BASE_URL}/")
if response.status_code == 200:
root_data = response.json()
print(f"β Root endpoint working: {root_data['message']}")
return True
else:
print(f"β Root endpoint failed: {response.status_code}")
return False
except Exception as e:
print(f"β Root endpoint error: {e}")
return False
def test_file_upload():
"""Test file upload with a sample NetCDF file."""
print("π Testing file upload...")
# Check if we have any sample NetCDF files
sample_files = []
data_dirs = [
Path("2019"),
Path("argo_data"),
Path("argo_data_2020_01"),
Path("data")
]
for data_dir in data_dirs:
if data_dir.exists():
nc_files = list(data_dir.glob("*.nc"))
if nc_files:
sample_files.extend(nc_files[:1]) # Take one file from each directory
if not sample_files:
print("β οΈ No sample NetCDF files found for testing")
return False
# Test with the first available file
test_file = sample_files[0]
print(f"π Using test file: {test_file}")
try:
with open(test_file, 'rb') as f:
files = {'file': (test_file.name, f, 'application/octet-stream')}
response = requests.post(f"{BASE_URL}/upload", files=files)
if response.status_code == 200:
upload_result = response.json()
task_id = upload_result['task_id']
print(f"β File uploaded successfully, task ID: {task_id}")
# Wait a bit and check status
print("β³ Waiting for processing...")
time.sleep(5)
status_response = requests.get(f"{BASE_URL}/status/{task_id}")
if status_response.status_code == 200:
status_data = status_response.json()
print(f"π Processing status: {status_data['status']}")
print(f"π¬ Message: {status_data['message']}")
if status_data['status'] == 'completed':
print("β
File processing completed successfully!")
if 'extracted_data' in status_data:
print("π Extracted data preview:")
extracted = status_data['extracted_data']
print(f" - Profiles: {extracted.get('total_profiles', 'N/A')}")
print(f" - Measurements: {list(extracted.get('measurements', {}).keys())}")
if 'storage_results' in status_data:
storage = status_data['storage_results']
print("πΎ Storage results:")
print(f" - ChromaDB: {storage.get('chromadb', {}).get('status', 'N/A')}")
print(f" - Supabase: {storage.get('supabase', {}).get('status', 'N/A')}")
return True
else:
print(f"β Status check failed: {status_response.status_code}")
return False
else:
print(f"β File upload failed: {response.status_code}")
print(f"Response: {response.text}")
return False
except Exception as e:
print(f"β File upload error: {e}")
return False
def run_tests():
"""Run all tests."""
print("π Starting FastAPI tests...")
print("=" * 50)
tests = [
("Root Endpoint", test_root_endpoint),
("Health Check", test_health_endpoint),
("File Upload", test_file_upload)
]
results = {}
for test_name, test_func in tests:
print(f"\nπ Running: {test_name}")
results[test_name] = test_func()
print("-" * 30)
print("\nπ TEST SUMMARY")
print("=" * 50)
passed = 0
total = len(tests)
for test_name, result in results.items():
status = "β
PASS" if result else "β FAIL"
print(f"{test_name}: {status}")
if result:
passed += 1
print(f"\nResults: {passed}/{total} tests passed")
if passed == total:
print("π All tests passed! FastAPI application is working correctly.")
else:
print("β οΈ Some tests failed. Check the logs above for details.")
if __name__ == "__main__":
print("FastAPI Test Suite")
print("Make sure the FastAPI server is running on localhost:8001")
print("You can start it with: python fastapi_app.py")
print()
# Check if server is running
try:
response = requests.get(f"{BASE_URL}/", timeout=5)
if response.status_code == 200:
run_tests()
else:
print("β FastAPI server not responding correctly")
except requests.exceptions.ConnectionError:
print("β Cannot connect to FastAPI server. Make sure it's running on localhost:8001")
except Exception as e:
print(f"β Error connecting to server: {e}")