You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Locust.io中setup、teardown未执行及测试流程的技术咨询

Why Your TaskSet's 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 the Locust/HttpLocust class, run once per user instance.
  • on_start/on_stop: Belong to the TaskSet class, run when a user starts/stops executing that specific TaskSet.

内容的提问来源于stack exchange,提问作者user1641178

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:34:06