How to retry a request until i get a valid dynamically generated value in response using karate dsl

走远了吗. 提交于 2020-01-24 19:25:12

问题


I am sending a request to fetch the API ID from backend but because my backend is slow it doesn't give back the ID in one go and that's making my test case fail in the first try. Though it passes if I try again, but that's not ideally it should work. I tried putting a sleep, but that doesn't look promising either.

My test case is :

Given URL storeURL

And param query =

When method get

Then status 200

  • call read('Sleep.feature')

  • def APIIDStr = response.list[0].id

  • print 'APIID from Store is: ', APIIDStr

Can i do something here so that if APIIDStr is empty in the first go , it tries to fetch again until it gets a valid value?


回答1:


Yes. Please refer to the documentation on how to implement polling using JavaScript: https://github.com/intuit/karate#polling

function(x) {
  while (true) {
    var result = karate.call('get.feature');
    var greeting = result.response;
    karate.log('poll response', greeting);
    if (greeting.id == x) {
      karate.log('condition satisfied, exiting');
      return;
    }
    karate.log('sleeping');
    // uncomment / modify the sleep time as per your wish
    // java.lang.Thread.sleep(1000);
  }
}



回答2:


The follow code can correctly run now:

Feature:
  Background:
  * url 'url'

  Scenario:
  * def input =
  """
  {
    'form': {},
    'query': {},
  }
  """
  * path '/rest/n/test'
  * params input.query
  * form fields input.form
  * method post
  * status 200
  * math response contains { result: 1 }
  * eval if (response.result != 1) karate.call('delete-user.feature'))

So, I hope hope retryPost method which can retry-post the scenario (it can auto check status).

or:

...
* eval if (responseStatus == 5xx) retryPost/retryGet/retryPut
* eval if (response.result != 1) retryPost/retryGet/retryPut

Here retryPost/retryGet/retryPut only re-run the section code.

for example:

Feature:
  Background:
  * url 'url'

  Scenario:
  # section 1
  ...
  * method post
  * eval if () retryPost # only re-run section 1

  # section 2
  ...
  * method post
  *eval if () retryPost # only re-run section 2

Thanks a lot!



来源:https://stackoverflow.com/questions/52252789/how-to-retry-a-request-until-i-get-a-valid-dynamically-generated-value-in-respon

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