Reputation: 43
I have been reading through the K6 documentation and am struggling to find a way to conform a K6 script to meet my needs. The scenario I imagine in my head:
// 1. init code
export function setup() {
// 2. setup code
// The VU would get setup here with authentication once
}
export default function (data) {
// 3. VU code
// The VU would run this code a repeated amount of times
}
export function teardown(data) {
// 4. teardown code
// The VU would be deauthed here after the VU code has ran its course
Unfortunately, from what I've read here: https://k6.io/docs/using-k6/test-life-cycle, my understanding is that the above scenario isn't possible. "setup
is called at the beginning of the test, after the init stage but before the VU stage (default function), and teardown is called at the end of a test, after the VU stage (default
function). Therefore, VU number is 0 while executing the setup
and teardown
functions." I interpret this to mean that in the above scenario, all the VU's would use the same authentication to run the VU code instead of each VU getting it's own separate authentication.
If I simply exclude the setup and teardown sections, then each VU would get new authentication on each loop:
export default function (data) {
// 3. VU code
// VU gets authenticated
// VU does a bunch of stuff
// VU clears authentication
}
Is there a way to design K6 scripts with my intention (VU Authenticates once -> VU code loop -> Deauth at the end once)?
Upvotes: 1
Views: 2467
Reputation: 1219
Yes, setup and teardown are global per the test run.
There is an issue about per VU setup/teardown, but it has not be prioritized highly as there is ... other stuff which seem more important :).
I would also like to point out that the setup, teardown and the default code are run in separate JS VMs where the only shared memory (and it is copied between them) is the data
that is returned by setup and is the first argument to default and teardown.
Currently there are two workarounds (with varying success):
if (__ITER == 0) { authenticate(); }
setup
can return an array of objects and authenticate all the VUs in the setup
code and then each VU can get their authentication (I guess it is a token of some kind) from the array using the __VU
variable which start at 1
for VUs that execute the default
function. Later on teardown
will get that same array and can deauthenticate everything. You might need to increase some ]timeouts](https://k6.io/docs/using-k6/options#setup-timeout) and/or use http.batch.Depending on how exactly you are going to authenticate and deauthenticate ... there might be an even better option :).
Upvotes: 5