Knowledgebase

Data Parameterization


Background

Scripting examples on how to parameterize data in a test script. Parameterization is typically necessary when Virtual Users(VUs) will make a POST, PUT, or PATCH request in a test. Parameterization helps to prevent server side caching from impacting your load test. This will make your test more realistic.


Data files/Parameterization

Reading parameterization data from a CSV file

As k6 doesn’t support parsing CSV files out of the box, we’ll have to resort to using a Node.js library called Papa Parse and Browserify (to make it work in k6).

There are a few of steps to make this work:

  1. Make sure you have the necessary prerequisites installed:
  2. Install the Papa Parse library:

    npm install papaparse

  3. Run it through browserify:

    browserify node_modules/papaparse/papaparse.min.js -s papaparse > papaparse.js

  4. Move the papaparse.js file to the same folder as your script file and you’ll be able to import it into your test script:

    import papaparse from "./papaparse.js"

Here’s an example using Papa Parse to parse a CSV file of username/password pairs and using that data to login to the LoadImpact test site:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
    Where contents of data.csv is:

    username,password
    admin,123
    test_user,1234
*/

import http from "k6/http";
import {check, sleep} from "k6";
import papaparse from "./papaparse.js";

// Load CSV file and parse it using Papa Parse
const csvData = papaparse.parse(open("./data.csv"), {header: true});

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
    csvData.data.forEach(userPwdPair => {
        console.log(JSON.stringify(userPwdPair));
    });

    // Pick a random username/password pair
    let randomUser = csvData.data[Math.floor(Math.random() * csvData.data.length)];
    console.log("Random user: ", JSON.stringify(randomUser));

    // Login to LoadImpact test site using the random user
    let res = http.post("https://test.loadimpact.com/login.php", {login: randomUser.username, password: randomUser.password});
    check(res, {
        "login succeeded": (r) => r.status === 200 && r.body.indexOf("successfully authorized") !== -1
    });

    sleep(1);
}

Reading parameterization data from a JSON file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
    Where contents of data.json is:
    {
        "users": [
            { username: "test", password: "qwerty" },
            { username: "test", password: "qwerty" }
        ]
    }
*/

const data = JSON.parse(open("./data.json"));

export default function() {
    let user = data.users[0];
    console.log(data.users[0].username);
}