1- # load_test.py
21from locust import HttpUser , task , between
32import random
43
54class StudentApiUser (HttpUser ):
65 wait_time = between (1 , 2 )
6+ last_student_ids = []
7+
8+ @task (1 )
9+ def home (self ):
10+ self .client .get ("/" )
11+
12+ @task (1 )
13+ def health (self ):
14+ self .client .get ("/health" )
715
816 @task (2 )
917 def get_students (self ):
@@ -18,5 +26,27 @@ def create_student(self):
1826 "gpa" : round (random .uniform (6.0 , 10.0 ), 2 ),
1927 "email" : f"testuser{ student_id } @example.com"
2028 }
21- self .client .post ("/students" , json = payload )
29+ response = self .client .post ("/students" , json = payload )
30+ if response .status_code == 201 :
31+ # store created ID for subsequent GET/PUT/DELETE
32+ self .last_student_ids .append (response .json ()["id" ])
33+
34+ @task (1 )
35+ def get_student_by_id (self ):
36+ if self .last_student_ids :
37+ student_id = random .choice (self .last_student_ids )
38+ self .client .get (f"/students/{ student_id } " )
39+
40+ @task (1 )
41+ def update_student (self ):
42+ if self .last_student_ids :
43+ student_id = random .choice (self .last_student_ids )
44+ payload = {"gpa" : round (random .uniform (6.0 , 10.0 ), 2 )}
45+ self .client .put (f"/students/{ student_id } " , json = payload )
46+
47+ @task (1 )
48+ def delete_student (self ):
49+ if self .last_student_ids :
50+ student_id = self .last_student_ids .pop (0 ) # remove from list after deletion
51+ self .client .delete (f"/students/{ student_id } " )
2252
0 commit comments