28

Is it possible to have Locust pass a header command with a secure token to load test an API?

I am trying to test our api for an encoder with a header flag for a token as the server being tested has to receive a token with the request, ie.

curl -H “Authorization: Token token string” http://someserver

Liam Douglas
  • 389
  • 1
  • 3
  • 3

3 Answers3

45

Yes, you can use:

token_string = "token string"

resp = self.client.post(
            url="http://someserver",
            data=json.dumps(data),
            auth=None,
            headers={"authorization": "Token " + token_string},
            name="http://someserver",
        )
Matt Doyle
  • 867
  • 8
  • 12
20

Additionally, if you want to use same headers for every request you can also set them to the client in the on_start method. They will be automatically used with every client request.

class User(HttpUser):

    def on_start(self):
        self.client.headers = {'Authorization': 'my-auth-token'}

    @task
    def my_authenticated_task(self):
        self.client.post('enspoint')  # this will use headers we set earlier
matusko
  • 3,487
  • 3
  • 20
  • 31
1
class User(HttpUser):

    host = 'http://127.0.0.1:8000'      
    @task
    def predict_post(self):
        self.client.post("/route/", data=json.dumps({
        "text": "finish all the track to hear and great good tune u do a great job alan walker",
        "max_op_words": 10,
        "max_time": 1,
        "max_predictions": 1
        }),auth=None,
        headers={"authtoken":"your-auth-token", 'content-type': 'application/json'})

I was missing out on content-type header and was getting a 401 error authorization error.