Not sure I understand your whole question, but I’ll try to give an example where each VU has its own credentials, and you’re not logging in every iteration.
Say you have a JSON file users.js
(or many such files, if you parametrize like I explained here) like this:
[
{
"username": "user1",
"password": "pass1"
},
{
"username": "user2",
"password": "pass2"
},
{
"username": "user3",
"password": "pass3"
}
]
Then, you can write your k6 script like this:
import http from "k6/http";
import { sleep } from "k6";
let users = JSON.parse(open(__ENV.MY_USERS_FILE));
export let options = {
vus: users.length, // VUs stands for "virtual users", after all
duration: "10s",
};
export function setup() {
// Transform users into login requests
let loginRequests = users.map(u => ["POST", "https://httpbin.org/anything", u]);
// log in all users in parallel
let loginResponses = http.batch(loginRequests);
// this is just a demo, but maybe extract some cookies or tokens or whatever in the actual case
let loginData = loginResponses.map(r => r.json().headers['X-Amzn-Trace-Id']);
console.log(JSON.stringify(loginData, null, " "));
return loginData; // return some array with login details for each user
}
export default function (setupData) {
let vuData = setupData[__VU - 1]; // Starts from 1
console.log(`VU ${__VU} is operating with data ` + JSON.stringify(vuData));
http.get(`https://httpbin.org/anything?userdata=${vuData}`);
sleep(1);
}
And run it with k6 run --env MY_USERS_FILE=users.json zt.js
. Then, each user should only be logged in in the setup()
function and you can use their cookies/tokens/whatever in the iteration.
Or, you can use the __ITER
execution context variable (until we implement Per-VU init lifecycle function · Issue #785 · grafana/k6 · GitHub) to log in each VU only in their fist iteration, and never again, like this:
export default function () {
if (__ITER == 0) {
initVU();
}
normalVUCode();
}