SAI CHANDRA SAI CHANDRA - 6 months ago 10
JSON Question

Script Assertion to get token and set it as http header to the next test step

How to write a script(assertion) in order to get the

randomAccessToken
as output from the given code.The code is in json format.

{
"status": "Success",
"code": 1000,
"message": "Random access token generated",
"randomAccessToken": "ef12286f-3263-4c3b-949a-3a43497254e2-20162124112138-1722093936686484240"
}


UPDATE from comment:

I need the header name as "randomAccesstoken" but for the next TestStep because to run that I need this info.

Answer

Have grrovy script assertion and paste the below code.

import groovy.json.JsonSlurper 
def jsponresponse = messageExchange.responseContent
def jsonSlurper = new JsonSlurper()
jsonParsed = jsonSlurper.parseText(jsponresponse)
actualValue = jsonParsed.randomAccessToken
log.info actualValue

assert 12 < actualValue.length

//here you need to use groovy regx or string length grater than as assert i used srting length

Hope this helps!! dont forget to click answered.. if it didn't work provide your finding we solve.

Now the refined script assertion would do ,store the randomacesskey in to a property ,that can be used in next HTTP REQUEST headers

import groovy.json.JsonSlurper 
def jsponresponse = messageExchange.responseContent
def jsonSlurper = new JsonSlurper()
jsonParsed = jsonSlurper.parseText(jsponresponse)
actualValue = jsonParsed.randomAccessToken
log.info actualValue    
assert 12 < actualValue.length
context.testCase.testSteps["requestProps"].setPropertyValue( "Tokenkey", actualValue )

what does it mean? the new line

context.testCase.testSteps["requestProps"].setPropertyValue( "Tokenkey", actualValue )

In order the above line to get execute , you need to add testStep properties and rename it as "requestProps" and add a entry "Tokenkey"

by the time the script assertion excuted successfully , script have extracted and stored randomAccessToken value in to Tokenkey refernce , for cross reference open properties step after the execution of first request successfully and you see a value that got extracted from randomAccessToken i.e., you see this after executing the firt request,

requestProps
Tokenkey = yettqutt-ajsfugau-uyatwdua

Now in the another any request of the same test case which requires this extracted Randomaccess token in header section ? How to do that ?

open that httpRequest -->headers--> add an entry that server accepts

if in your case server accepts name of the randomaccess key is "access-key"

then an add entry

access-key = ${requestProps#Tokenkey}

now fire the second or 3rd nth request you have set this header parameter in the request it will go through.