Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double auth with requests

I'm using Locust (which uses Requests) to do page load tests. The page has a popup requesting username and password to access the page and there is a standard login page.

I'm using the client.auth to authenticate the first time (on the popup) to open the page and send data on the POST request to login the account.

The problem is that Locust never displays a failure, even when I skip the second authentication. In other words, if I do the client.auth authentication I can GET any page (even the ones for which authentication is needed, and I skip the second authentication) and Locust does not display a 401 error. So I'm doing something wrong here.

Here is the code that I'm using:

class UserBehavior(TaskSet):
def on_start(self):
    self.login()

def login(self):
    # Set basic auth credentials
    if BASIC_AUTH_CREDENTIALS:
        self.client.auth = BASIC_AUTH_CREDENTIALS

    headers = {
        'referer': 'http://myreferer.com'
    }
    data = {
        'username': 'John',
        'password': 'Doe',
        'csrfmiddlewaretoken': '123456712345671234567'
    }

    r = self.client.post('/login', data=data, headers=headers)

@task
def progress(self):
    self.client.get("/needed/authorization")

What I want is to measure the time it takes a page to load when a number of users try to load it. I have a couple of pages that I measure this on, one that loads fast the other much slower, but the test displays the same values for both. I think that Locust's simulated users get redirected to the login page every time and therefor they have the same response time and don't report a 401 or 404, or any error for that matter.

Please help me do this properly.

like image 235
Vedran Avatar asked Aug 15 '26 15:08

Vedran


1 Answers

For testing the login required pages you should send loged-in user's info (cookie) in the header.

class UserBehavior(TaskSet):

cookie = ""

def on_start(self):
    self.cookie = self.get_user_cookie()

def get_user_cookie(self):
    # Set basic auth credentials
    if BASIC_AUTH_CREDENTIALS:
        self.client.auth = BASIC_AUTH_CREDENTIALS

    headers = {
        'referer': 'http://myreferer.com'
    }
    data = {
        'username': 'John',
        'password': 'Doe',
        'csrfmiddlewaretoken': '123456712345671234567'
    }

    r = self.client.post('/login', data=data, headers=headers)
    if r.status_code == 200:
        return r.request.headers['Cookie']
    else:
        print "User cannot login"

@task
def progress(self):
    self.client.get("/needed/authorization", headers = {"Cookie": self.cookie})
like image 182
Mesut GUNES Avatar answered Aug 18 '26 06:08

Mesut GUNES



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!