简体   繁体   English

如何在空手道的功能运行之间共享变量?

[英]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.我有一个应用程序通过在我的karate-config文件中使用karate.callSingle()创建一次令牌。

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.我的计划是在一个变量中设置创建时间,该变量可以在karate-config文件的后续迭代中共享,以便在时间差足够大时重新创建令牌。

Is there a way in Karate in which I can set a variable in the karate-config that can be shared in subsequent iterations ?在空手道中有没有一种方法可以在karate-config中设置一个可以在后续迭代中共享的变量?

In the end I followed Peter Thomas' advice and used Java by "caching" properties between features.最后,我遵循了 Peter Thomas 的建议,并通过“缓存”特性之间的属性来使用 Java。 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使用这个简单的 KarateCache Java 类

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);
}

Are you storing the result of callSingle() to a variable?您是否将callSingle()的结果存储到变量中? 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 .如果到期时间保存到变量expirationTimecreateToken.feature ,您可以访问它karate-config.jstokenResult.expirationTime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM