Different variable value due to multiple execution of Init function

Test data locale value is different from default function locale due to multiple executions of init.
Below is the code snippet

import { check, group, sleep } from ‘k6’;
import { SharedArray } from “k6/data”;
import papaparse from ‘https://jslib.k6.io/papaparse/5.1.1/index.js’;
import { randomIntBetween } from ‘https://jslib.k6.io/k6-utils/1.1.0/index.js’;

const locale = locale_generator();

const csvProduct= new SharedArray(“Product”,function() {
console.log("TestData_locale= "+locale);
return papaparse.parse(open(‘./Test_Data/Product_choice_’+locale+‘.csv’), {header:false}).data;

});

export default function(){

group('indexPage', (_) => 
{
  console.log("Index_locale= "+locale);
  
});

}

export function locale_generator(){
let country_selector=randomIntBetween(1,4);

     switch(country_selector) {
          case 1:
              return 'en_gb';
          case 2:
              return 'fr_be';
          case 3:
              return 'fr_fr';
          default:
              return 'en_ie';
     }
}

Output:

INFO[0001] TestData_locale= en_gb source=console
execution: local
script: .\ticket.js
output: -

scenarios: (100.00%) 1 scenario, 1 max VUs, 10m30s max duration (incl. graceful stop):

  • default: 1 iterations for each of 1 VUs (maxDuration: 10m0s, gracefulStop: 30s)

INFO[0001] Index_locale= en_ie source=console

running (00m00.0s), 0/1 VUs, 1 complete and 0 interrupted iterations
default ✓ [======================================] 1 VUs 00m00.0s/10m0s 1/1 iters, 1 per VU

Hi @vish92 !

Do I get it right, and do you want that the whole test run starts to use the once randomly picked locale?

If yes, I think it’s only possible to achieve with some hacks, like see the “bad” example below:

import { randomItem } from 'https://jslib.k6.io/k6-utils/1.2.0/index.js';
import { sleep } from 'k6';

const locales = ["en_gb", "fr_fr"];

// Load everything file in the base init context
if (__VU == 0) {
   locales.forEach((file) => open("./test_data/" + file + ".json"));
}
  
const testLocale = randomItem(locales);
const testCase = open("./test_data/" + testLocale + ".json");

export function setup() {
   console.log("locale: ", testLocale)

   return JSON.parse(testCase);
}

export default function(data) {
   console.log('VU: ', __VU);

   console.log(JSON.stringify(data))
   sleep(2);
}

Let me know if that helps,
Cheers!