HttpUser类
HttpUser是常用的User,它添加一个client用于发出HTTP请求的属性。
from locust import HttpUser, task, between class MyUser(HttpUser): wait_time = between(5, 15) @task(4) def index(self): self.client.get("/") @task(1) def about(self): self.client.get("/about/")
它包含了所有的HTTP方法方法:
就像一样
发出POST请求,查看响应并隐式重用第二个请求获得的所有会话cookie
response = self.client.post("/login", {"username":"testuser", "password":"secret"}) print("Response status code:", response.status_code) print("Response text:", response.text) response = self.client.get("/my-profile")
验证响应
如果HTTP响应代码正常(<400),则请求被视为成功,但是对响应进行一些其他验证通常很有用。
您可以通过使用catch_response参数,带有-statement以及对response.failure()的调用来将请求标记为失败。
with self.client.get("/", catch_response=True) as response: if response.text != "Success": response.failure("Got wrong response") elif response.elapsed.total_seconds() > 0.5: response.failure("Request took too long")
也可以将请求标记为成功,即使响应代码是失败的:
with self.client.get("/does_not_exist/", catch_response=True) as response: if response.status_code == 404: response.success()
from locust.exception import RescheduleTask ... with self.client.get("/does_not_exist/", catch_response=True) as response: if response.status_code == 404: raise RescheduleTask()