Extending K6 scripts
Now we can see what else you can do with K6 other than run performance tests. K6 uses JavaScript for creating test scripts with allows you to build different test scripts on top of it.
Creating shared logic
One of the first things while working with development, you will learn how to build components that you can reuse.
Shared.js
import { Counter } from 'k6/metrics'
export const log = (__ENV.log === 'true');
export const apiUrl = `https://localhost/example`;
const errorCount = new Counter('error_count');
export function logStatus(checkName, checkStatus, response) {
???let reason = '';
???if (!checkStatus) {
???????reason = 'Check Failed';
???????errorCount.add(1);
???} else if (log) {
???????reason = 'Log';
???}
???if (reason) {
???????console.log(`${checkName}: ${reason}`);
???????if (response.request.body) {
???????????console.log(`Request: ${JSON.stringify(response.request.body)}`);
???????}
???????console.log(`Status code: ${response.status}`);
???????if (response.body) {
???????????console.log(`Response: ${JSON.stringify(response.body)}`);
???????}
???}
};
Following logic allows us to control tests and provides shared logic to checking / logging errors. When we want to use own logic, it can be done in same way as other K6 imports.
Script reads environment variable called log and checks if it has value true and enables internal variable called log. If value of the environment variable is something else like false or doesn’t exists, it defaults to false meaning that no logging is used.
The second line defines shared apiUrl variable that can be used in other scripts as base url.
领英推荐
The third line defines custom Counter type metric https://k6.io/docs/using-k6/metrics/. It’s used to count number of errors in case where expected HTTP response status might be something else than 200 OK.
Function provides shared functionality that can be used for checking and logging errors. It helps me to test different scripts and provides information that might be useful when trying to understand, if the problem is in test or in API.
Using shared logic in your script
Example.js
import { group, check } from 'k6
import http from 'k6/http'
import { apiUrl, logStatus } from './shared.js';
export const params = {
???headers: {
???????accept: 'application/json',
???????'content-type': 'application/json'
???}
};
export const options = {
???thresholds: {
???????http_req_duration: ['p(95)<2000'],
???????'error_count': [ 'count == 0' ],
???}
};
export default function () {
???let response;
???let checkStatus;
???group('Users', () => {
???????response = http.get(apiUrl + '/users', params);
???????checkStatus = check(response, {
???????????'response code was 200': (res) => res.status == 200
???????});
???????logStatus('Users: Valid', checkStatus, response);
???});
???group('User 1', () => {
???????response = http.get(apiUrl + '/users/1', params);
???????checkStatus = check(response, {
???????????'response code was 200': (res) => res.status == 200
???????});
???????logStatus('User: Found', checkStatus, response);
???});
???group('User 0', () => {
???????response = http.get(apiUrl + '/users/0', params);
??????checkStatus = check(response, {
???????????'user not found': (res) => res.status == 404
???????});
???????logStatus('User: not found', checkStatus, response);
???});
};
Script uses variables defined in shared.js file and makes logic much easier to read.
Now we can enable logging for every request or just for failed requests.
k6 run -e log=true .\example.js
k6 run -e log=false .\example.js