【问题标题】:K6 - iterate over array, but not for each VUK6 - 遍历数组,但不是针对每个 VU
【发布时间】:2021-06-17 20:01:05
【问题描述】:

我正在编写一个脚本来使用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


    【解决方案1】:

    从 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))
    }
    

    【讨论】:

      【解决方案2】:

      我最终使用...scenarios :-) 和全局变量 __VU 的组合来解决这个特定场景。

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

      因为 __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
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-19
        • 1970-01-01
        • 1970-01-01
        • 2020-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-19
        相关资源
        最近更新 更多