Gatling - 用 session 实现关联传递 token 值

Gatling - 用 session 实现关联传递 token 值_第1张图片
图片发自App

项目中的某个接口必须先登录后调用,但是 header 中的Authorization 需要在登录返回的token中添加一个字串,所以需要先获得 token 并修改后传递给该接口的请求。

虽然这是常见的关联的问题,但是由于刚开始研究gatling, 苦于中文相关文档有限,看了官方文档,也是有些茫然,尝试了不同的方法后,终于看到请求成功了。

package advisorApp

import io.gatling.core.Predef._

import io.gatling.http.Predef._

import scala.concurrent.duration._

class application extends Simulation {

val httpConf = http

.baseURL("https://xxxx.xxxx") // Here is the root for all relative URLs

.acceptHeader("application/json, text/plain, */*") // Here are the common headers

.acceptLanguageHeader("zh-CN,zh;q=0.9,en;q=0.8")

.acceptEncodingHeader("gzip, deflate, br")

.userAgentHeader("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36")

val headers_10 = Map("Content-Type" -> "application/json") // Note the headers specific to a given request

val scn = scenario("SigningAdvisor")

.exec(http("login")

.post("/advisor-auth/api/auth/xxxx/_actions/loginOrRegisterUser") //test data

.headers(headers_10)

.body(StringBody("""{ "phone": "177xxxxxxxx","verificationCode":"7777"}""")).asJSON

.check(status.is(200))

.check(jsonPath("$..userId").saveAs("userId"))

.check(jsonPath("$..token").exists)

.check(jsonPath("$..token").saveAs("token"))

)

// 取出 token 值并修改

.exec(session => {

val token = session("token").as[String]

val token2 = "Bearer " + token

session.set("token",token2)

})

// 打印 session 验证正确性

.exec { session => println(session)

session

}

.exec(http("advisorSigning")

.post("/bms-advisor/api/advisors")

.headers(headers_10)

.header("Authorization","${token}")

.body(StringBody("""{"userId": "5a5d9d1f30c49e0008c1c913",

"advisorPhone": "xxxxxx", //  test data

"emailAddress": "[email protected]",

"advisorName": "xxxx", //test data

"idCardNumber": "xxxxxxx", //test data

"nation": "Han",

"highestDegree": "doctor",

"politicalStatus": "ptgm",

"provinceCompanyId": "59f422cdb2b14f0008a1166d"}""")).asJSON)

setUp(scn.inject(atOnceUsers(1)).protocols(httpConf))

}

打印出的session 结果:

Session(SigningAdvisor,1,Map(gatling.http.cache.dns -> io.gatling.http.resolver.ShuffleJdkNameResolver@54fba1c8, userId -> 5a5daee230c49e0008c1c915, token -> Bearer eyJhbGciOiJIUzI1NiJ9.eyJwcmluY2lwYWwiOiI1YTVkYWVlMjMwYzQ5ZTAwMDhjMWM5MTUiLCJkYXRhIjoiMzI5MDQyNDQtZTUwZC00ZmExLWIyMWYtY2MxNjM3ZTZlOGI3IiwiZXhwIjoxNTE2Njk2MDc3fQ.yJsKzVk1wkT4j6Ygdua4jpoxq1V3zzXZ8hDuk3EI4Pw),1516091277053,151,OK,List(),io.gatling.core.protocol.ProtocolComponentsRegistry$$Lambda$409/115086468@687d0e8a)

你可能感兴趣的:(Gatling - 用 session 实现关联传递 token 值)