Random User Agent Simulation in Locust

  • Share this:

Code introduction


This code defines a Locust simulation user that randomly selects a user agent header and visits a website.


Technology Stack : Locust

Code Type : The type of code

Code Difficulty :


                
                    
def random_user_agent():
    import random
    import locust
    from locust import HttpUser, task, between

    class WebsiteUser(HttpUser):
        wait_time = between(1, 5)

        @task
        def load_homepage(self):
            self.client.get("/")

        @task
        def random_user_agent_header(self):
            user_agents = [
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15",
                "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0"
            ]
            user_agent = random.choice(user_agents)
            self.client.get("/", headers={"User-Agent": user_agent})

    if __name__ == "__main__":
        locust.main(["locust", "-f", __file__])                
              
Tags: