My first load testing with K6
K6 is an open-source load testing tool, it is flexible to set testing situation so that the test is closer to real situation, and it provides customize metric for developer.
Test life cycle
- init: Declare global variable and import file or module.
- setup: Set up test environment and generate shared data, run before the test and only run once
- VU code: Implement test, running as many times as option setting.
- teardown: Close test environment and send webhook notification when test finish, only run once.
Let’s do it
K6 support multiple platform for example Windows/Linux /CentOs/Docker.
The example will run on Mac OS.
First, I need to install K6.
brew install k6
http.get()to call an API in default function.
The example API needs query parameter
K6 support two way to construct URL with query parameter, I will use
URLSearchParam in the example.
The API needs authorize value from cookie.
There are also two ways to set up cookies. I will use
cookieJar for setting cookie.
I will use
check to verify whether the response status is 200 or not per response.
If one of the response status is not expected, it only notes the fail record and shows the result when test complete.
The example has two customize metric, it will display with two metric type,
- Rate : calculate value of matching condition and the value is percentage and non-zero.
- Trend : calculate values with different statistics(min, max, average or percentiles).
For now, actually could run test with command, and the result will show on the terminal.
But, I try to use
Scenario feature in the example.
It allow us to make more comprehensive adjustments to VU and iteration.
One script can define multiple scenarios, and every scenario can use distinct VU and iteration configuration.
In the example, I try to use
ramping arrival rate scenario.
I only need to set configuration in option.
- executor (Required): Unique executor name. It has seven executor in official document.
- startTime (Required): The point that the scenario start to execute. The default value is 0s.
- startRate: Number of iterations execute per time unit during the test processing.
- timeUnit: In the specific time, the test should achieve target of iterations or start rate value. The value is NOT changed during test run.
- preallocatedVUs: Number of virtual users before the test run to presume the test resource.
- maxVUs: Maximum number of virtual users during the test running.
- stages: Array of the target iteration.
Last, running command
k6 run script.js on the terminal, and could check the result.
The customize metrics(error_rate, serverWaitingTime) and
check also display on the terminal.
Finally, K6 also support other result visualization.
For example, K6 cloud, Grafana, Amazon CloudWatch etc.