Locust - 如何为同一用户定义多个任务集?

Locust - How do I define multiple task sets for the same user?

请考虑以下代码:

class Task1(TaskSet):
    @task
    def task1_method(self):
        pass


class Task2(TaskSet):
    @task
    def task2_method(self):
        pass


class UserBehaviour(TaskSet):
    tasks = [Task1, Task2]


class LoggedInUser(HttpUser):
    host = "http://localhost"
    wait_time = between(1, 5)
    tasks = [UserBehaviour]

当我只用一个用户执行上面的代码时,方法 Task2.Method 永远不会被执行,只有 Task1.

中的方法

我该怎么做才能确保为同一用户执行来自两个任务的代码?

我想这样做是因为我想把任务分成不同的文件,以便更好地组织项目。如果那不可能,我如何才能将任务定义到不同的文件中,以便我可以为我的应用程序模块的每个 od 定义任务?

起初我以为这是一个错误,但它实际上是预期的(虽然我不太明白为什么它是这样实现的)

One important thing to know about TaskSets is that they will never stop executing their tasks, and hand over execution back to their parent User/TaskSet, by themselves. This has to be done by the developer by calling the TaskSet.interrupt() method.

https://docs.locust.io/en/stable/writing-a-locustfile.html#interrupting-a-taskset

我会用继承来解决这个问题:定义一个具有共同任务的基础 TaskSet 或 User class,然后子class它,添加 user-type-specific tasks/code.

如果您定义了一个基本用户 class,如果您不希望 Locust 也 运行 该用户,请记住设置 abstract = True

我想我明白了。为了解决这个问题,我不得不在每个任务集的末尾添加一个方法来停止任务集的执行:

  def stop(self):
    self.interrupt()

除此之外,我不得不将继承的 class 更改为 SequentialTaskSet,以便所有任务按顺序执行。

这是完整代码:

class Task1(SequentialTaskSet):
    @task
    def task1_method(self):
        pass
    @task
    def stop(self):
        self.interrupt()


class Task2(SequentialTaskSet):
    @task
    def task2_method(self):
        pass
    @task
    def stop(self):
        self.interrupt()


class UserBehaviour(SequentialTaskSet):
    tasks = [Task1, Task2]


class LoggedInUser(HttpUser):
    host = "http://localhost"
    wait_time = between(1, 5)
    tasks = [UserBehaviour]

现在似乎一切正常。