Simulating User Actions with Locust

  • Share this:

Code introduction


This code defines a user behavior based on the Locust library, simulating random actions of a user on a website, including accessing random resources, submitting forms, browsing products, searching for products, and logging in and out.


Technology Stack : The code uses the Locust library and its features such as tasks, between, FastHttpUser, get, post, click_link, and login/logout.

Code Type : The type of code

Code Difficulty :


                
                    
def random_user_behavior(user):
    from locust import task, between
    from locust.contrib.fasthttp import FastHttpUser

    @task
    def perform_action(self):
        self.client.get("/random_resource", name="Random Resource")
        wait_time = between(1, 5)
        self.client.post("/submit_form", data={"input": "data"}, name="Submit Form")

    @task
    def browse_products(self):
        self.client.get("/products", name="Browse Products")
        self.client.click_link(text="Product Details", link_text="Product Details")

    @task
    def search_for_product(self):
        self.client.get("/search", name="Search for Product")
        self.client.post("/search", data={"query": "laptop"})

    def setup(self):
        self.client.get("/login", name="Login")
        self.client.post("/login", data={"username": "user", "password": "pass"})

    def teardown(self):
        self.client.get("/logout", name="Logout")