We all have used k6 for load testing and are used to writing scripts for it. Currently I faced a challenge of leveraging the already present Rest Assured tests and use them to automate a script for load testing.
It is not crazy as it sounds. After a bit of research, I got a hang of it. Let me take you through how to achieve it.
- First and foremost, get you tests ready and make sure they are running. 😉
- Now, I have created a repo where there is a Dockerfile that takes care of running the proxy server and running a script that starts it. The link to my GitHub repo.
- Clone the GitHub repo and navigate to the folder [k6-with-har] and run the following command:
docker build -t har-proxy .
- This will build an image and then you can run the container using following command:
- Create a directory ‘hardata’
docker run -it -p 9000:9000 -v $PWD/hardata:/opt/har-data har-proxy
- This will start the container and the proxy is listening at 9000 port.
# Its time to make changes to your code a bit.
- Configure your requests to use the proxy.
RestAssured.proxy("localhost", 9000);
RestAssured.useRelaxedHTTPSValidation();
- Run your tests, you can see the output where the above command is running.
- Once all the tests are done you can quit the command.
- The output file will be there in your created directory `hardata` as `http.har` .
# Lets now convert the .har file to k6 script.
- First download the har-to-k6 tool.
- After the installation is done, run the below command to convert it to k6 script.
har-to-k6 http.har -o loadtest.js
# Now it's time to modify the script generated by the above command.
- According to your use case you need to make changes to the code. For example: If your requests are passing any sensitive data such as tokens then you need to either remove them or change them into variable.
- Need to make sure no such sensitive data is there in the code and it is not uploaded to your repository.
- You can follow the detailed instructions given in the following blog:
# Running the Script:
- The generated script has auto-generated a “functional” test. By default, this test runs with one virtual user and for one iteration.
- You can configure the load options in many ways, As CLI arguments while running the test:
k6 run --vus 10 --duration 30s loadtest.js
- As options in the script file.
export const options = {
vus: 10,
duration: '30s',
};
- You have many different options to configure the tests, check out the Adding more VUs guide and the Options guide.
# Now finally it's time to run the load test.
k6 run loadtest.js
You can see the output on the screen while the test is running.