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

Viewed 3471

Please consider the follow code:

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]

When I execute the code above with just one user, the method Task2.Method never gets executed, only the method from Task1.

What can I do to make sure the code from both tasks gets executed for the same user?

I would like to do it this way because I want to separate the tasks into different files for better organizing the project. If that is not possible, how can I have tasks defined into different files in an way that I can have tasks defined for each od my application modules?

2 Answers

I think I got it. To solve the problem I had to add a method at the end of each taskset to stop the execution of the task set:

  def stop(self):
    self.interrupt()

In addition to that, I had to change the inherited class to SequentialTaskSet so all tasks get executed in order.

This is the full code:

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]

Everything seems to be working fine now.

At first I thought this was a bug, but it is actually just as intended (although I dont really understand WHY it was implemented that way)

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

I would solve this issue with inheritance: Define a base TaskSet or User class that has the common tasks, and then subclass it, adding the user-type-specific tasks/code.

If you define a base User class, remember to set abstract = True if you dont want Locust to run that user as well.

Related