当多个VU时,K6提供SharedArray
用于在多个 VU(Virtual User)之间共享数据,而不是每个 VU 都有自己的独立数据。可以更容易地在不同 VUs 之间传递信息或共享状态,从而更好地模拟真实世界中的并发场景。
1、数据参数化
(1)数据来源CSV文件
k6 本身并不解析 CSV 文件,但您可以使用外部库 Papa Parse。
import papaparse from 'https://jslib.k6.io/papaparse/5.1.1/index.js';
import { SharedArray } from 'k6/data';
const csvData = new SharedArray('another data name', function () {
// Load CSV file and parse it using Papa Parse
return papaparse.parse(open('./data.csv'), { header: true }).data;
});
export default function () {
// ...
}
其中:{ header: true }
是一个参数,用于指示 CSV 解析器(在这里是 Papa Parse)首行是否包含列头(header)信息。具体作用如下:
当 { header: true }
时,表示 CSV 文件的第一行包含列头信息,解析后的数据将以对象的形式返回,对象的属性名为列头信息,属性值为对应的数据值。
[
{ "name": "Alice", "age": "25", "city": "New York" },
{ "name": "Bob", "age": "30", "city": "Los Angeles" },
{ "name": "Charlie", "age": "28", "city": "Chicago" }
]
当 { header: false }
或未指定时,CSV 文件将被解析为一个二维数组,其中每个元素代表一行数据,每行数据中的元素代表各列的数值。
name, age, city
Alice, 25, New York
Bob, 30, Los Angeles
Charlie, 28, Chicago
在这个特定的情况中,通过设置 { header: true }
,解析后的数据将以对象数组的形式返回,每个对象中的属性名对应列头信息,这样可以更容易地访问和操作 CSV 数据的各个列
在上述代码中,通过调用 Papa Parse 解析 CSV 文件后,使用 .data
来访问解析后的数据。.data
是 Papa Parse 返回对象的一个属性,它包含了解析后的 CSV 数据。
具体的例子
/* Where contents of data.csv is:
username,password
admin,123
test_user,1234
*/
import http from 'k6/http';
import { check, sleep } from 'k6';
import { SharedArray } from 'k6/data';
import papaparse from 'https://jslib.k6.io/papaparse/5.1.1/index.js';
// not using SharedArray here will mean that the code in the function call (that is what loads and
// parses the csv) will be executed per each VU which also means that there will be a complete copy
// per each VU
const csvData = new SharedArray('another data name', function () {
// Load CSV file and parse it using Papa Parse
return papaparse.parse(open('./data.csv'), { header: true }).data;
});
export default function () {
// Now you can use the CSV data in your test logic below.
// Below are some examples of how you can access the CSV data.
// Loop through all username/password pairs
for (const userPwdPair of csvData) {
console.log(JSON.stringify(userPwdPair));
}
// Pick a random username/password pair
const randomUser = csvData[Math.floor(Math.random() * csvData.length)];
console.log('Random user: ', JSON.stringify(randomUser));
const params = {
login: randomUser.username,
password: randomUser.password,
};
console.log('Random user: ', JSON.stringify(params));
const res = http.post('https://test.k6.io/login.php', params);
check(res, {
'login succeeded': (r) => r.status === 200 && r.body.indexOf('successfully authorized') !== -1,
});
sleep(1);
}
(2)数据来源Json
// data.json
{
"users": [
{ "username": "test", "password": "qwerty" },
{ "username": "test", "password": "qwerty" }
]
}
import { SharedArray } from 'k6/data';
const data = new SharedArray('some data name', function () {
return JSON.parse(open('./data.json')).users;
});
export default function () {
const user = data[0];
console.log(data[0].username);
}
2、URL查询参数的参数化
import papaparse from 'https://jslib.k6.io/papaparse/5.1.1/index.js';
import { SharedArray } from 'k6/data';
const csvData = new SharedArray('another data name', function () {
// Load CSV file and parse it using Papa Parse
return papaparse.parse(open('./data.csv'), { header: true }).data;
});
export default function () {
// Loop through all username/password pairs
for (const userPwdPair of csvData) {
console.log(JSON.stringify(userPwdPair));
}
// Pick a random username/password pair 从CSV中随机选择一对用户名或密码
const randomUser = csvData[Math.floor(Math.random() * csvData.length)];
console.log('Random user: ', JSON.stringify(randomUser));
// 请求头
var params = {
headers:{
'Authorization':token
},
};
let res = http.get(`https:xxxxxx?date1=${randomUser.a}&date2=${randomUser.b}`,params)
check(res, {
'status is 200': (r) => r.status === 200
}
)
sleep(1);
}
在 JavaScript 或 Node.js 中,用于字符串插值的正确符号是反引号(`),也称为模板字符串(Template literals)。 因此,正确的写法是使用反引号 ` 来定义字符串,并在其中使用 ${} 语法来嵌入变量,如下所示:
const baseUrl = 'https://api.example.com';
const userId = 123;
const url = `${baseUrl}/user/${userId}`;
由于我们使用了反引号,它们将被正确地解析为相应的变量值,并嵌入到 URL 字符串中。这样,URL 就可以根据 `baseUrl` 和 `userId` 动态生成了。