我有一个python requests
-based套件的API测试,可以用408或5xx响应自动重试每个请求。为了进行负载测试,我正在考虑在k6中重新实现其中的一些。k6
是否支持重试http请求?
发布于 2019-08-05 05:12:04
k6中没有这样的功能,但是您可以简单地通过包装k6/http函数来添加它,例如:
function httpGet(url, params) {
var res;
for (var retries = 3; retries > 0; retries--) {
res = http.get(url, params)
if (res.status != 408 && res.status < 500) {
return res;
}
}
return res;
}
然后只使用httpGet
而不是http.get
;)
发布于 2021-08-12 15:42:17
您可以创建一个可重用的重试函数,并将其放入由测试脚本导入的模块中。
这一职能可以是一般用途:
function retry(limit, fn, pred) {
while (limit--) {
let result = fn();
if (pred(result)) return result;
}
return undefined;
}
然后在调用时提供正确的参数:
retry(
3,
() => http.get('http://example.com'),
r => !(r.status == 408 || r.status >= 500));
当然,可以随意地将它封装在一个或多个特定的函数中:
function get3(url) {
return request3(() => http.get(url));
}
function request3(req) {
return retry(
3,
req,
r => !(r.status == 408 || r.status >= 500));
}
let getResponse = get3('http://example.com');
let postResponse = request3(() => http.post(
'https://httpbin.org/post',
'body',
{ headers: { 'content-type': 'text/plain' } });
奖励:您可以通过实现一个巧妙命名的函数来使调用代码更具表现力,该函数反转其结果,而不是使用否定运算符:
function when(pred) {
return x => !pred(x);
}
然后
retry(
3,
() => http.get('http://example.com'),
when(r => r.status == 408 || r.status >= 500));
或者彻底改变谓词的行为,测试失败的请求,而不是成功的请求:
function retry(fn, pred, limit) {
while (limit--) {
let result = fn();
if (!pred(result)) return result;
}
return undefined;
}
function unless(pred) {
return x => !pred(x);
}
retry(
3,
() => http.get('http://example.com'),
r => r.status == 408 || r.status >= 500);
retry(
3,
() => http.get('http://example.com'),
unless(r => r.status != 408 && r.status < 500));
https://stackoverflow.com/questions/57344334
复制相似问题