← Load Test Directory

Setting a Random User-Agent with LoadForge

Learn how to create a dynamic list of user agents and set up each LoadForge client to randomly select one.

You are now browsing the LoadForge locust test directory. You can use these tests as a starting point for your own tests, or use our AI wizard to generate one automatically.

World

Overview

Customizing headers to fit specific needs is simple with LoadForge. In this guide, we'll demonstrate how you can set up a list of user agents and let each client choose one randomly during the test. This method provides a realistic approach to load testing, simulating different user agents accessing your application.

Although our focus in this example is on user agents, the same principle can be applied to other headers, or even for randomly selecting users, paths, and more.

Creating and Setting Random User Agents

The example below demonstrates how to:

  1. Define a list of user agents.
  2. Use the on_start method to let each client pick a user agent randomly at the beginning of a test.
  3. Maintain the selected user agent for each client throughout the test duration.
import random
from locust import HttpUser, task, between

USER_AGENTS = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64; rv:88.0) Gecko/20100101 Firefox/88.0",
    "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko",
]

class QuickstartUser(HttpUser):
    wait_time = between(3, 5)

    def on_start(self):
        selected_agent = random.choice(USER_AGENTS)
        self.headers = {"User-Agent": selected_agent}
        self.client.headers = self.headers

    @task(1)
    def load_page(self):
        self.client.get("/example-url")

Enhance Your Locust Tests

Did you know? LoadForge is built on the powerful locust.io framework. This means if you're a locust user, you can directly import your scripts into LoadForge to maximize your testing capabilities. Elevate your testing experience with LoadForge!

Ready to run your test?
LoadForge is cloud-based locust.io testing.