Random Page Visit Tasks with Locust

  • Share this:

Code introduction


This code defines a custom function named random_task that uses the Locust library to generate random page visit tasks. It creates a TaskSet class containing a task called random_page, which randomly selects a page from a predefined list of pages to visit. Then, it uses Locust's runner to execute these tasks.


Technology Stack : Locust, TaskSet, task, random, get

Code Type : Locust task generator

Code Difficulty : Intermediate


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

    class WebsiteTasks(TaskSet):
        @task
        def random_page(self):
            page = choice(["home", "about", "contact", "services"])
            self.client.get(f"/{page}")

    def run_locust():
        from locust import runner
        runner.run(locust=WebsiteTasks)

    run_locust()