Need a way to pass variables from User class to a TaskSet in Locust

Viewed 1401

I'm new to locust and I'm trying to write load tests. The purpose of my Locust Users would be to create an Item by calling a createItem API. In this scenario the item_id in each request should be unique as it has a unique criteria.

This is what I've done.

import json
from random import randint

from locust import HttpUser, constant, SequentialTaskSet, task

from flow.helper import read_json


class WebsiteUser(HttpUser):
    """
    User class that does requests to the locust web server running on localhost
    """
    host = "http://localhost:8080/api/"
    wait_time = constant(3)

    @task
    class SequenceOfTasks(SequentialTaskSet):
        item_id = randint(100, 9999)

        @task
        def create_item(self):
            request = read_json('resources/create_item.json')
            request['item-id'] = self.item_id
            response = self.client.post('createItem', json.dumps(request),
                                        headers={'Content-Type': 'application/json'})
            assert response.status_code == 200

The first request is a success and it creates an entry successfully. But all the later requests fail and in the application server's logs I can see that it is trying to create items with the same item_id. Is there any way i can dynamically generate a value in the WebsiteUser class and pass it to the SequenceOfTasks?

1 Answers

Not an exact answer to the question but i got this code working without having conflicting item_ids by shifting the random logic inside the method. Something like:-

@task
    class SequenceOfTasks(SequentialTaskSet):
        self.item_id = None
        @task
        def create_item(self):
            request = read_json('resources/create_item.json')
            self.item_id = randint(100, 9999)
            request['item-id'] = self.item_id
            ...
Related