问题
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