简体   繁体   中英

Issue with getting the response data using Locust

Im trying to see if I'm able to get the response data as I'm trying to learn how to use regex on Locust. I'm trying to reproduce my test script from JMeter using Locust. This is the part of the code that I'm having problem with.

import time,csv,json
from locust import HttpUser, task,between,tag

class ResponseGet(HttpUser):
    response_data= ""
    wait_time= between (1,1.5)
    host= "https://portal.com"
    username= "NA"
    password= "NA"

    @task
    def portal(self):
        print("Portal Task")
        response = self.client.post('/login', json={'username':'user','password':'123'})
        print(response)
        self.response_data = json.loads(response.text)
        print(response_data)     

I've tried this suggestion and I somehow can't make it work.

My idea is get response data > use regex to extract string > pass the string for the next task to use

For example: Get login response data > use regex to extract token > use the token for the next task.

Is there any better way to do this?

The way you're doing it should work, but Locust's HttpUser's client is based on Requests so if you want to access the response data as a JSON you should be able to do that with just self.response_data = response.json() . But that will only work if the response body is valid JSON. Your code will also fail if the response body is not JSON.

If your problem is in parsing the response text as JSON, it's likely that the response just isn't JSON, possibly because you're getting an error or something. You could print the response body before your attempt to load it as JSON. But your current print(response) won't do that because it will just be printing the Response object returned by Requests. You'd need to print(response.text()) instead.

As far as whether a regex would be the right solution for getting at the token returned in the response, that will depend on how exactly the response is formatted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM