Calmcode - locust: terminal

How to run Locust from the terminal.

1 2 3 4 5 6 7 8

The FastApi app that we end up with is listed below:

from fastapi import FastAPI
from pydantic import BaseModel
import time
import random

class Simulation(BaseModel):
    uid: str
    n_sim: int

app = FastAPI()

@app.get("/hello/")
def root():
    return {"message": "hello world"}

@app.get("/sleep/")
def root():
    time.sleep(0.1)
    return {"message": "slept!"}

@app.post("/simulate/")
def simulate(sim:Simulation):
    return {"uid": sim.uid, "result": sum([random.random() for i in range(sim.n_sim)])}

If this syntax looks unfamiliar, feel free to check out the fastapi video series.

The new user behavior definition is listed below:

import random
from locust import HttpUser, between, task, tag

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

    def on_start(self):
        self.uid = str(random.randint(0, 100_000)).zfill(6)

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

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

    @task
    def simulate(self):
        self.client.post("/simulate/", json={
            "uid": self.uid,
            "n_sim": random.randint(10, 20)
        })

To run this via the terminal in headless mode you can run;

locust -f benchmark.py --headless --host http://0.0.0.0:8000 -u 1000 -r 50

Note the use of the tags!