0

在我从 Post 请求中获得令牌后,如下所示:

{ "access_token": "12345", "expires_in": 3600, "token_type": "Bearer" } 

我想在不同的 TestSteps Headers 值中使用这个标记。

例如,我必须在收到此令牌后发出 GET 请求,并且它在标头 ->Authentification : Bearer + token_value中。

那么我可以编写一个 GroovyScript 或其他东西来自动完成它吗?我正在使用 ReadyApi。

问候, 阿德里安

4

2 回答 2

1

Script Assertion在您收到上述响应的同一步骤中添加:

脚本断言 从响应中获取值并创建项目属性并设置检索到的值。

//Check if the response is empty or null
assert context.response, "Response is null or empty"
def json = new groovy.json.JsonSlurper().parseText(context.response)
def token =  "${json.token_type} ${json.access_token}" as String
log.info "Token will be: ${token}"
//Assing the value at project level property TOKEN
context.testCase.testSuite.project.setPropertyValue('TOKEN', token)

现在需要将该值动态设置为每个传出请求的标头。即,为或请求类型步骤添加Authorization标头及其值。为此,将使用功能。添加一个事件并将以下脚本添加到其中。请按照内联评论。SOAPRESTEventsSubmitListener.beforeSubmit

import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep
import com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep

//Please edit the header name as you wanted
def headerName = 'Authorization'


//a method which sets the headers
def setHttpHeaders(def headers) {
    def step = context.getProperty("wsdlRequest").testStep
    if (step instanceof RestTestRequestStep || step instanceof WsdlTestRequestStep) {
    def currentRequest = step.httpRequest
    def existingHeaders = currentRequest.requestHeaders
    headers.each {
           existingHeaders[it.key] = it.value
        }
        currentRequest.requestHeaders = existingHeaders
    } else {
      log.info 'not adding headers to the current step as it is not request type step'
    }
}

//read the token from project properties
def token = context.expand('${#Project#TOKEN}')
//assert the value of token
assert token, "Token is null or empty"

//UPDATE from the comment to add the header to next request
if (token) {
  def headerValue = [(token)]
  def headers = [(headerName) : (headerValue)]
  setHttpHeaders(headers)
}
于 2017-03-01T19:46:26.737 回答
0
 import groovy.json.JsonSlurper
import groovy.json.*

def tokens=testRunner.runStepByname("Token")
def response = context.expand( '${Token#Response}' )
def JsonSlurperjsonSlurper = newJsonSlurper()
def Objectresult = jsonSlurper.parseText(response)
def access_token= result.access_token

def authorization = "Bearer "+access_token
testRunner.testCase.setPropertyValue("access_token", authorization)
于 2017-09-15T07:13:20.800 回答