Random User Behavior Simulation with Locust

  • Share this:

Code introduction


This code defines a function named `random_user_behavior` that accepts a user instance as an argument and generates random user behaviors using the Locust library. It creates a `UserBehavior` class containing random tasks that can be clicking, scrolling, typing text, or waiting.


Technology Stack : Locust, random, choice, TaskSet, task, scroll, type, wait

Code Type : The type of code

Code Difficulty : Intermediate


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

    class UserBehavior(TaskSet):
        tasks = [random_task]

        @task
        def random_task(self):
            actions = ["click", "scroll", "type", "wait"]
            action = choice(actions)
            if action == "click":
                self.click("random_button")
            elif action == "scroll":
                self.scroll(0, 100)
            elif action == "type":
                self.type("random_text")
            elif action == "wait":
                self.wait(choice([1, 2, 3, 4, 5]))

    user.behave(UserBehavior)