String.split() 在空手道特征文件中返回异常

String.split() in Karate Feature File returning exceptions

我不确定如何从已创建的功能中拆分响应字符串以获得响应 header "Location" 值。

我试过的

1)

Feature: Create Tariff

  Background:
  * def result = call read('../../get-user-token.feature')
  * def serviceId = call read('create-service.feature')

  Scenario: Create Tariff
    Given url 'https://app-dev.topbox.pro/tariff-svc/api/v1/tariffs'
    And header Authorization = result.response.token_type + " " + result.response.access_token
    And request
      """
      {
      serviceTypeId: '#(serviceId.responseHeaders['Location'].split('/')[1])',
      owner: 1,
      type: 0,
      pencePerMile: '69.69',
      minMileage: '1.00',
      minCost: 5,
      zoneFrom: '',
      zoneTo: '',
      fixedCost: 0
      }
      """
    When method POST
    Then status 201

这导致了...

IntegrationTests.TestSetup.create-tariff: create-tariff.feature:10 - net.minidev.json.parser.ParseException: Unexpected token L at position 46.

2)

Feature: Create Tariff

  Background:
  * def result = call read('../../get-user-token.feature')
  * def serviceId = call read('create-service.feature').responseHeaders['Location'].split('/')[1]

  Scenario: Create Tariff
    Given url 'https://app-dev.topbox.pro/tariff-svc/api/v1/tariffs'
    And header Authorization = result.response.token_type + " " + result.response.access_token
    And request
      """
      {
      serviceTypeId: '#(serviceId)',
      owner: 1,
      type: 0,
      pencePerMile: '69.69',
      minMileage: '1.00',
      minCost: 5,
      zoneFrom: '',
      zoneTo: '',
      fixedCost: 0
      }
      """
    When method POST
    Then status 201

这导致了...

failed features: IntegrationTests.TestSetup.create-tariff: -unknown-:5 - javascript evaluation failed: read('create-service.feature').responseHeaders['Location'].split('/')1, TypeError: Cannot read property "Location" from undefined in at line number 1

注意 指定的功能 "create-service.feature" 在隔离时确实有效,并且确实产生响应 header,如下所示

您需要使用 Javascript 函数:https://github.com/intuit/karate#javascript-functions

* def greeter = function(name){ return 'hello ' + name }
* assert greeter('Bob') == 'hello Bob'

编辑:

* def service = { key : "someinfo/myServiceId"}
* def func = function(service){return service.key.split('/')[1]}
* def serviceId = func(service)
* match serviceId == "myServiceId"

我认为第一个错误是由于表达式中的单引号引起的,请尝试转义它

喜欢,

And request
"""
{
serviceTypeId: '#(serviceId.responseHeaders.Location[0].split(\'/\')[1])',
owner: 1,
type: 0,
pencePerMile: '69.69',
minMileage: '1.00',
minCost: 5,
zoneFrom: '',
zoneTo: '',
fixedCost: 0
}
"""

编辑:刚才注意到 responseHeader 中的每个值都有一个列表类型值,因此像 Location[0]

一样访问它

你的第二个方法应该是这样的,

* def serviceId = call read('create-service.feature').responseHeaders.Location[0].split('/')[1]

使用lastIndexOf代替split:

* def location = responseHeaders['Location'][0]
* def serviceId = location.substring(location.lastIndexOf('/') + 1)