简体   繁体   中英

extract a value of token from a script groovy

I test a request REST from soapui and I receive one response Json that contains one token (userToken) :

{
   "status": 200,
   "entity":    {
      "status": "SUCCESS",
      "message":       {
         "defaultMsg": "Successfully logged in.",
         "msgId": "controller.authorization.success.log.in"
      },
      "data":       {
         "userToken": "b57796e3-d9e4-49f2-9d46-481a2048ab65",
         "userName": "operateur",
         "userId": "operateur",
        }
}

I add this assertion in soapui for extracting the value of userToken and put it as a variable of the project:

import com.eviware.soapui.support.XmlHolder
import net.sf.*
import net.sf.json.*
import net.sf.json.groovy.*

//def ResponseMessage = testRunner.testCase.testSteps["Recuperation Jeton"].testRequest.response.contentAsString
def ResponseMessage = messageExchange.response.contentAsString
log.info("OAUTH TOCKEN :"+ResponseMessage)
def object = new JsonSlurper().parseText(ResponseMessage)
log.info ("userToken :"+object.data.userToken)



messageExchange.modelItem.testStep.testCase.testSuite.project.setPropertyValue( "X-AUTH-TOKEN",object.data.userToken) 

but it doesn't work...Can you give me your advices please ?

Thanks in Advance,

Best Regards,

There are several issues with your code. Firstly, you miss proper import for JsonSlurper - groovy.json.JsonSlurper . Secondly, your path to userToken property is not correct - you miss entity in the beginning. Your script should look more or less like that:

import groovy.json.JsonSlurper

def json = messageExchange.response.contentAsString
def root = new JsonSlurper().parseText(json)

log.info ("userToken: " + root.entity.data.userToken)

messageExchange.modelItem.testStep.testCase.testSuite.project.setPropertyValue("X-AUTH-TOKEN", root.entity.data.userToken)

It appears that Script Assertion is being used for the REST Request test step .

  • In order to get the response, you could simple use context.response .

    log.info context.response

  • In order to set property at project level, use context.testCase.testSuite.project.setPropertyValue('NAME', 'VALUE')

Over all script for Script Assertion would be:

//check if there is response
assert context.response, 'Response is empty or null'

def json = new groovy.json.JsonSlurper().parseText(context.response)
def token = json.data.userToken

//check if there is token
assert token, 'token is empty or null'
log.info token

//Set value at project level property
context.testCase.testSuite.project.setPropertyValue('X-AUTH-TOKEN', token)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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