我想在网站上做一些负载测试。 首先,这是我的代码:
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
我正在运行蝗虫:locust --host= https://my_host .
我总是收到 405 err 错误报告:
11 POST/sign_in: "CatchResponseError('登录失败',)"
有人可以向我解释如何确保我已登录以及如何使用 Locust 执行此操作吗? 我有点困惑,因为我也尝试过让事情与 token 等一起工作,但仍然是一样的。
最佳答案
您可能需要尝试一些“愚蠢”的事情,具体取决于您的 API 的工作方式,如下所示:
- 尝试在端点后附加一个尾部斜杠 (/),例如
'/sign_in/'
而不是'/sign_in'
。 - 出于某种原因,当我在我的主机变量中使用
http
时出现错误,但当我使用https
时它工作正常。您可能也想尝试一下。 - 确保您没有忘记端点中的版本(如果有的话)。例如,
'https://my_host/v1/sign_in/'
。
至于使用 token 登录,下面的代码对我来说工作正常:
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
在我调用 sign_in
的情况下,返回一个 key
,然后我将其用作请求的 token 。希望这会有所帮助,我也是 Locust 的新手。
关于python - Locustio(Python)登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48645831/