Karate Repeat API Call

淺唱寂寞╮ 提交于 2021-01-28 01:24:05

问题


We're using Karate for backend testing of a microservice. I'd like to be able to make N calls to the backend API, where N is configurable as a number without having to do ugly things.

This was my first approach:

    Given url baseUrl
    And headers HEADERS
    When method get
    Then status 200

    Given url baseUrl
    And headers HEADERS
    When method get
    Then status 200

    Given url baseUrl
    And headers HEADERS
    When method get
    Then status 200

(Just repeating the call) It works, but obviously does not scale well (imagine 1000 of these).

Next approach was a bit better - I put the call in a separate feature and used the https://github.com/intuit/karate#data-driven-features approach:

    * table jwts
      | headers |
      | HEADERS |
      | HEADERS |
      | HEADERS |
      | HEADERS |
      | HEADERS |

    * def result = call read('call-once.feature') jwts

Slightly better but still does not scale. We also tried varieties of karate.repeat() which seems like the most natural approach, but had trouble with the syntax. None of the examples I could find had an API call inside of a for-each.

* def callFunction = function (HEADERS) { read('call-putaway-once.feature'); { HEADERS: '#(HEADERS)'} }
* def result = karate.repeat(5, callFunction)

But couldn't get any varieties of that working.

Can anyone provide an example of how to repeat the same exact Karate lines N times? I'm really looking for something like:

for (int i = 0; i < numTimes; i++) {
    Given url baseUrl
    And headers HEADERS
    When method get
    Then status 200
}

(Or functionally equivalent).

Thanks!


回答1:


Here you go. First, the second called.feature:

@ignore
Feature:

Scenario:
Given url 'http://httpbin.org'
And path 'headers'
And header X-Karate = count
When method get
Then status 200

And now you can do this in your first feature:

* def fun = function(x){ return { count: x } }
* def data = karate.repeat(5, fun)
* call read('called.feature') data

P.S. by the way search the readme for "polling", there is an example of an API call in a loop: polling.feature




回答2:


Karate almost have a feature to do this : retry until.

This feature doesn't repeat "n" time, but repeat until a condition is not validate Example here : polling.feature

For a simple request it's seems like :

Given url baseUrl
And headers HEADERS
And retry until responseStatus == 200
When method get


来源:https://stackoverflow.com/questions/56796622/karate-repeat-api-call

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!