API Load testing with K6 in a data-driven framework

Reading Time: 4 minutes

Hi friends

In this short blog,  we will explore how we perform load testing with different types of APIs with the help of the k6. But you may think that we already have JMeter and Gatling tools available in the market for load testing. So why do we use k6? But this k6 tool has its own advantages, in this short blog, we will also read about data-driven testing using k6. we’ll explore it later. So without much take time, let’s get started.

k6 as load testing tool

k6 was previously called load impact and is an open-source load testing tool for testing the performance of APIs, microservices, and websites also. Using k6, you can test the reliability and performance of your systems and catch performance regressions and problems earlier.

why we use k6?

It is a popular tool among developers due to its easy-to-use framework. K6 uses Go and Javascript languages in its architecture. Since Javascript is a popular language among developers known very well, It Works well in a CI workflow and  You can even generate testing scripts from Postman. collection, whereas in Gatling’s case you need to learn Scala, and learning Scala is however a high effort, So that point helps k6 make a popular tool used for load testing.

Key features

Data Driven load testing framework with K6

Basically, a data-driven testing framework is a technique in which you keep input test data separate from the actual test script. This DDT framework is totally dependent on the input test data. There are majorly two components in the data-driven testing framework. The first is the test script and the second is the test data. The test data set is created in external sources such as an excel file, CSV file, XML file, or any database After that, we connect the test script with test data to retrieve multiple sets of data to perform the application under test.

but in our case, we use a CSV file as an external source for the DDT framework. basically, it simply contains Comma-separated values.

As k6 doesn’t support parsing CSV files natively, we’ll have to resort to using a library called Papa Parse, and to import it we simply write.

import papaparse from "https://jslib.k6.io/papaparse/5.1.1/index.js";

HTTP Request

It contains multiple requests like GET, POST, PUT, etc for which takes some JSON data as its input parameters.

before that, we need to connect our script to a CSV file like this

const csvRead = new SharedArray("credentials", function() {
    return papaparse.parse(open('./data.csv'), {header: true}).data;
 // returning array

we use a demi login page API for testing and also use some email and passwords which are saved in CSV file.


    var email = csvRead[Math.floor(Math.random() * csvRead.length)]['email'];
    var password = csvRead[Math.floor(Math.random() * csvRead.length)]['password'];

    // Generate base64 encoded credentials
    var toBeEncoded = email + ':' + password;
    var encodedString = encoding.b64encode(toBeEncoded);


    let params = {
        headers : {
        "Authorization": "Basic " + encodedString,
        "X-Requested-With": "XMLHttpRequest"
        }
    };

In the above code, we use Math. floor(Math. random() method for selecting random login credentials (email, password) from CSV file, and we also use Generate base64 for representing binary data using only printable (text) characters and some parameters like Authorization type, etc.

now we move forward to the HTTP request with some checks or assertions.

let response = http.post("https://reqres.in/api/login", params);
    console.log(`Logging is using `+ email + ":" + password + ` Status: ` + response.status);
    check(response ,{
        'status is 200 all thing are fine': (r) => r.status === 200,
      }); 

Adding more virtual user(VUs) and Time duration

we can add VUs and time duration as two-way like below

  1. Through command-line
     $ k6 run --vus 10 --duration 10s (file_name.js)

2. Through Script-based

  //Test setup
export let options = {
   //virtual user
  vus: 10,  
  duration: '10s'  //time duration
};

To run the k6 test simply write in the terminal.

$ k6 run (file_name.js)

In the above image, you see the user is different at every time with status code 200 which is ok

Add the Thresholds

Basically, Thresholds are pass/fail criteria used to specify the performance expectations of the system under test and it also analyzes the performance metrics and determines the final test result (pass/fail). Thresholds are essential for load-testing automation. so let’s add some thresholds to our code.


export let options = {
  thresholds: {
    "http_req_duration": ["p(95)<1000"]
    // it means 95% of requests should be below 200ms
   },

For load testing

when we use ramp -the up concept you should ramp up the VU to a good amount and maintain it for a fixed period of time before ramping it down to 0. Have a look at the following example, which uses 100 VUs.

// Load test setup
export let options = {
  
  stages: [
      { duration: '5s', target: 50 }, // simulate ramp-up of traffic from 1 to 50 users over 5 minutes.
      { duration: '10s', target: 50 }, // stay at 50 users for 5 minutes.
      { duration: '5s', target: 0 }, // ramp-down to 0 users.
  ]
};
k6 run k6-script.js

That’s all for this blog, I Hope so you enjoyed and learned about the k6 in detail, and in the next blog, we will learn more about it, so stay tuned.

Thank you!!  

References:

https://k6.io/

knoldus

Written by 

I am a Software Consultant in knoldus software limited, I have 6 months past experience and I am a quick learner, self-motivated, and etc