-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocustfile.py
More file actions
518 lines (431 loc) · 15.7 KB
/
Copy pathlocustfile.py
File metadata and controls
518 lines (431 loc) · 15.7 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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
"""
Locust Load Testing Configuration for Online Bookstore
Simulates realistic user behavior patterns for performance testing
Installation:
pip install locust
Usage:
# Start with web UI
locust -f locustfile.py --host=http://localhost:5000
# Headless mode (no UI)
locust -f locustfile.py --host=http://localhost:5000 --users 100 --spawn-rate 10 --run-time 1m --headless
# With custom settings
locust -f locustfile.py --host=http://localhost:5000 --users 50 --spawn-rate 5 --run-time 5m
Access Web UI:
http://localhost:8089
"""
from locust import HttpUser, task, between, tag, events
import random
import json
from datetime import datetime
# Sample data for testing
BOOK_TITLES = [
"The Great Gatsby",
"1984",
"Moby Dick",
"I Ching"
]
DISCOUNT_CODES = [
"SAVE10",
"WELCOME20",
"save10", # Test case sensitivity
"INVALID" # Test invalid code
]
VALID_EMAILS = [
"user1@test.com",
"user2@test.com",
"user3@test.com",
"loadtest@bookstore.com",
"performance@test.com"
]
PAYMENT_CARDS = {
"valid": "4532123456789012",
"failed": "4532123456781111" # Ends in 1111 - mock failure
}
class BookstoreUser(HttpUser):
"""
Simulates a typical user browsing and purchasing from the bookstore
Wait time: Between 1-3 seconds between tasks (simulates reading/thinking time)
"""
wait_time = between(1, 3)
def on_start(self):
"""
Called when a user starts (simulates user session initialization)
Initialize user-specific data
"""
self.email = random.choice(VALID_EMAILS)
self.password = "password123"
self.name = f"LoadTest User {random.randint(1, 1000)}"
self.cart_items = []
# Optional: Register and login
# Uncomment if you want users to register/login
# self.register_user()
# self.login_user()
def on_stop(self):
"""Called when a user stops (cleanup)"""
# Optional: Logout
pass
# ==================== BROWSING TASKS ====================
@task(10)
@tag('browsing', 'critical')
def view_homepage(self):
"""
View homepage with book catalog
Weight: 10 (most frequent action)
"""
with self.client.get("/", catch_response=True, name="GET /homepage") as response:
if response.status_code == 200 and b"Bookstore" in response.content:
response.success()
else:
response.failure("Homepage did not load correctly")
@task(3)
@tag('browsing')
def view_cart(self):
"""
View shopping cart
Weight: 3 (moderate frequency)
"""
with self.client.get("/cart", catch_response=True, name="GET /cart") as response:
if response.status_code == 200:
response.success()
else:
response.failure("Cart page did not load")
# ==================== CART MANAGEMENT TASKS ====================
@task(5)
@tag('cart', 'critical')
def add_to_cart(self):
"""
Add a random book to cart
Weight: 5 (frequent action)
"""
book_title = random.choice(BOOK_TITLES)
quantity = random.randint(1, 5)
data = {
'title': book_title,
'quantity': str(quantity)
}
with self.client.post("/add-to-cart", data=data, catch_response=True, name="POST /add-to-cart") as response:
if response.status_code in [200, 302]:
self.cart_items.append(book_title)
response.success()
else:
response.failure(f"Failed to add {book_title} to cart")
@task(2)
@tag('cart')
def update_cart_quantity(self):
"""
Update quantity of an item in cart
Weight: 2 (less frequent)
"""
if self.cart_items:
book_title = random.choice(self.cart_items)
new_quantity = random.randint(1, 10)
data = {
'title': book_title,
'quantity': str(new_quantity)
}
with self.client.post("/update-cart", data=data, catch_response=True, name="POST /update-cart") as response:
if response.status_code in [200, 302]:
response.success()
else:
response.failure("Failed to update cart")
@task(1)
@tag('cart')
def remove_from_cart(self):
"""
Remove an item from cart
Weight: 1 (occasional action)
"""
if self.cart_items:
book_title = random.choice(self.cart_items)
data = {'title': book_title}
with self.client.post("/remove-from-cart", data=data, catch_response=True, name="POST /remove-from-cart") as response:
if response.status_code in [200, 302]:
self.cart_items.remove(book_title)
response.success()
else:
response.failure("Failed to remove from cart")
@task(1)
@tag('cart')
def clear_cart(self):
"""
Clear entire cart
Weight: 1 (rare action)
"""
with self.client.post("/clear-cart", catch_response=True, name="POST /clear-cart") as response:
if response.status_code in [200, 302]:
self.cart_items.clear()
response.success()
else:
response.failure("Failed to clear cart")
# ==================== CHECKOUT TASKS ====================
@task(2)
@tag('checkout', 'critical')
def view_checkout(self):
"""
View checkout page
Weight: 2 (moderate frequency)
"""
with self.client.get("/checkout", catch_response=True, name="GET /checkout") as response:
if response.status_code in [200, 302]:
response.success()
else:
response.failure("Checkout page failed")
@task(1)
@tag('checkout', 'critical', 'transaction')
def complete_checkout_success(self):
"""
Complete a successful checkout process
Weight: 1 (critical but less frequent)
"""
# First add items to cart
for _ in range(random.randint(1, 3)):
book_title = random.choice(BOOK_TITLES)
self.client.post("/add-to-cart", data={
'title': book_title,
'quantity': str(random.randint(1, 3))
})
# Process checkout
discount_code = random.choice(DISCOUNT_CODES) if random.random() > 0.5 else ""
checkout_data = {
'name': self.name,
'email': self.email,
'address': f'{random.randint(1, 999)} Test St',
'city': 'Test City',
'zip_code': str(random.randint(10000, 99999)),
'payment_method': 'credit_card',
'card_number': PAYMENT_CARDS['valid'],
'expiry_date': '12/25',
'cvv': '123',
'discount_code': discount_code
}
with self.client.post("/process-checkout", data=checkout_data, catch_response=True, name="POST /process-checkout [Success]") as response:
if response.status_code in [200, 302]:
self.cart_items.clear()
response.success()
else:
response.failure("Checkout failed")
@task(1)
@tag('checkout', 'error-handling')
def complete_checkout_failed_payment(self):
"""
Test checkout with failed payment
Weight: 1 (test error handling)
"""
# Add item to cart
book_title = random.choice(BOOK_TITLES)
self.client.post("/add-to-cart", data={
'title': book_title,
'quantity': '1'
})
# Attempt checkout with failing card
checkout_data = {
'name': self.name,
'email': self.email,
'address': '123 Test St',
'city': 'Test City',
'zip_code': '12345',
'payment_method': 'credit_card',
'card_number': PAYMENT_CARDS['failed'], # This will fail
'expiry_date': '12/25',
'cvv': '123'
}
with self.client.post("/process-checkout", data=checkout_data, catch_response=True, name="POST /process-checkout [Failed Payment]") as response:
if response.status_code in [200, 302] and b'Payment failed' in response.content:
response.success()
else:
response.failure("Failed payment not handled correctly")
# ==================== AUTHENTICATION TASKS ====================
@task(1)
@tag('auth')
def register_user(self):
"""
Register a new user account
Weight: 1 (occasional action)
"""
unique_email = f"loadtest_{random.randint(1, 999999)}@test.com"
register_data = {
'email': unique_email,
'password': 'password123',
'name': f'LoadTest User {random.randint(1, 9999)}',
'address': f'{random.randint(1, 999)} Test Street'
}
with self.client.post("/register", data=register_data, catch_response=True, name="POST /register") as response:
if response.status_code in [200, 302]:
response.success()
else:
response.failure("Registration failed")
@task(1)
@tag('auth')
def login_user(self):
"""
Login with demo account
Weight: 1 (occasional action)
"""
login_data = {
'email': 'demo@bookstore.com',
'password': 'demo123'
}
with self.client.post("/login", data=login_data, catch_response=True, name="POST /login") as response:
if response.status_code in [200, 302]:
response.success()
else:
response.failure("Login failed")
@task(1)
@tag('auth')
def view_account(self):
"""
View account page
Weight: 1 (occasional action)
"""
with self.client.get("/account", catch_response=True, name="GET /account") as response:
if response.status_code in [200, 302]:
response.success()
else:
response.failure("Account page failed")
# ==================== EDGE CASE TESTS ====================
@task(1)
@tag('edge-case', 'error-handling')
def test_invalid_quantity(self):
"""
Test adding item with invalid quantity (error handling)
Weight: 1 (test robustness)
"""
invalid_quantities = ['abc', '-1', '0', '!@#$', '']
data = {
'title': random.choice(BOOK_TITLES),
'quantity': random.choice(invalid_quantities)
}
with self.client.post("/add-to-cart", data=data, catch_response=True, name="POST /add-to-cart [Invalid Qty]") as response:
# Should handle gracefully, not crash
if response.status_code in [200, 302, 400]:
response.success()
else:
response.failure("Invalid quantity not handled")
@task(1)
@tag('edge-case')
def test_nonexistent_book(self):
"""
Test adding non-existent book
Weight: 1 (test validation)
"""
data = {
'title': 'Nonexistent Book Title 12345',
'quantity': '1'
}
with self.client.post("/add-to-cart", data=data, catch_response=True, name="POST /add-to-cart [Invalid Book]") as response:
if response.status_code in [200, 302, 404]:
response.success()
else:
response.failure("Nonexistent book not handled")
class BrowsingUser(HttpUser):
"""
User that only browses without purchasing
Simulates window shoppers
"""
wait_time = between(2, 5)
@task(10)
@tag('browsing')
def browse_homepage(self):
self.client.get("/")
@task(3)
@tag('browsing')
def view_cart_empty(self):
self.client.get("/cart")
class PowerUser(HttpUser):
"""
Aggressive user that makes many rapid requests
Tests system under stress
"""
wait_time = between(0.5, 1)
@task(5)
def rapid_browsing(self):
self.client.get("/")
@task(3)
def rapid_cart_actions(self):
book = random.choice(BOOK_TITLES)
self.client.post("/add-to-cart", data={
'title': book,
'quantity': str(random.randint(1, 5))
})
# ==================== CUSTOM EVENTS & REPORTING ====================
@events.test_start.add_listener
def on_test_start(environment, **kwargs):
"""
Called when load test starts
"""
print("\n" + "="*60)
print("🚀 LOAD TEST STARTED")
print("="*60)
print(f"Target Host: {environment.host}")
print(f"Start Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("="*60 + "\n")
@events.test_stop.add_listener
def on_test_stop(environment, **kwargs):
"""
Called when load test stops
"""
print("\n" + "="*60)
print("🏁 LOAD TEST COMPLETED")
print("="*60)
print(f"End Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("="*60 + "\n")
# ==================== CUSTOM TASKS FOR SPECIFIC SCENARIOS ====================
class CheckoutOnlyUser(HttpUser):
"""
User focused on checkout process
Good for testing payment gateway performance
"""
wait_time = between(2, 4)
@task(1)
@tag('checkout', 'stress')
def quick_purchase(self):
"""Complete purchase quickly"""
# Add to cart
self.client.post("/add-to-cart", data={
'title': random.choice(BOOK_TITLES),
'quantity': '1'
})
# Checkout
self.client.post("/process-checkout", data={
'name': 'Speed Tester',
'email': f'speed{random.randint(1,9999)}@test.com',
'address': '123 Speed St',
'city': 'Fast City',
'zip_code': '12345',
'payment_method': 'credit_card',
'card_number': PAYMENT_CARDS['valid'],
'expiry_date': '12/25',
'cvv': '123'
})
# ==================== USAGE EXAMPLES ====================
"""
EXAMPLE COMMANDS:
1. Basic load test with web UI:
locust -f locustfile.py --host=http://localhost:5000
2. Headless mode (100 users, spawn 10/second, run 5 minutes):
locust -f locustfile.py --host=http://localhost:5000 --users 100 --spawn-rate 10 --run-time 5m --headless
3. Stress test (500 users, aggressive spawn):
locust -f locustfile.py --host=http://localhost:5000 --users 500 --spawn-rate 50 --run-time 10m --headless
4. Test specific tags only (critical paths):
locust -f locustfile.py --host=http://localhost:5000 --tags critical
5. Generate HTML report:
locust -f locustfile.py --host=http://localhost:5000 --users 100 --spawn-rate 10 --run-time 2m --headless --html report.html
6. Run with specific user class:
locust -f locustfile.py --host=http://localhost:5000 BookstoreUser
7. Distributed load testing (master):
locust -f locustfile.py --host=http://localhost:5000 --master
8. Distributed load testing (worker):
locust -f locustfile.py --host=http://localhost:5000 --worker --master-host=<master-ip>
PERFORMANCE TARGETS:
- Homepage load time: < 200ms (50th percentile)
- Cart operations: < 300ms (50th percentile)
- Checkout process: < 1000ms (50th percentile)
- Error rate: < 1%
- Success rate: > 99%
METRICS TO MONITOR:
- Response times (min, max, median, 95th percentile)
- Requests per second (RPS)
- Failure rate
- Current users
- Response time distribution
"""