在选通负载测试期间刷新承载令牌



如何在3小时的测试中每15分钟刷新一次gatling(用scala编写(中的承载(aouth2(令牌?

我可以获得我的代币,但在这种情况下,我不能每15分钟应用一次。

def getXYZ() = {
exec(
http("Get all xyz")
.get("/xyz/v1/abc")
)
}
val authTimeout = 20.seconds
val safetyMargin = 5.seconds
val executionTime = 2.hours
val tokenTimeout: ChainBuilder = exec(session => session.set("timeout", authTimeout.fromNow))
val printSession: ChainBuilder = exec { session => println(session)
session
}
def refreshAccessToken(): ChainBuilder = {
exec(tokenTimeout)
doIf(session => {
session("timeout").as[Deadline].timeLeft <= safetyMargin
}) {
exec(
http("Refresh Access Token")
.post(url)
.formParam("grant_type", "client_credentials")
.formParam("scope", scope)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Authorization", s"Basic $base64EncodedCredentials")
.check(jsonPath("$.access_token").find.saveAs("accessToken"))
)
.exec(printSession)
}
}
val scn = scenario("Scenario: Load Simulation With rampingUp Users")
.exec(session => {
val mytoken = session("accessToken")  // -->Trying the capture the token here
println(mytoken.as[String])
session
})
.exec(getXYZ())
.pause(5)
setUp(
scn.inject( ..... etc ...)

伪代码(Java版本,自Gatling 3.7起支持(:

// global mutable reference to a shared token
private volatile String token = null;
// first scenario refreshes the token
// must run with one single user 
ScenarioBuilder refresh = scenario("refresh")
.during(Duration.ofHours(3)).on(
exec(http("refreshToken").get(???).check(saveToken))
.exec(session ->
{
token = session.getString("token")
return token;
}
).pause(Duration.ofMinutes(15))
);

// second scenario uses the token,
// must start after the first one
ScenarioBuilder use = scenario("use")
.exec(http("useToken").get(???).header("Bearer", session -> token))

你好@Stéphane LANDELLE,

我尝试了你的伪代码解决方案,发现了一些问题:

  1. 我看不到在头方法中使用会话的方法(它只是在IntelliJ自动完成中不存在(
  2. 当我定义这样的场景时,无法确保一个令牌在另一个令牌之前执行
setUp(
refreshToken.injectOpen(
atOnceUsers(1)
).protocols(httpProtocolToken),
doWhatever.injectOpen(
rampUsers(handler.getUsers()).during(
Duration.ofSeconds(handler.getRamp()))
).protocols(httpProtocol)
)
  1. 当我将Auth标头定义为
.header("Authorization", "Bearer " + token)

使用您的第一个场景语法来刷新令牌(它是有效的,如果您在变量上放置断点,它会被更新,但是(,如果它被初始化为null,它就会保持原样,不管怎样,事实上,如果您将断点放在那里,它不会停止。我认为实现是场景是静态的,除非你在ActionBuilder中调用会话(但我不能像第1点中提到的那样这样做(

我想我已经走到了死胡同,除非我得到一些提示,谢谢。

最新更新