Search code examples
pythonhttppython-requestsloadlocust

Locustio (Python) login


I want to make some load tests on the website. First of all, that's my code:

from locust import HttpLocust, TaskSet, task

class UserBehavior(TaskSet):
def on_start(self):
    """ on_start is called when a Locust start before any task is scheduled """
    self.login()

def login(self):
    post_data = {'username':'my_login', 'password':'my_pass', 'Login':'Login'}
    with self.client.post('/sign_in', post_data, catch_response=True) as response:
        if 'cookie' not in response.cookies:
            response.failure('login failed')
@task(2)
def index(self):
    self.client.get("/admin")

@task(1)
def profile(self):
    self.client.get("/profile")

class WebsiteUser(HttpLocust):
    task_set = UserBehavior
    min_wait = 5000
    max_wait = 9000

I am running locust with: locust --host=https://my_host.

Always I am receiving 405 err Error report:

11 POST /sign_in: "CatchResponseError('login failed',)"

Can someone please explain to me how to make sure I am logged in and how to do this with locust? I am a little confused because I've also tried to make things work with tokens etc., and still the same.


Solution

  • Some "silly" things you may need to try, depending on how your API is working, are the following:

    1. Try append a trailing slash(/) to your endpoint e.g. '/sign_in/' instead of '/sign_in'.
    2. For some reason, I get an error when I use http in my host variable, but it works fine when I use https. You might want to try this out too.
    3. Make sure you did not forget version in your endpoint if you have one. For example, 'https://my_host/v1/sign_in/'.

    As for logging in with a token, below code works fine for me:

    from locust import HttpLocust, TaskSet, task
    import json
    
    
    class UserBehavior(TaskSet):
    
        def __init__(self, parent):
           super(UserBehavior, self).__init__(parent)
    
           self.token = ""
           self.headers = {}
    
       def on_start(self):
          self.token = self.login()
    
          self.headers = {'Authorization': 'Token ' + self.token}
    
      def login(self):
          response = self.client.post("/sign_in/", data={'username':'my_login', 'password':'my_pass', 'Login':'Login'})
    
        return json.loads(response._content)['key']
    
     @task(2)
     def index(self):
         self.client.get("/admin/", headers=self.headers)
    
     @task(1)
     def profile(self):
         self.client.get("/profile/", headers=self.headers)
    
    class WebsiteUser(HttpLocust):
        task_set = UserBehavior
        min_wait = 5000
        max_wait = 9000
    

    In my case calling sign_in, returns a key which I then use as a token for my requests. Hope this helps, I am pretty new to Locust as well.