karate

retry until on reusable / helper feature files


I have a feature to test a scenario, say scenario A

Feature: Testsuite

Scenario: Scenario A

    # calling a reusable helper file here
    * def getProducts = call read('../helpers/get-products.feature')

How can I use retry until on the reusable helper get-products.feature file without directly including it in the contents of the helper feature?

That is, is there some way I can achieve something like

retry call read('../helpers/get-products.feature') until response.status == "Complete."

Solution

  • Yes this can be done although the retry logic would need to live in a javascript function instead of using karate retry until.

    First you would need to create a function that will handle the retry logic along with calling the feature file ex. retryFeature.js. This function will take 2 params, first for the path to the feature file you want to call and perform the retry on, second param is for the number of time you want to retry

        function retryFeatureCall(featurePath, maxAttempts) {
        var attempts = 0;
        var result;
        while (attempts < maxAttempts) {
            result = karate.call(featurePath);
            if (result.responseStatus == 200) {
                return result;
            }
            attempts++;
            karate.log('Retry attempt:', attempts);
        }
        throw new Error('Max retry attempts reached');
    }
    

    Now you can use this function in your main feature to attempt however many retries against your called feature. The below will attempt calling the feature 5 seperate times, only exiting when you get a 200 response code.

          Scenario: Call feature with retry
           * def retryFeatureCall = read('classpath:retryFeature.js')
           * def result = retryFeatureCall('classpath:testFeature.feature', 5)
           * match result.responseStatus == 200
    

    Also you could technically remove the logic in the function that limits the number of retries but not sure how you would exit the method if it doesn't end up ever completing.

    If you need more time between retry attempts you could add a thread.sleep to the function.

    The exit condition does not have to be on the responseStatus, it can be any condition from the response itself.