【问题标题】:Use setattr in the Locust class在 Locust 类中使用 setattr
【发布时间】:2020-10-31 20:24:52
【问题描述】:

我正在使用 Locust 对 API 进行负载测试。例如,我正在向 google 发送一个 GET 请求。我的用例是我想通过将函数动态分配给类来使用 setattr 创建 @task 方法。这是我的代码

from locust import TaskSet, HttpUser, between, task

@task
def default_method(self):
    self.client.get("/")

class WebsiteTasks(TaskSet):
    def on_start(self):
        print("start process")
        setattr(self, 'index', default_method)

class WebsiteUser(HttpUser):
    host = "https://www.google.com"
    tasks = [WebsiteTasks]
    wait_time = between(1, 10)

作为响应,我在启动新的负载测试浏览器时遇到了该异常:

Exception: No tasks defined. use the @task decorator or set the tasks property of the User

任何帮助将不胜感激

【问题讨论】:

    标签: python locust


    【解决方案1】:

    在 on_start 中添加任务为时已晚,因为 Locust 会在实际开始之前检查任务是否存在(我认为这是正确的行为,或者人们可能最终运行 on_start 却导致测试立即失败)

    有什么阻止您使用列表,例如文档中的这个示例:

    def my_task(user):
        pass
    
    class MyUser(User):
        tasks = [my_task]
        ...
    

    您仍然可以从 on_start 操作该列表,只要它不为空即可。

    【讨论】:

    • 可以,以后可以修改。我这样做的地方有流程。只需至少开始一项任务,然后您就可以即时手动编辑任务。我不使用 setattr,我直接操作任务列表。
    猜你喜欢
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 2011-10-17
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多