Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท Concepts and Scripts

Test Data and Environment Variables

Feed realistic data into k6 tests with open(), SharedArray and CSV parsing, pick data per VU and iteration, read environment variables with __ENV, and avoid memory blowups.

A load test that sends the same request with the same user a million times is not realistic: caches serve every call, and the database is never exercised. Real traffic involves many users, products and search terms. This lesson shows how to get data into a k6 script (files, generated values), how to share it efficiently between VUs, how to pick a different record per VU or iteration, and how to configure a run with environment variables.

Environment variables with __ENV

The built-in __ENV object holds the environment variables of the process, plus any set with -e on the command line.

Terminal
k6 run -e BASE_URL=https://staging.example.com -e USERS=50 script.js
JavaScript
const BASE_URL = __ENV.BASE_URL || 'http://localhost:3000';
const USERS = Number(__ENV.USERS || 10);

Values are always strings, so convert numbers with Number() and booleans yourself (__ENV.DEBUG === 'true'). Use __ENV for anything that differs between environments or runs: the base URL, credentials, load level. Never commit secrets in the script; pass them through the environment or a CI secret store.

Reading a file with open()

open(path) reads a file during the init stage and returns its text (add 'b' as the second argument for binary data). Paths are relative to the script file.

JavaScript
const raw = open('./users.json');
const users = JSON.parse(raw);

The function exists only in init code. Calling it inside default fails.

SharedArray: one copy for all VUs

Remember that init code runs once per VU. With 500 VUs, the snippet above keeps 500 copies of the parsed array. SharedArray solves this: it runs the loader function once, then shares the result read-only between all VUs.

JavaScript
import { SharedArray } from 'k6/data';

const users = new SharedArray('users', function () {
  return JSON.parse(open('./users.json'));
});

export default function () {
  const user = users[Math.floor(Math.random() * users.length)];
  // ...
}

The first argument is a unique name; the second is the loader. Behaves like an ordinary array for reading (length, index, map), but you cannot modify it. It is the recommended way to load JSON data. For CSV, parse it inside the loader (for example with the papaparse library, which k6 can import from a URL or a local copy), or split lines by hand:

JavaScript
const rows = new SharedArray('products', () =>
  open('./products.csv').trim().split('\n').slice(1).map((line) => {
    const [sku, price] = line.split(',');
    return { sku, price: Number(price) };
  }));

Choosing a record: random, per VU, per iteration

How you pick data changes the test:

JavaScript
// 1. Random: simple and realistic for read traffic
const a = users[Math.floor(Math.random() * users.length)];

// 2. One fixed record per VU: each VU "is" a user for the whole test
const b = users[(__VU - 1) % users.length];

// 3. Sequential across all iterations of one VU
const c = users[(__VU * 1000 + __ITER) % users.length];

// 4. Unique across the whole test (inside a scenario)
import exec from 'k6/execution';
const d = users[exec.scenario.iterationInTest % users.length];

Choose per VU when each virtual user needs a stable identity (a logged-in session), and per iteration when each run should use a new record (creating unique orders). If users must never repeat and the list is shorter than the number of iterations, make the list longer; a modulo that wraps around causes duplicates, which can trigger "already exists" errors that are really test-data bugs.

Generating data in the script

Sometimes you want values that are unique without a file:

JavaScript
const email = `user-${__VU}-${__ITER}-${Date.now()}@example.test`;

A user id built from __VU and __ITER is unique within a test, and adding Date.now() (or a run id from __ENV) keeps it unique across runs when the system under test keeps old data. The k6-utils helper library offers randomString, randomIntBetween, randomItem and uuidv4 for this; import it from a pinned URL or a local copy.

A stand-in for data selection

The program below is not k6. It mimics the selection strategies above with a plain array and counts how often each user would be used, so you can see the difference between random choice and per-VU choice. The random part uses a seeded generator, so the output is the same on every run.

Node.js Stand-in: random versus per-VU data selection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Per-VU choice uses exactly 3 distinct users with 4 iterations each, which is what a "session per user" test wants; the random choice spreads the load unevenly.

Passing a whole configuration

For larger projects, keep profiles in one place:

JavaScript
const profiles = {
  smoke:  { vus: 1,  duration: '30s' },
  load:   { vus: 50, duration: '10m' },
  stress: { vus: 200, duration: '10m' },
};
export const options = profiles[__ENV.PROFILE || 'smoke'];

k6 run -e PROFILE=load script.js then selects the load shape without editing any file. You will build on this pattern in the Patterns and Analysis chapter.

Common mistakes

  • Reading a 100 MB file with open() in every VU (use SharedArray).
  • Assuming __ENV.VUS is a number.
  • Using Math.random() in init and expecting a different value per iteration (init runs once per VU).
  • Choosing data by __ITER alone, so every VU uses the same sequence and collides.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use SharedArray instead of JSON.parse(open('data.json')) in init code?

    Init code runs per VU. SharedArray loads once and shares the data, saving memory.
  2. 2. What type are values in __ENV?

    Environment variables are always strings, so convert with Number() or compare to 'true'.
  3. 3. Which expression gives each VU its own fixed user from a list?

    __VU is stable for a VU, so indexing by it gives each VU a fixed identity.
  4. 4. Where can open() be called?

    open() reads local files and is only available during the init stage.

Summary

  • __ENV reads environment variables (always strings); set them with -e KEY=value.
  • open() reads files in init code; SharedArray shares one read-only copy across VUs.
  • Pick data randomly, per VU, per iteration or by a unique counter depending on the test.
  • Generate unique values from __VU, __ITER and a run id.
  • Keep profiles in one object and choose with __ENV.PROFILE.

Next: Checks