I want to store an id in a setup section, what I got when I upload a file for an endpoint, and after that, I need to get back the uploaded element in the default section multiple times. I tried to use a helper function with a setter and getter but it gave back undefined in the default function. Is there any easy way to store a number between the setup function and the default?
Asked
Active
Viewed 595 times
1 Answers
1
Yes, that is possible and it is documented and explained in Test Life Cycle – Setup and Teardown Stages.
The setup
function can return an object, which is then passed to each VU's default function as the first parameter:
import http from 'k6/http';
export function setup() {
const res = http.get('https://httpbin.test.k6.io/get');
return { data: res.json() };
}
export function teardown(data) {
console.log(JSON.stringify(data));
}
export default function (data) {
console.log(JSON.stringify(data));
}
There are some restrictions regarding the data types you can pass between setup and default or teardown, but you mentioned it being a number which should be no problem. Basically anything is supported, as long as it can be serialized to and from JSON.
For your use-case it would probably look like this:
import http from 'k6/http';
const file = open('./path/to/file', 'b');
export function setup() {
const uploadData = {
fileUploadFieldName: http.file(file, 'yourfilename'),
};
const res = http.post('https://example.com/upload', uploadData);
return { documentId: res.json('document.id') };
}
export default function (data) {
const res = http.get(http.url`https://example.com/documents/${data.documentId}`);
// ...
}

knittl
- 246,190
- 53
- 318
- 364