Locust provides two special methods, on_start and on_stop, to handle setup and teardown actions for individual users. These methods allow you to execute specific code when a simulated user starts or stops, making it easier to simulate real-world scenarios like login/logout or initialization tasks.
In this blog, we’ll cover,
- What
on_startandon_stopdo. - Why they are important.
- Practical examples of using these methods.
- Running and testing Locust scripts.
What Are on_start and on_stop?
on_start: This method is executed once when a new simulated user starts. It’s commonly used for tasks like logging in or setting up the environment.on_stop: This method is executed once when a simulated user stops. It’s often used for cleanup tasks like logging out.
These methods are executed only once per user during the lifecycle of a test, as opposed to tasks that are run repeatedly.
Why Use on_start and on_stop?
- Simulating Real User Behavior: Real users often start a session with an action (e.g., login) and end it with another (e.g., logout).
- Initial Setup: Some tasks require initializing data or setting up user state before performing other actions.
- Cleanup: Ensure that actions like logout are performed to leave the system in a clean state.
Examples
Basic Usage of on_start and on_stop
In this example, we just print on start and `on stop` for each user while running a task.
from locust import User, task, between, constant, constant_pacing
from datetime import datetime
class MyUser(User):
wait_time = between(1, 5)
def on_start(self):
print("on start")
def on_stop(self):
print("on stop")
@task
def print_datetime(self):
print(datetime.now())