Locust 修改请求结果
手动控制 Locust 请求结果是成功还是失败
默认情况下,除非 HTTP 响应代码为 OK(2xx),否则请求将被标记为失败的请求。 大多数情况下,此默认值是您想要的。
但是,有时候,例如,当测试您希望返回 404 的 URL 端点或测试设计错误的系统,即使发生错误时,该系统可能返回 200 OK 时(类似于你测试某个 URL,希望他是 404 页面,那么此时如果是 404 页面,那么对你来说应该是测似乎结果成功的),这时候就需要手动控制 locust
是否应将请求视为成功或失败。
通过使用 catch_response 参数和 with 语句,即使响应代码正常,也可以将请求标记为失败:
with self.client.get("/", catch_response=True) as response:
if response.content != b"Success":
response.failure("Got wrong response")
举一反三,我们也可以将带有 200 响应码的请求标记为失败;
可以将 catch_response
参数与 with
语句一起使用,手动把 HTTP 的错误请求在统计信息中用正确作为测试报告:
with self.client.get("/does_not_exist/", catch_response=True) as response:
if response.status_code == 404:
response.success()
以阿西河为例
from locust import HttpLocust, TaskSet, task
class UserTask(TaskSet):
@task
def job(self):
with self.client.get('/', catch_response = True) as response:
if response.status_code == 200:
response.failure('Failed!')
else:
response.success()
class User(HttpLocust):
task_set = UserTask
min_wait = 1000
max_wait = 3000
host = "https://www.axihe.com"
catch_response = True
:catch_response值为布尔类型,如果设置为 True, 允许该请求被标记为失败。
通过 client.get()
方法发送请求,将整个请求的给 response
, 通过 response.status_code
得请求响应的 HTTP 状态码。
如果不为 200 则通过 response.failure('Failed!')
打印失败!
使用动态参数将对请求的分组
网站上的网址中包含动态参数是很常见的。
通常在 Locust
的统计信息中将这些 URL 分组在一起是很有意义的。
这可以通过将名称参数传递给 HttpSession
的不同请求方法来完成。
举个栗子:
# Statistics for these requests will be grouped under: /blog/?id=[id]
for i in range(10):
self.client.get("/blog?id=%i" % i, name="/blog?id=[id]")