Locust User Generator for Simulating Web Interactions

  • Share this:

Code introduction


This code defines a user generator based on the Locust library, used to simulate users visiting the homepage and performing random attempts. It uses the User class, task decorators, event handling, and random number generation from the Locust library.


Technology Stack : Locust library, User class, task decorator, event handling, random number generation

Code Type : The type of code

Code Difficulty :


                
                    
def random_user_generator(user_id, max_attempts=5):
    from locust import Locust, task, events
    from random import randint
    from time import sleep

    class User(Locust):
        task_set = TaskSet(visit_home_page, make_random_attempt)

        def on_start(self):
            self.attempts = 0

        @task
        def visit_home_page(self):
            print(f"User {user_id} is visiting the home page.")

        @task
        def make_random_attempt(self):
            self.attempts += 1
            if self.attempts <= max_attempts:
                print(f"User {user_id} is making an attempt {self.attempts}.")
                sleep(randint(1, 3))  # Simulate a random wait time
            else:
                print(f"User {user_id} has exceeded the maximum number of attempts.")

    events.user_start.add_callback(User.on_start)