获取令牌并将其作为授权 header 的值发送给其余步骤

Get the token and send it as value for Authorization header for the rest of the steps

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

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

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

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

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

此致, 阿德里安

在您收到上述回复的同一步骤中添加 Script Assertion

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)

现在需要将每个传出请求的值动态设置为 header。即,为 SOAPREST 请求类型步骤添加 Authorization header 及其值。为此,将使用 Events 功能。 添加一个 SubmitListener.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)
}
 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)