K6 Run setup every 5 mins

Hi,

I’m trying to get the setup function which grabs my bearer token once every 5 minutes. I have the setup to run only once but the aim is to get some kind of logic in there that it will refresh the token after 5 minutes.

import http from “k6/http”;
import { Rate } from “k6/metrics”;
import { check, target, sleep, timeunit, rate, iterations, duration } from “k6”;
import encoding from “k6/encoding”;

let vuAuthToken;

const failures = new Rate(‘failed requests’);

export const options = {
stages: [
{ duration: “5s”, target: 1 },
{ duration: “10s”, target: 5 },
{ duration: “10s”, target: 0 },
],
thresholds: {
http_req_failed: [‘rate<0.01’],
http_req_duration: [‘p(95)<200’]
}
};

export function setup() {

const credentials = 'username:password';
const encodedCredentials = encoding.b64encode(credentials);

const params = {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Basic ${encodedCredentials}` 
    },
  };
  const data = {
    grant_type: 'client_credentials',
        scope: 'fhir'
  }

const result = http.post("url for token", data, params);
vuAuthToken = result.json('access_token')
return vuAuthToken

}

export default function find_pregnancies(vuAuthToken) {

const params = {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${vuAuthToken}` 
    },
  };
  const data = {
    }

const result = http.post("url for test", JSON.stringify(data), params);
console.log(result.body)
check(result, {
    "http response status is success": (r) => r.status == 200,
    "response holds data": (r) => r.body.length > 1
});
failures.add(result.status != 200);

}

Hi @dillonhood

Maybe this thread helps you: Periodically refreshing a token aside a script