【问题标题】:k6 script: How to parse file info to use in HTTP queryk6 脚本:如何解析文件信息以在 HTTP 查询中使用
【发布时间】:2018-08-31 19:49:42
【问题描述】:

我是 k6 的新手,也是 JS 的新手。我正在尝试从我从 DB 中的列导出的平面文件中读取列表。我想打开这个文件并遍历列表,将每个项目附加为我的 HTTP 调用的查询参数。我不知道如何继续。

例如,如果这是我的文件:

employees.txt

01111
02222
06666
04444
09999

& 这是我的 k6 脚本 (perf-employee.js)

import http from "k6/http";
import { sleep } from "k6";

export let options = {
  vus: 3,
  duration: "5s" 
};

var data = {some type of parsing her?}.open("./employees.txt");

export default function() {
  http.get("http://www.example.com/employee?employee_num={number-here}“);
  sleep(1);
};

任何关于前进方向的指导将不胜感激。

【问题讨论】:

    标签: javascript fileparsing k6


    【解决方案1】:

    open() returns 一个简单的字符串(如果使用b 标志,则为二进制),因此您可以通过使用 JavaScript 将其转换为数组(它自己的数组行中的每一行)来解析它String.split() 方法。或者,如果您想读取更复杂的数据文件,请使用 JSON 和 JSON.parse() 方法将其直接转换为 JavaScript 对象 - 请查看上面链接中的第一个示例。

    然后通过使用 k6 的 execution context variables 你可以做这样的事情:

    import http from "k6/http";
    import { sleep } from "k6";
    
    var data = open("./employees.txt").split(/\r?\n/);
    
    export let options = {
        vus: 3,
        duration: "5s"
    };
    
    
    export default function () {
        var employee = data[__ITER % data.length];
        console.log(`VU ${__VU} on iteration ${__ITER} has employee ID ${employee}...`)
        http.get(`http://www.example.com/employee?employee_num=${employee}`);
        sleep(1);
    };
    

    你应该看到类似这样的脚本输出:

    INFO[0001] VU 2 on iteration 0 has employee ID 01111... 
    INFO[0001] VU 1 on iteration 0 has employee ID 01111... 
    INFO[0001] VU 3 on iteration 0 has employee ID 01111... 
    INFO[0002] VU 2 on iteration 1 has employee ID 02222... 
    INFO[0002] VU 1 on iteration 1 has employee ID 02222... 
    INFO[0002] VU 3 on iteration 1 has employee ID 02222... 
    INFO[0003] VU 2 on iteration 2 has employee ID 06666... 
    INFO[0003] VU 3 on iteration 2 has employee ID 06666... 
    INFO[0003] VU 1 on iteration 2 has employee ID 06666... 
    INFO[0004] VU 2 on iteration 3 has employee ID 04444... 
    INFO[0004] VU 1 on iteration 3 has employee ID 04444... 
    INFO[0004] VU 3 on iteration 3 has employee ID 04444... 
    INFO[0005] VU 2 on iteration 4 has employee ID 09999... 
    INFO[0005] VU 1 on iteration 4 has employee ID 09999... 
    INFO[0005] VU 3 on iteration 4 has employee ID 09999... 
    

    【讨论】:

      猜你喜欢
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多