pythonlocust

How to share or pass variables between multiple classes in Locust?


I am trying to write a simple performance test task using Locust. I have two sequential HTTP tasks, and if I set the variables in one class it works fine. However I want to split the tasks into two classes as shown below. I need to use the variable from the first class in another class.

How can I achieve that?

# FIRST CLASS
from locust import SequentialTaskSet

class MySeqTask1(SequentialTaskSet):

    @task
    def get_status1(self):
        r = self.client.get("/200")
        print("1. Status of 200")
        self.data = 20 # ***VARIABLE TO BE SHARED TO SECOND CLASS***
#SECOND CLASS 
from locust import SequentialTaskSet, HttpUser, constant, task,FastHttpUser
from sampleLocust import MySeqTask1
    
class MySeqTask2(SequentialTaskSet):

    @task
    def get_status3(self):
        obj = MySeqTask1(self)
        self.client.get(f"/301")
        print("3. Status of 301")
        print(obj.data) # ***USING VARIABLE FROM FIRST CLASS***

    class MyLoadTest(FastHttpUser):
       host = "https://http.cat"
       tasks = [MySeqTask1,MySeqTask2]
       wait_time = constant(1)

I am getting the following error:

Command to run the program : locust -f utils/Baseclassone.py --headless -u 1 -r 1 -t 1m

print(obj.data) # ***USING VARIABLE FROM FIRST CLASS***
AttributeError: 'MySeqTask1' object has no attribute 'data'

Solution

  • You can set your variables on the User instead of on the TaskSet. It is accessible as self.user in the TaskSet, e.g.

    self.user.data = 20