Generated Token every 10 mins and use it during load test

Hi @Sreenivas

The recommendations in Periodically refreshing a token aside a script - #3 by codebien are valid for your case. Are you finding it difficult to introduce in your script?

I’ve tried to get the script from your initial message but it’s not easy. I had to replace characters (probably from the copy&paste if you are using Windows?), and some of the syntax is still not correct. It would help if you can provide a working script within block codes like below, but simplified and working, so I can reproduce your code:

import { group } from 'k6';
import { check, sleep } from 'k6';
import http from 'k6 / http';
import { htmlReport } from 'K6 Load Test: <%= title %>';
import { textSummary } from 'https://jslib.k6.io/k6-summary/0.0.1/index.js'
import { SharedArray } from 'k6 / data';
import papaparse from 'https://jslib.k6.io/papaparse/5.1.1/index.js';
import encoding from 'k6 / encoding';
import { findBetween } from 'https://jslib.k6.io/k6-utils/1.2.0/index.js';

export const options = {
    scenarios: {
        setup: { // some arbitrary scenario name for genarate token
            executor: 'per- vu - iterations',
            vus: 1,
            //duration: '1s',
            iterations: 2,
            gracefulStop: '0s', // do not wait for iterations to finish in the end
            tags: { test_type: 'setup' }, // extra tags for the metrics generated by this scenario
            exec: 'setup', // the function this scenario will execute
        },
        scenario1: { // some arbitrary scenario name
            executor: 'constant- vus',
            //executor: 'per-vu-iterations',
            vus: 15,
            duration: '60m',
            //iterations: 10,
            gracefulStop: '0s', // do not wait for iterations to finish in the end
            tags: { test_type: 'scenario1' }, // extra tags for the metrics generated by this scenario
            exec: 'scenario1', // the function this scenario will execute
        },
        scenario2: { // some arbitrary scenario name
            executor: 'constant- vus',
            //executor: 'per-vu-iterations',
            vus: 15,
            duration: '60m',
            //iterations: 10,
            gracefulStop: '0s', // do not wait for iterations to finish in the end
            tags: { test_type: 'scenario2' }, // extra tags for the metrics generated by this scenario
            exec: 'scenario2', // the function this scenario will execute
        },

    },
    discardResponseBodies: false,
    thresholds: {
        // we can set different thresholds for the different scenarios because
        // of the extra metric tags we set!
        'http_req_duration{ test_type: api }': ['p(95) < 250', 'p(99) < 350'],
        'http_req_duration{ test_type: website }': ['p(99) < 500'],
        http_req_duration: [{
            threshold: 'p(90) < 500',
            threshold: 'p(95) < 900',
            abortOnFail: false,
        }]

        // we can reference the scenario names as well
        //'http_req_duration{scenario:my_api_test_2}': ['p(99)<300'],

    }

};

export function setup() { //genarating token here

    var url1 = 'token genaration url';

    const payload1 = {
        [“client_id”]: “13246546”,
        [“client_secret”]:“466464646”,

    }
    const params1 = {
        headers: {
            'Content - Type': 'application / x - www - form - urlencoded',
            'Accept': 'application / json',
        },

        tags: {
            name: 'Oauth', // first request
        },

    };

    var Response1 = http.post(url1, payload1, params1, check);

    // console.log(Response1.body);
    // console.log(Response1.status);
    // console.log(Response1);

    check(url1, {
        'is Auth ': (r) => Response1.status === 200,

    });

    let securityToken = findBetween(Response1.body, '“token”:“', '”,');

    return { securityToken };
    //sleep(3600);

}

export default function (data) {
    //console.log((data.securityToken));
    let authToken = data.json('access_token');
    let securityToken = findBetween(Response1.body, '“token”:“', '”,');
    let refreshToken = findBetween(Response1.body, '“token”:“', '”,');
    console.log(refreshToken);

}

export function scenario1(data) {

    var url = '';
    const payload = '';

    const params = {
        headers: {
            'Content - Type': 'application / json',
            'token': 'bearer token' // using here

        },

        tags: {
            name: '231', // first request
        },

    };

    //console.log(payload);
    const Response = http.post(url, payload, params, check);
    //console.log(Response.body);
    //console.log(Response.status);
    //console.log(globalThis.vars [“vuAuthToken”]);
    check(url, {
        '123456': (r) => Response.status === 200,
    });
    sleep(0.8)
}

var refreshed = 0;

export function scenario2(data) {
    var diff = new Date() - refreshed
    if (diff > 4999) {
        console.log(refresh the token)
        refreshed = new Date()
    }
    var url = 'scenario2';
    const payload = ``;

    const params = {
        headers: {
            'Content - Type': 'application / json',
            'Authorization': Bearer token, // token using here
        },

        tags: {
            name: '1313gdgd', // first request
        },

    };

    //console.log(payload);
    const Response = http.post(url, payload, params, check);
    // console.log(Response.body);
    // console.log(Response.status);
    console.log(data.securityToken);

    check(url, {
        '134654': (r) => Response.status === 200,
    });
    sleep(0.8)
}

Also a bit more context will help. I’m not familiar with the system you’re testing and interacting with. It would be really tricky to give you a satisfying answer without getting more information from you.

I see that you are creating the initial token in the setup() function which is also an scenario? You might want to have a look at the test lifecycle. This will share the token with all VUs, but after 10 minutes each VU will generate a new token. Will that work for your system?

You also have a mix of scenarios and the default() function. I would initially simplify that, work on the token refresh and then reintroduce the complexity. Once your token refresh strategy is working.

To summarize, it will help if you provide more context about your system and what you want to achieve, and to provide a simplified test that we can execute, so we can suggest a concrete alternative.

Cheers!