Simulating Random User Behaviors with Locust

  • Share this:

Code introduction


This code defines a function named `random_user_behavior` that simulates random user behaviors in a web application using the Locust library. It uses the TaskSet and task decorators from Locust to define different tasks and the between function to simulate wait times between user behaviors.


Technology Stack : The package and technology stack used in this code are [Locust].

Code Type : The type of code

Code Difficulty : Advanced


                
                    
def random_user_behavior(user):
    from locust import TaskSet, task, between
    import random

    class UserBehavior(TaskSet):
        wait_time = between(1, 5)

        @task
        def random_task(self):
            tasks = [self.task1, self.task2, self.task3, self.task4]
            task_to_run = random.choice(tasks)
            task_to_run(self)

        @task
        def task1(self):
            print("Executing Task 1: Click on Home Page")

        @task
        def task2(self):
            print("Executing Task 2: Add Item to Cart")

        @task
        def task3(self):
            print("Executing Task 3: View Cart")

        @task
        def task4(self):
            print("Executing Task 4: Checkout")

    user.user_type = UserBehavior