Repository navigation
Expand file tree
/
Copy pathtest_api.py
More file actions
278 lines (218 loc) · 8.38 KB
/
Copy pathtest_api.py
File metadata and controls
278 lines (218 loc) · 8.38 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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/usr/bin/env python3
"""
Test script for the QuantLink FREN Narrator Web API.
This script tests all the available endpoints to ensure they are working correctly.
It's a simple way to verify the functionality of the API server.
Usage:
python test_api.py [--host HOST] [--port PORT]
"""
import argparse
import requests
import json
import time
import sys
def print_success(message):
"""Print a success message with green color."""
print(f"\033[92m✓ {message}\033[0m")
def print_error(message):
"""Print an error message with red color."""
print(f"\033[91m✗ {message}\033[0m")
def print_info(message):
"""Print an info message with blue color."""
print(f"\033[94m→ {message}\033[0m")
def print_header(message):
"""Print a header message with yellow background."""
print(f"\033[43m\033[30m {message} \033[0m")
def test_health_endpoint(base_url):
"""Test the health check endpoint."""
print_header("Testing Health Check Endpoint")
try:
response = requests.get(f"{base_url}/api/health", timeout=5)
response.raise_for_status()
data = response.json()
if data.get("status") == "healthy":
print_success("Health check passed")
return True
else:
print_error(f"Health check failed: {data}")
return False
except Exception as e:
print_error(f"Health check failed with error: {str(e)}")
return False
def test_crypto_price_endpoint(base_url):
"""Test the cryptocurrency price endpoint."""
print_header("Testing Cryptocurrency Price Endpoint")
# Test basic price
try:
response = requests.get(f"{base_url}/api/crypto/price?crypto=bitcoin¤cy=usd", timeout=5)
response.raise_for_status()
data = response.json()
if data.get("success") and data.get("current_price") is not None:
print_success("Basic price fetch passed")
else:
print_error(f"Basic price fetch failed: {data}")
return False
except Exception as e:
print_error(f"Basic price fetch failed with error: {str(e)}")
return False
# Test price with 24h change
try:
response = requests.get(
f"{base_url}/api/crypto/price?crypto=bitcoin¤cy=usd&with_24h_change=true",
timeout=5
)
response.raise_for_status()
data = response.json()
if (data.get("success") and data.get("current_price") is not None and
"price_change_24h" in data):
print_success("Price with 24h change fetch passed")
return True
else:
print_error(f"Price with 24h change fetch failed: {data}")
return False
except Exception as e:
print_error(f"Price with 24h change fetch failed with error: {str(e)}")
return False
def test_multiple_prices_endpoint(base_url):
"""Test the multiple cryptocurrency prices endpoint."""
print_header("Testing Multiple Cryptocurrency Prices Endpoint")
try:
response = requests.get(
f"{base_url}/api/crypto/prices?cryptos=bitcoin,ethereum,solana¤cy=usd",
timeout=5
)
response.raise_for_status()
data = response.json()
if (data.get("success") and
isinstance(data.get("prices"), dict) and
len(data.get("prices", {})) == 3):
print_success("Multiple prices fetch passed")
return True
else:
print_error(f"Multiple prices fetch failed: {data}")
return False
except Exception as e:
print_error(f"Multiple prices fetch failed with error: {str(e)}")
return False
def test_narrate_text_endpoint(base_url):
"""Test the narrate text endpoint."""
print_header("Testing Narrate Text Endpoint")
try:
payload = {
"text": "Hello world, this is a test of the narration API.",
"return_audio": False
}
response = requests.post(
f"{base_url}/api/narrator/text",
json=payload,
timeout=10
)
response.raise_for_status()
data = response.json()
if data.get("success") and "file_id" in data:
file_id = data["file_id"]
print_success(f"Text narration passed, got file ID: {file_id}")
return file_id
else:
print_error(f"Text narration failed: {data}")
return None
except Exception as e:
print_error(f"Text narration failed with error: {str(e)}")
return None
def test_get_audio_file_endpoint(base_url, file_id):
"""Test the get audio file endpoint."""
print_header("Testing Get Audio File Endpoint")
if not file_id:
print_info("Skipping audio file fetch because no file ID is available")
return True
try:
response = requests.head(
f"{base_url}/api/narrator/audio/{file_id}",
timeout=5
)
response.raise_for_status()
content_type = response.headers.get("Content-Type")
if content_type and "audio" in content_type:
print_success(f"Audio file fetch passed with content type: {content_type}")
return True
else:
print_error(f"Audio file fetch returned unexpected content type: {content_type}")
return False
except Exception as e:
print_error(f"Audio file fetch failed with error: {str(e)}")
return False
def test_narrate_crypto_endpoint(base_url):
"""Test the narrate cryptocurrency price endpoint."""
print_header("Testing Narrate Cryptocurrency Price Endpoint")
try:
payload = {
"crypto": "bitcoin",
"currency": "usd",
"with_24h_change": True,
"return_audio": False
}
response = requests.post(
f"{base_url}/api/narrator/crypto",
json=payload,
timeout=10
)
response.raise_for_status()
data = response.json()
if (data.get("success") and
"file_id" in data and
"narration_text" in data and
"price_data" in data):
print_success(f"Cryptocurrency narration passed")
return True
else:
print_error(f"Cryptocurrency narration failed: {data}")
return False
except Exception as e:
print_error(f"Cryptocurrency narration failed with error: {str(e)}")
return False
def main():
"""Main function to run all tests."""
parser = argparse.ArgumentParser(description="Test the QuantLink FREN Narrator Web API")
parser.add_argument('--host', type=str, default='localhost', help='Host of the API server')
parser.add_argument('--port', type=int, default=5001, help='Port of the API server')
args = parser.parse_args()
base_url = f"http://{args.host}:{args.port}"
print_info(f"Testing API at {base_url}")
print_info("==================================")
# Track overall test success
all_tests_passed = True
# Test health endpoint
if not test_health_endpoint(base_url):
all_tests_passed = False
print("\n") # Add some spacing
# Test crypto price endpoint
if not test_crypto_price_endpoint(base_url):
all_tests_passed = False
print("\n") # Add some spacing
# Test multiple prices endpoint
if not test_multiple_prices_endpoint(base_url):
all_tests_passed = False
print("\n") # Add some spacing
# Test narrate text endpoint
file_id = test_narrate_text_endpoint(base_url)
if not file_id:
all_tests_passed = False
print("\n") # Add some spacing
# Test get audio file endpoint
if not test_get_audio_file_endpoint(base_url, file_id):
all_tests_passed = False
print("\n") # Add some spacing
# Test narrate crypto endpoint
if not test_narrate_crypto_endpoint(base_url):
all_tests_passed = False
print("\n") # Add some spacing
# Print summary
print_header("Test Summary")
if all_tests_passed:
print_success("All tests passed successfully!")
return 0
else:
print_error("Some tests failed. See above for details.")
return 1
if __name__ == "__main__":
sys.exit(main())