Lukas Cardot
Lukas Cardot

Reputation: 205

How to share variables between feature runs in Karate?

I have an application that creates a token once by using karate.callSingle() in my karate-config file.

This token however expires after some time, so I might need to recreate it after some tests.

My plan would be to set the time of creation in a variable that can be shared in subsequent iterations of the karate-config file, so that I can recreate the token if the time difference is big enough.

Is there a way in Karate in which I can set a variable in the karate-config that can be shared in subsequent iterations ?

Upvotes: 1

Views: 2895

Answers (2)

Lukas Cardot
Lukas Cardot

Reputation: 205

In the end I followed Peter Thomas' advice and used Java by "caching" properties between features. Here's my implementation :

var tokenRefreshTimeInMinutes = 5;
var myToken = {};
var KarateCache = Java.type('KarateCache');
var lastRefreshTime = KarateCache.get('lastRefreshTime');

if (!lastRefreshTime || differenceInMinutes(new Date(lastRefreshTime), new Date()) >= tokenRefreshTimeInMinutes) {
    myToken = karate.call('theFileRefreshingTheToken');
    KarateCache.add('lastRefreshTime', new Date().toUTCString());
    KarateCache.add('myToken', JSON.stringify(myToken));
} else {
    myToken = JSON.parse(KarateCache.get('myToken'));
}

with this simple KarateCache Java class

private static final Map<String, String> KARATE_CACHE = new ConcurrentHashMap<>();

public static void add(String key, String value) {
    KARATE_CACHE.put(key, value);
}

public static String get(String key) {
    return KARATE_CACHE.get(key);
}

Upvotes: 2

Alex D
Alex D

Reputation: 410

Are you storing the result of callSingle() to a variable? Like:

var tokenResult = karate.callSingle('createToken.feature', config);

If you save the expiration time to a variable expirationTime inside createToken.feature, you can access it in karate-config.js as tokenResult.expirationTime.

Upvotes: 1

Related Questions