4

我有一个requests基于 python 的 API 测试套件,可以自动重试每个请求,响应为 408 或 5xx。我正在考虑在 k6 中重新实现其中的一些以进行负载测试。是否k6支持重试 http 请求?

4

2 回答 2

10

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;)

于 2019-08-05T05:12:04.850 回答
2

您可以创建一个可重用的重试函数并将其放入一个模块中,以便由您的测试脚本导入。

该功能可以是通用的:

  • 期望函数重试
  • 期望一个谓词从失败的调用中辨别成功
  • 重试上限
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));
于 2021-08-12T15:42:17.230 回答