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

Locust中LoadTest调用子类方法出现AttributeError的困惑

问题原因分析及解决办法

这不是Locust的Bug,是你的代码设计问题。

核心原因是Locust实例化了父类LoadTest本身,而非你定义的子类TeacherProcess/StudentProcess。Locust会自动扫描所有继承自User的类,并将它们当作可运行的用户类创建实例。如果你的LoadTest类直接继承自User,但自身没有实现_generate_post_data方法,那么Locust启动后就会创建LoadTest的实例,调用post_request任务时自然会触发AttributeError。

至于压测统计显示无失败请求,大概率是因为子类的请求正常执行,而父类实例在尝试执行任务时直接报错退出,没有产生有效请求,所以统计里没计入失败数据,但日志会记录这个错误。

解决步骤

  • 将LoadTest改为抽象基类:用Python的abc模块标记_generate_post_data为抽象方法,确保父类无法被实例化。示例代码:

    from abc import ABC, abstractmethod
    from locust import User, task
    
    class LoadTest(User, ABC):
        @task
        def post_request(self):
            data = self._generate_post_data()
            # 发送请求的逻辑
    
        @abstractmethod
        def _generate_post_data(self):
            pass
    
    class TeacherProcess(LoadTest):
        def _generate_post_data(self):
            return {"teacher_key": "value"}
    
    class StudentProcess(LoadTest):
        def _generate_post_data(self):
            return {"student_key": "value"}
    
  • 检查Locust运行配置:启动Locust时确保指定的是子类TeacherProcess/StudentProcess,而非父类LoadTest。比如命令行不要用--class-prefix LoadTest这类参数,让Locust自动扫描子类即可。

  • 调整类继承结构:如果不想用抽象基类,也可以让LoadTest不直接继承User,仅作为普通基类,让子类同时继承User和LoadTest(不过更推荐抽象基类的方式,代码规范度更高)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:05:19