Custom Locust User Class for Random Website Activities

  • Share this:

Code introduction


This function generates a custom Locust user class to simulate random user activities on a website, such as logging in, logging out, and viewing a profile. The type of user activity is determined by the parameter `activity_type`.


Technology Stack : Locust, FastHttpUser, random

Code Type : Custom Locust user class

Code Difficulty : Intermediate


                
                    
def random_user_activity(user_id, activity_type):
    from locust import Locust, events
    from locust.contrib.fasthttp import FastHttpUser
    import random

    class RandomUserActivity(FastHttpUser):
        wait_time = random.randint(1, 5)

        def on_start(self):
            self.activity_type = activity_type

        def on_stop(self):
            events.user_stop.fire(user=self)

        def task(self):
            if self.activity_type == 'login':
                self.client.post("/login", json={"user_id": user_id, "password": "password123"})
            elif self.activity_type == 'logout':
                self.client.get("/logout")
            elif self.activity_type == 'profile':
                self.client.get(f"/profile/{user_id}")

    return RandomUserActivity