k6 结果校验
得益于 JavaScript 的支持,k6 可以实现非常灵活的结果校验。
先看例子:
import { check } from 'k6';
import http from 'k6/http';
export default function () {
const res = http.get('http://test.k6.io/');
check(res, {
'is status 200': (r) => r.status === 200,
'body size is 11,105 bytes': (r) => r.body.length == 11105,
});
}
结果:
$ k6 run script.js
...
✓ is status 200
✗ body size is 11,105 bytes
↳ 0% — ✓ 0 / ✗ 1
checks.........................: 50.00% ✓ 1 ✗ 1
data_received..................: 17 kB 2.3 kB/s
...
这里我定义了两个检查,一个 "is status 200",一个 "body size is 11,105 bytes"。
显然,只要 k6 通过 Response 接口暴露的数据,都可以按你的需求做检查。
对于性能测试的场景,这种已经是 functional test 级别的校验能力,可以说是杀鸡用牛刀了。
Response 对象到底暴露了什么数据,可以参考其 TypeScript 定义([https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/k6/http.d.ts#L389](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/k6/http.d.ts#L389)。 如果你用 Visual Studio Code 打开,应该能直接点击跳转到 .d.ts 文件。