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

GitLab CI中运行Locust测试时用户未实际生成的问题排查

问题分析与解决方案

1. 修正类级代码执行时机错误

你把print(f"\nLOAD CLASS")直接写在SocialLoad类定义中,这部分代码会在类加载阶段执行,而非测试运行时。GitLab CI环境下类加载可能早于测试启动,导致打印滞后,且无法反映实际测试执行状态。

将调试代码移到实例方法内(比如on_start),确保测试运行时触发:

class SocialLoad(TaskSet):
    def on_start(self):
        print(f"\n[User Start] LOAD CLASS initialized")
        self.login()

2. 修复login方法的语法错误

你的login方法定义缺少self参数:

# 错误写法
def login():
    print(f"\nUSER AUTH")
    ...

这会导致on_start调用self.login()时抛出异常(GitLab CI可能未显示完整报错),直接中断用户初始化流程,测试自然无法执行。修正为:

# 正确写法
def login(self):
    print(f"\n[Auth] Starting login for user")
    # 后续登录逻辑代码

3. 明确Locust启动参数

当前--autoquit 0会让测试结束后立即退出,若测试未正常启动会直接终止。同时需明确指定用户数和孵化率,匹配你的10个邮箱需求:

locust -H https://host -f locustfile.py,scenario.py --autostart --autoquit 30 --users 10 --spawn-rate 0.5 --html locust_report.html
  • --users 10:对应你的10个测试用户
  • --spawn-rate 0.5:每2秒生成1个用户,刚好20秒完成全部孵化
  • --autoquit 30:测试结束后等待30秒再退出,确保报告生成完成

4. 确保邮箱分配的唯一性与线程安全

直接使用全局列表分配邮箱可能存在并发竞争,导致多个用户拿到同一邮箱或取空。改用Queue实现线程安全的邮箱分配:

from queue import Queue

# 初始化邮箱队列
USER_EMAILS = Queue()
for email in ["user1@test.com", "user2@test.com", ...]:  # 替换为你的邮箱列表
    USER_EMAILS.put(email)

class SocialLoad(TaskSet):
    def on_start(self):
        # 每个用户启动时从队列取唯一邮箱
        self.current_email = USER_EMAILS.get()
        print(f"\n[User Init] Using email: {self.current_email}")
        self.login()

5. 开启完整日志排查隐藏错误

GitLab CI默认可能截断部分日志,添加set -x开启命令调试,查看完整执行流程:

script:
  - set -x
  - locust -H https://host -f locustfile.py,scenario.py --autostart --autoquit 30 --users 10 --spawn-rate 0.5 --html locust_report.html

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:10:34