Search code examples
pythonlocust

Use setattr in the Locust class


I'm using Locust to load test an API. As an example, I am sending a GET request to google. My USE CASE is that I want to create the @task methods using setattr by assigning the functions dynamically to the class. This is my code

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)

As response I has that exception when start new load test browser:

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

Any help would be appreciated


Solution

  • Adding tasks in on_start is too late, as Locust will check for the existence of tasks before actually starting (and I think this is the correct behaviour, or people might end up running on_start only to have the test fail immediately after)

    Is anything stopping you from using a list, like in this example from the documentation:

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

    You can still manipulate that list from on_start, as long as it is not empty to start with.