Repository navigation
Expand file tree
/
Copy pathload_test.py
More file actions
486 lines (412 loc) · 18.3 KB
/
Copy pathload_test.py
File metadata and controls
486 lines (412 loc) · 18.3 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#!/usr/bin/env python
"""
Load testing client for the CSV Sensor Processing Service.
This script simulates high concurrency by uploading multiple CSV files
simultaneously to test the server's ability to handle load.
Usage:
python load_test.py --files 100 --concurrency 20
python load_test.py --files 50 --concurrency 10 --size large
"""
import argparse
import asyncio
import csv
import io
import random
import time
from datetime import datetime
from typing import List, Dict, Any
import aiohttp
from app.config import settings
class LoadTester:
"""Load testing client for CSV processing service."""
def __init__(self, api_url: str = None, concurrency: int = 10):
"""
Initialize the load tester.
Args:
api_url: Base URL of the API (default: from settings)
concurrency: Maximum concurrent requests (default: 10)
"""
self.api_url = api_url or f"http://localhost:{settings.api_port}"
self.concurrency = concurrency
self.semaphore = asyncio.Semaphore(concurrency)
self.results: List[Dict[str, Any]] = []
self.errors: List[Dict[str, Any]] = []
def generate_csv_content(self, num_rows: int = 100, sensor_count: int = 5) -> bytes:
"""
Generate random CSV content for testing.
Args:
num_rows: Number of data rows to generate
sensor_count: Number of unique sensors
Returns:
CSV content as bytes
"""
output = io.StringIO()
writer = csv.writer(output)
# Write header
writer.writerow(['sensor_id', 'timestamp', 'temperature'])
# Generate random sensor data
base_time = datetime.now()
for i in range(num_rows):
sensor_id = f"sensor_{random.randint(1, sensor_count):03d}"
# Generate timestamps in sequence
timestamp = base_time.replace(
hour=random.randint(0, 23),
minute=random.randint(0, 59),
second=random.randint(0, 59)
)
temperature = round(random.uniform(15.0, 35.0), 2)
writer.writerow([sensor_id, timestamp.isoformat(), temperature])
return output.getvalue().encode('utf-8')
def generate_csv_with_errors(self, num_rows: int = 100, error_rate: float = 0.1) -> bytes:
"""
Generate CSV content with some invalid rows for error testing.
Args:
num_rows: Number of data rows to generate
error_rate: Percentage of rows that should be invalid (0.0 to 1.0)
Returns:
CSV content as bytes
"""
output = io.StringIO()
writer = csv.writer(output)
# Write header
writer.writerow(['sensor_id', 'timestamp', 'temperature'])
base_time = datetime.now()
for i in range(num_rows):
# Randomly introduce errors
if random.random() < error_rate:
# Generate invalid row
error_type = random.choice(['missing_field', 'invalid_timestamp', 'invalid_temp'])
if error_type == 'missing_field':
writer.writerow(['sensor_001', base_time.isoformat()]) # Missing temperature
elif error_type == 'invalid_timestamp':
writer.writerow(['sensor_002', 'invalid-date', '25.5'])
else:
writer.writerow(['sensor_003', base_time.isoformat(), 'not-a-number'])
else:
# Generate valid row
sensor_id = f"sensor_{random.randint(1, 10):03d}"
timestamp = base_time.replace(
hour=random.randint(0, 23),
minute=random.randint(0, 59)
)
temperature = round(random.uniform(15.0, 35.0), 2)
writer.writerow([sensor_id, timestamp.isoformat(), temperature])
return output.getvalue().encode('utf-8')
async def upload_file(
self,
session: aiohttp.ClientSession,
file_content: bytes,
filename: str,
file_index: int
) -> Dict[str, Any]:
"""
Upload a single file to the API.
Args:
session: aiohttp client session
file_content: CSV file content
filename: Name of the file
file_index: Index of this file in the batch
Returns:
Result dictionary with timing and response data
"""
async with self.semaphore: # Limit concurrency
start_time = time.time()
try:
# Prepare multipart form data
form = aiohttp.FormData()
form.add_field(
'file',
file_content,
filename=filename,
content_type='text/csv'
)
# Upload the file
async with session.post(
f"{self.api_url}/upload",
data=form,
timeout=aiohttp.ClientTimeout(total=30)
) as response:
response_data = await response.json()
elapsed = time.time() - start_time
result = {
'file_index': file_index,
'filename': filename,
'status_code': response.status,
'file_id': response_data.get('file_id'),
'upload_time': elapsed,
'success': response.status == 202,
'timestamp': datetime.now().isoformat()
}
if result['success']:
self.results.append(result)
else:
result['error'] = response_data.get('detail', 'Unknown error')
self.errors.append(result)
return result
except asyncio.TimeoutError:
elapsed = time.time() - start_time
error = {
'file_index': file_index,
'filename': filename,
'status_code': 0,
'upload_time': elapsed,
'success': False,
'error': 'Request timeout',
'timestamp': datetime.now().isoformat()
}
self.errors.append(error)
return error
except Exception as e:
elapsed = time.time() - start_time
error = {
'file_index': file_index,
'filename': filename,
'status_code': 0,
'upload_time': elapsed,
'success': False,
'error': str(e),
'timestamp': datetime.now().isoformat()
}
self.errors.append(error)
return error
async def check_processing_status(
self,
session: aiohttp.ClientSession,
file_id: str,
max_wait: int = 60
) -> Dict[str, Any]:
"""
Poll the API to check if a file has been processed.
Args:
session: aiohttp client session
file_id: ID of the uploaded file
max_wait: Maximum time to wait in seconds
Returns:
Processing status information
"""
start_time = time.time()
while time.time() - start_time < max_wait:
try:
async with session.get(
f"{self.api_url}/status/{file_id}",
timeout=aiohttp.ClientTimeout(total=10)
) as response:
if response.status == 200:
data = await response.json()
status = data.get('status')
if status in ['processed', 'partial', 'failed']:
return {
'file_id': file_id,
'status': status,
'wait_time': time.time() - start_time,
'success': True
}
# Still processing, wait before retry
await asyncio.sleep(0.5)
except Exception as e:
return {
'file_id': file_id,
'status': 'error',
'wait_time': time.time() - start_time,
'success': False,
'error': str(e)
}
# Timeout
return {
'file_id': file_id,
'status': 'timeout',
'wait_time': max_wait,
'success': False,
'error': 'Processing timeout exceeded'
}
async def run_load_test(
self,
num_files: int = 100,
csv_size: str = 'medium',
include_errors: bool = False,
wait_for_processing: bool = False
):
"""
Run the load test by uploading multiple files concurrently.
Args:
num_files: Number of files to upload
csv_size: Size of CSV files ('small', 'medium', 'large')
include_errors: Whether to include invalid rows in some files
wait_for_processing: Whether to wait for all files to be processed
"""
# Determine CSV size
size_config = {
'small': (50, 5), # 50 rows, 5 sensors
'medium': (200, 10), # 200 rows, 10 sensors
'large': (1000, 20), # 1000 rows, 20 sensors
}
num_rows, sensor_count = size_config.get(csv_size, size_config['medium'])
print(f"\n{'='*70}")
print(f"🚀 LOAD TEST CONFIGURATION")
print(f"{'='*70}")
print(f"API URL: {self.api_url}")
print(f"Total Files: {num_files}")
print(f"Concurrency: {self.concurrency}")
print(f"CSV Size: {csv_size} ({num_rows} rows, {sensor_count} sensors)")
print(f"Include Errors: {include_errors}")
print(f"Wait for Results: {wait_for_processing}")
print(f"{'='*70}\n")
# Generate file contents
print("📝 Generating CSV files...")
files_data = []
for i in range(num_files):
if include_errors and i % 5 == 0: # 20% error files
content = self.generate_csv_with_errors(num_rows, error_rate=0.2)
filename = f"load_test_errors_{i:04d}.csv"
else:
content = self.generate_csv_content(num_rows, sensor_count)
filename = f"load_test_{i:04d}.csv"
files_data.append((content, filename, i))
print(f"✅ Generated {num_files} CSV files\n")
# Upload files concurrently
print(f"⬆️ Uploading {num_files} files with max {self.concurrency} concurrent requests...")
start_time = time.time()
async with aiohttp.ClientSession() as session:
upload_tasks = [
self.upload_file(session, content, filename, idx)
for content, filename, idx in files_data
]
# Execute uploads with progress updates
upload_results = []
for i, task in enumerate(asyncio.as_completed(upload_tasks)):
result = await task
upload_results.append(result)
# Progress indicator every 10 files
if (i + 1) % 10 == 0 or (i + 1) == num_files:
elapsed = time.time() - start_time
rate = (i + 1) / elapsed if elapsed > 0 else 0
print(f" Progress: {i+1}/{num_files} files uploaded ({rate:.1f} files/sec)")
upload_elapsed = time.time() - start_time
# Print upload summary
print(f"\n{'='*70}")
print(f"📊 UPLOAD RESULTS")
print(f"{'='*70}")
print(f"Total Time: {upload_elapsed:.2f}s")
print(f"Successful: {len(self.results)}")
print(f"Failed: {len(self.errors)}")
print(f"Upload Rate: {num_files/upload_elapsed:.2f} files/sec")
if self.results:
upload_times = [r['upload_time'] for r in self.results]
print(f"Avg Upload Time: {sum(upload_times)/len(upload_times):.3f}s")
print(f"Min Upload Time: {min(upload_times):.3f}s")
print(f"Max Upload Time: {max(upload_times):.3f}s")
if self.errors:
print(f"\n❌ Errors encountered:")
for err in self.errors[:5]: # Show first 5 errors
print(f" - File {err['filename']}: {err.get('error', 'Unknown error')}")
if len(self.errors) > 5:
print(f" ... and {len(self.errors) - 5} more errors")
# Optionally wait for processing
if wait_for_processing and self.results:
print(f"\n{'='*70}")
print(f"⏳ WAITING FOR PROCESSING")
print(f"{'='*70}")
print(f"Checking status of {len(self.results)} uploaded files...\n")
process_start = time.time()
file_ids = [r['file_id'] for r in self.results if r.get('file_id')]
status_tasks = [
self.check_processing_status(session, file_id)
for file_id in file_ids
]
processing_results = []
for i, task in enumerate(asyncio.as_completed(status_tasks)):
result = await task
processing_results.append(result)
if (i + 1) % 10 == 0 or (i + 1) == len(file_ids):
print(f" Progress: {i+1}/{len(file_ids)} files checked")
process_elapsed = time.time() - process_start
# Processing summary
processed = sum(1 for r in processing_results if r.get('status') == 'processed')
partial = sum(1 for r in processing_results if r.get('status') == 'partial')
failed = sum(1 for r in processing_results if r.get('status') == 'failed')
errors = sum(1 for r in processing_results if r.get('status') in ['error', 'timeout'])
print(f"\n{'='*70}")
print(f"📊 PROCESSING RESULTS")
print(f"{'='*70}")
print(f"Total Time: {process_elapsed:.2f}s")
print(f"Processed: {processed}")
print(f"Partial: {partial}")
print(f"Failed: {failed}")
print(f"Errors/Timeout: {errors}")
if processing_results:
wait_times = [r['wait_time'] for r in processing_results if r.get('success')]
if wait_times:
print(f"Avg Wait Time: {sum(wait_times)/len(wait_times):.2f}s")
print(f"Min Wait Time: {min(wait_times):.2f}s")
print(f"Max Wait Time: {max(wait_times):.2f}s")
print(f"\n{'='*70}")
print(f"✅ LOAD TEST COMPLETE")
print(f"{'='*70}\n")
async def main():
"""Main entry point for the load testing script."""
parser = argparse.ArgumentParser(
description='Load test the CSV Sensor Processing Service',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Upload 50 files with 10 concurrent requests
python load_test.py --files 50 --concurrency 10
# Upload 100 large files with 20 concurrent requests
python load_test.py --files 100 --concurrency 20 --size large
# Include files with errors and wait for processing
python load_test.py --files 30 --errors --wait
# Stress test with 500 files
python load_test.py --files 500 --concurrency 50 --size small
"""
)
parser.add_argument(
'--files',
type=int,
default=50,
help='Number of files to upload (default: 50)'
)
parser.add_argument(
'--concurrency',
type=int,
default=10,
help='Maximum concurrent requests (default: 10)'
)
parser.add_argument(
'--size',
choices=['small', 'medium', 'large'],
default='medium',
help='Size of CSV files: small (50 rows), medium (200 rows), large (1000 rows)'
)
parser.add_argument(
'--errors',
action='store_true',
help='Include files with invalid rows for error testing'
)
parser.add_argument(
'--wait',
action='store_true',
help='Wait for all files to be processed and show results'
)
parser.add_argument(
'--api-url',
type=str,
default=None,
help=f'API base URL (default: http://localhost:{settings.api_port})'
)
args = parser.parse_args()
# Create and run load tester
tester = LoadTester(api_url=args.api_url, concurrency=args.concurrency)
await tester.run_load_test(
num_files=args.files,
csv_size=args.size,
include_errors=args.errors,
wait_for_processing=args.wait
)
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n\n⚠️ Load test interrupted by user")
except Exception as e:
print(f"\n\n❌ Load test failed: {e}")
raise