erronius
erronius

Reputation: 49

Karate Repeat API Call

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!

Upvotes: 2

Views: 4631

Answers (2)

Raphael Bahuau
Raphael Bahuau

Reputation: 43

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

Upvotes: 1

Peter Thomas
Peter Thomas

Reputation: 58058

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

Upvotes: 4

Related Questions