K6 - 遍历数组,但不针对每个 VU

  • 本文关键字:VU 遍历 数组 K6 k6
  • 更新时间 :
  • 英文 :


我正在编写一个脚本来使用 k6 测试我的基础设施。

我希望将每个 VU 分配给从现有数组获得的先前已知id,并且 VU 在创建 VU 时仅执行一次来自default函数的指令。

如何遍历这个数组,获取id并将其用于脚本创建的每个VU?

最初的想法是低沉的,但我确信这是不正确的。

export let options = {
stages: [
{ duration: '10s', target: 1 },
{ duration: '10s', target: 10 },
],
};
const ids = [
{'id':1, 'name':'name1'},
{'id':3, 'name':'name3'},
{'id':4, 'name':'name4'},
{'id':18, 'name':'name18'}];
export default function () {
for(var i=0; i<ids.length; i++) {
var user = ids[i];
//do something with user.id
}
}

根据 K6 手册,每个 VU 都将执行default函数内的所有内容,但它会使所有 VU 执行 for 循环,这不是我想要的行为。

我希望 VU 执行 for 内部的内容,但为每个新 VU 使用不同的 id。像波纹管这样的东西:

export default function () {
var user = ids[i];
//do something with user.id
}

从k6版本0.34开始,这个问题有一个解决方案。

import exec from "k6/execution";
import { SharedArray } from "k6/data";
import http from "k6/http";

const data = new SharedArray("my dataset", function(){
const ids = [
{'id':1, 'name':'name1'},
{'id':3, 'name':'name3'},
{'id':4, 'name':'name4'},
{'id':18, 'name':'name18'}
];
return ids;
})
export const options = {
scenarios :{
"use-all-the-data": {
executor: "shared-iterations",
vus: data.length,
iterations: data.length,
maxDuration: "30s"
}
}
}
export default function() {
// this is unique even in the cloud
var item = data[exec.scenario.iterationInTest];
http.post("https://httpbin.test.k6.io/anything?endpoint=amazing", item)
console.log(JSON.stringify(item))
}

我最终使用以下组合来解决此特定场景...scenarios:-)和全局变量__VU.

在场景配置中,我说每个 VU 在所有测试期间只会迭代 1 次,我将启动与ids数组中一样多的 VU。这样,每个 VU 将使用其中一个 ID 并仅运行 1 次default函数。

由于__VU从 1 开始,所以我还必须使用__VU-1来正确索引数组。

const ids = [
{'id':1, 'name':'name1'},
{'id':3, 'name':'name3'},
{'id':4, 'name':'name4'},
{'id':18, 'name':'name18'}];
export let options = {
scenarios: {
stress_test: {
executor: 'per-vu-iterations',
vus: ids.length,
iterations: 1
}
}
};
export default function () {
var user = ids[__VU-1];
//do something with user.id
}

最新更新