Data Parameterization - Retrieving unique data

Hi Team,
Referring Docs - Retrieving unique data, scenario.iterationInTest

My test data is stored in testData.json file
In my request URL I want to pass random unique set of test data in variable randomAddress

But getting error "ERRO[0000] GoError: getting scenario information outside of the VU context is not supported"
Can you please help on this
Below is script

import { SharedArray } from 'k6/data';
import { scenario } from 'k6/execution';
import http from "k6/http";
import { check, sleep } from "k6";

const data = new SharedArray('users', function () {
  const f = JSON.parse(open('./testData.json'));
  return f;
});

export const options = {
  scenarios: {
    'constant-arrival-rate': {
      executor: 'constant-arrival-rate',
      rate: `${__ENV.RATE}`,
      timeUnit: '1s',
      duration: `${__ENV.DURATION}`,
      preAllocatedVUs: `${__ENV.PREALLOCATEDVUS}`,
      gracefulStop: '1s',
    },
  },
};

const randomAddress = data[scenario.iterationInTest];

const apiKEY = `${__ENV.APIKEY}`
export default function () {
  const testURL = `https://apitest.com/${randomAddress}/test`
  const url = testURL
  const params = {
    headers: {
      "accept": "application/json",
      "X-Api-Key": apiKEY,
    },
  };

  const result = http.get(url, params);

  check(result, {
    'status was 200': (response) => {
      if (response.status !== 200) {
        console.log(response.status, response.body, url);
      }
      return response.status === 200;
    },
  });
}

2nd question : If I want to pass full request URL as ENV using different randomAddress variable value

means something like
const testURL =${__ENV.URL}

k6 run -e URL=https://apietest.com/${randomAddress}/test

what is the correct syntax to run ?

1 Like

Hi @shailendrakumaromkar, sorry for the slow reply :frowning:

You are using information about the scenario outside of the default function which is not allowed. It actually is just not possible as outside of the defautl function you are not in any scenario, you are intializing the VU. As the documentation shows the line

const randomAddress = data[scenario.iterationInTest];

Should be inside the default function or something called by it. If you want it to be set only once, you can check if it is set or not and only set it if it is not.

I am not understanding your second qustion, that seems to be the correct syntax.

Hope this helps you