关于Locust.io中setup、teardown未执行及测试流程的技术咨询
setup and teardown Methods Aren't Executing in Locust Let's break down why those methods aren't running, and how to fix it:
The Root Cause
Locust's TaskSet class does not natively recognize setup and teardown as lifecycle hook methods. Those methods are actually part of the parent Locust (or HttpLocust in your code) class, not the TaskSet subclass. When you define them inside a TaskSet, Locust has no built-in logic to call them during test execution.
In contrast, on_start and on_stop are valid hooks for TaskSet—they run when a user starts executing the TaskSet, and when they stop, respectively. That's why you're seeing those print statements, but not the ones from setup/teardown.
Fix Options
You have two main paths depending on what you're trying to achieve:
1. Move setup/teardown Logic to the HttpLocust Class
If you want code that runs once per test instance (when the Locust user starts/ends their entire test run), move those methods to your HttpLocust subclass:
from locust import TaskSet, HttpLocust, task class BlazeDemoTaskSet(TaskSet): def on_start(self): print("hello from taskset on_start") def on_stop(self): print("hello from taskset on_stop") @task def reserve_task(self): post_response = self.client.post("/your-endpoint", json={"key": "value"}) # Add your request logic here class BlazeDemoUser(HttpLocust): task_set = BlazeDemoTaskSet min_wait = 1000 max_wait = 3000 def setup(self): print("hello from locust setup (runs once when the user starts)") def teardown(self): print("hello from locust teardown (runs once when the user finishes)")
2. Use on_start/on_stop for Per-TaskSet Lifecycle
If your logic needs to run every time a user enters or leaves the TaskSet (for example, if you have nested TaskSets), stick with on_start and on_stop in the TaskSet—these are the intended hooks for that use case.
Key Takeaways
setup/teardown: Belong to theLocust/HttpLocustclass, run once per user instance.on_start/on_stop: Belong to theTaskSetclass, run when a user starts/stops executing that specific TaskSet.
内容的提问来源于stack exchange,提问作者user1641178

