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        

要查看或添加评论,请登录

Jani Salomaa的更多文章

  • Lyhyt oppim??r? Semantic Kernelin saloihin

    Lyhyt oppim??r? Semantic Kernelin saloihin

    Koska taustani on Microsoft maailmassa, tutustuin Microsoftin Semantic Kerneliin tutustuessani vuosi sitten Azure AI…

  • Teko?lyt testiss? - Mistral

    Teko?lyt testiss? - Mistral

    Moni on nyt hehkuttanut Mistralin LeChat palvelua ja sen nopeutta. T?st? kiinnostuneena ajattelin testata palveluiden…

  • Miten vied? teko?lyn hy?dynt?mist? eteenp?in organisaatiossa?

    Miten vied? teko?lyn hy?dynt?mist? eteenp?in organisaatiossa?

    T?m? on kysymys, jota min? ja useampi kollega miettiv?t usein. Helppoa se ei ole! Toisaalta ei se aivan mahdotontakaan…

  • Tiedon merkitys teko?lyprojekteissa eli miten navetasta tuli s?nky

    Tiedon merkitys teko?lyprojekteissa eli miten navetasta tuli s?nky

    K?ytett?v? tieto on hyvin oleellinen asia teko?lyprojektissa. Jos tieto tai mallin opettamiseen k?ytetty tieto eiv?t…

  • Sujuva teko?lyn k?ytt??notto

    Sujuva teko?lyn k?ytt??notto

    Mit? tarkoittaa teko?lyn k?ytt??notto? T?ll? hetkell? puhutaan paljon ChatGPT:st?, CoPilotista ja muista vastaavista…

  • Teko?ly ja avoimuus

    Teko?ly ja avoimuus

    Meill? on ongelma Monet nykyiset teko?lyt / mallit pohjautuvat syv?oppimiseen, jossa mallia on opetettu suurella…

    2 条评论
  • Generatiivisen teko?lyn perusteet

    Generatiivisen teko?lyn perusteet

    Ymm?rrys on v?lill? aika pahasti koetuksella. Asiat ovat monesti monimutkaisia eik? niiden suunnattomasta…

    2 条评论
  • Cloud developer testing with K6

    Cloud developer testing with K6

    nother important aspect of the testing is to verify that your application works also after development project ends…

  • Testing

    Testing

    While building cloud native applications, it’s important to understand the meaning of testing. You should have proper…

    7 条评论
  • Windows Terminal

    Windows Terminal

    This is the second issue of Developer Tips. My monthly newsletter about different tips and ideas about cloud…

社区洞察

其他会员也浏览了