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

GitHub Actions中Locust监听器无法获取environment参数报错求助

Locust quitting listener throws TypeError in GitHub Actions (missing environment argument)

问题原因

你的监听器函数定义在logger类内部作为普通方法,但Locust触发quitting事件时会直接调用该方法,而Python类的普通方法会自动将类/实例作为第一个参数(self)传入,导致参数不匹配——方法期望接收environment,但实际收到的是类对象,进而抛出missing required positional argument: 'environment'错误。

另外你的代码还有两个逻辑错误:

  • fail_ratio是0-1的小数(代表百分比),你写的>25永远不会成立,应该改为>0.25
  • avg_response_time的判断值写的是>5,但注释说明是50ms,应该改为>50

解决方案

有两种修复方式:

方案1:将监听器改为全局函数

直接把监听器函数移出类,作为全局作用域的函数:

import logging
from locust import events

@events.quitting.add_listener
def check_test_results(environment):
    # 修正fail_ratio判断值为0.25(25%)
    if environment.stats.total.fail_ratio > 0.25:
        logging.error("Test failed due to failure ratio > 25%")
        environment.process_exit_code = 1
    # 修正avg_response_time判断值为50ms
    elif environment.stats.total.avg_response_time > 50:
        logging.error("Test failed due to average response time > 50 ms")
        environment.process_exit_code = 1
    else:
        environment.process_exit_code = 0

方案2:将类方法改为静态方法

如果需要保留类结构,给方法添加@staticmethod装饰器,避免Python自动传入self参数:

import logging
from locust import events

class Logger:
    @staticmethod
    @events.quitting.add_listener
    def check_test_results(environment):
        if environment.stats.total.fail_ratio > 0.25:
            logging.error("Test failed due to failure ratio > 25%")
            environment.process_exit_code = 1
        elif environment.stats.total.avg_response_time > 50:
            logging.error("Test failed due to average response time > 50 ms")
            environment.process_exit_code = 1
        else:
            environment.process_exit_code = 0

额外检查

确保GitHub Actions中使用的Locust版本与本地一致,版本差异可能导致事件参数传递逻辑变化。你可以在GitHub Actions的运行步骤中指定Locust版本,比如:

- name: Install dependencies
  run: pip install locust==<你的本地版本号>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:23:19