1

I am creating an animal into a database and then attempting to retrieve the animal which I have just created. However, there is a time lag ~5-10secs in the database. Therefore, a sleep wait is not suitable for this scenario as the response time varies. 

I would like to poll the message until animalId is returned in the array. It is also important that the requestId header is re-generated when the request is re-tried. 

What is the most elegant way of achieving this? 

Scenario:

    Given path '/animals'
    And header requestId = uniqueString(5)
    When method post
    Then status 200
    * def animalId = response.animalId

    Given path '/animals'
    And header requestId = uniqueString(5)
    When method get
    Then status 200


    {
        "animals": [
            {
                "animalId": "12219958",
                "reference": [
                    "12345"
                ]
            }
        ]
    }

    * def animalDetails = karate.jsonPath (response, "$.animals.[?(@.reference[0]== '" + animalId + "' )]")[0]
    * def animalId = '12345'
zwanchi101
  • 181
  • 3
  • 14

1 Answers1

0

The retry until syntax is what you are looking for: https://github.com/intuit/karate#retry-until

EDIT: regarding this requirement:

It is also important that the requestId header is re-generated when the request is re-tried.

You have to configure headers with a JavaScript function, so that it is fired for each re-try. Otherwise there is no-other option to tweak the body, please manually write a polling loop if needed (also explained in the docs).

EDIT: here is a simple example to see for yourself how the foo header is dynamic for each re-try. Paste this in a fresh Scenario and it will work.

* def counter = { value: 0 }
* configure headers = function(){ return { foo: counter.value } }
* url 'http://httpbin.org/get'
* retry until counter.value++ == 2
* method get
Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • Thanks for your answer. Are you able to provide an example of how this would look like in a feature file please? and an example of a function (if possible) Let's say that the re-generated header is a 5 digit random string. – zwanchi101 Mar 09 '20 at 15:41
  • @zwanchi101 here you go: https://github.com/intuit/karate/blob/master/karate-demo/src/test/java/demo/headers/headers.feature - and https://github.com/intuit/karate#commonly-needed-utilities – Peter Thomas Mar 09 '20 at 15:44
  • The resources you shared above have been useful. However when I use the `retry until` syntax, the function is not triggered despite `configure headers` in the Background. A unique request id is not being triggered and the previous value is being used on iteration 2 of the loop. Any ideas? – zwanchi101 Mar 09 '20 at 17:41
  • @zwanchi101 see my edit, you can see the `foo` header being sent with different values. – Peter Thomas Mar 09 '20 at 18:05