Postman /纽曼在失败时重试

yhuiod9q  于 2022-11-07  发布在  Postman
关注(0)|答案(4)|浏览(331)

在纽曼中,我希望测试以确保响应代码是正确的,响应时间是合理的,响应值是正确的。
在某些情况下,由于网络故障或其他系统状况,某些请求可能会以超时或不正确的值结束,如果在几秒钟后处理同一请求,这些问题将得到解决。
在这种情况下,我希望在请求之间的超时时间为Y的情况下重试x次完全相同的请求。
如果一个迭代在重试后通过,我希望纽曼退出代码为0(成功运行)。

i7uq4tfw

i7uq4tfw1#

您可以按如下方式设置请求工作流:
创建一个带有请求的集合,然后:
在预请求选项卡中,您可以实现计数器:

// Counter for number of requests
var counter = environment.counter ? _.parseInt(environment.counter) + 1 : 1;
postman.setEnvironmentVariable("counter", counter);

您的测试选项卡如下所示:

const code = (responseCode.code === 200);

if (code === 200 && environment.counter < X) {
    // Stop execution
    tests["Status code is 200"] = code;
    postman.setNextRequest();
}
else {
    // retry the same request
    postman.setNextRequest("Name of this request");
}

可以使用纽曼CLI配置请求本身的超时:

newman run myCollection.json --timeout-request Y
vsaztqbk

vsaztqbk2#

下面是我在收集预请求脚本中定义的retry函数,它只在通过收集执行测试时起作用:

Utils = {
        wait: function (that, sleepDuration){
            that.setTimeout(() => {}, sleepDuration);
        },
        withRetry: function(that, expectedHttpStatus, maxNumberOfTries, sleepBetweenTries, businessRetryConditionCallBack, endRetryCallback){

            if (!that.pm.environment.get("collection_tries")) {
                that.pm.environment.set("collection_tries", 1);
            }

            if (((that.pm.response.code != expectedHttpStatus) || businessRetryConditionCallBack())
                && (that.pm.environment.get("collection_tries") <= maxNumberOfTries)) {
                var tries = parseInt(that.pm.environment.get("collection_tries"), 10);
                that.pm.environment.set("collection_tries", tries + 1);
                Utils.wait(that, sleepBetweenTries, maxNumberOfTries);
                that.postman.setNextRequest(that.request.name);
            } else {
                if(businessRetryConditionCallBack()){
                    // On ne passe pas à la requête suivante
                    that.postman.setNextRequest(null);
                }

                that.pm.environment.unset("collection_tries");

                endRetryCallback();
            } 
        }
    };

下面是如何在请求预请求或测试脚本中使用它:

var expectedHttpStatus = 200;
    var maxNumberOfTries = 5;
    var sleepBetweenTries = 5000;

    Utils.withRetry(this, expectedHttpStatus, maxNumberOfTries, sleepBetweenTries, function(){
        // Retry business condition callback
        return pm.response.json().length <= 0;
    }, function(){
        // End retry callback
        pm.test("Has one result", function () {
            pm.expect(pm.response.json().length).to.equals(0);
        });
    });

只要(http状态与expectedHttpStatus不同或businessRetryConditionCallBack为真)且未到达maxNumberOfTries,则此代码将重试请求。
当http statut condition为true且到达maxNumberOfTries时,将执行检查以验证businessRetryConditionCallBack。如果不为true,则停止执行收集。

csbfibhn

csbfibhn3#

下面是相同的可重用函数

postmanFunctions.common.retryOnFailure(predicate,retryCount,waitbetweenRetrySec,ReroutetorequestifNeeded ,postmanAssertions);
  • predicate 函数决定成败
  • Assert函数具有所有postmanAssert
  • 如果“重新路由”为空,则在重试尝试之后执行Assert。
  • 具有重试计数和等待时间的灵活轮询(如果 predicate 通过,则不再轮询/回流)
  • 有一个最大流计数器(env var),它限制流跳转的数量,以避免无限循环

将以下函数存储在Globals或env中:

() => {
    var sleep = (sleepDuration) => {
        var startTime = new Date().getTime();
        while (new Date().getTime() - startTime < sleepDuration) {}
    }
    var sleepByAsyncDelayTime = () => {
        var sleepDuration = postman.getEnvironmentVariable('asyncDelayTime') || 0;
        sleep(sleepDuration);
    }
    var retryOnFailure = (predicate, numberOfRetrys, sleepDuration, reRouteRequestName, postmanAssertions) => {
        var retryCountPerReq_key = request.name + '_retry_count';
        var retryCountPerReq = pm.environment.get(retryCountPerReq_key) || 0;
        var reflowCountPerReq_key = request.name + '_reflow_count';
        var reflowCountPerReq = pm.environment.get(reflowCountPerReq_key) || 0;
        var totalReflowCount_key = 'totalReflowCount';
        var totalReflowCount = pm.environment.get(totalReflowCount_key) || 0;
        var maxReflowCounter = postman.getEnvironmentVariable('maxReflowCounter') || 0;
        var maxReflowCounterPerReq = postman.getEnvironmentVariable('maxReflowCounterPerReq') || 0;

        function clearAndExit() {
            pm.environment.unset(retryCountPerReq_key);
            pm.environment.unset(reflowCountPerReq_key);
            postmanAssertions();
        }

        function retry() {
            sleep(sleepDuration);
            pm.environment.set(retryCountPerReq_key, ++retryCountPerReq);
            postman.setNextRequest(request.name);
        }

        function reFlow() {
            if (totalReflowCount < maxReflowCounter && reflowCountPerReq < maxReflowCounterPerReq) {
                pm.environment.unset(retryCountPerReq_key);
                pm.environment.set(totalReflowCount_key, ++totalReflowCount);
                pm.environment.set(reflowCountPerReq_key, ++reflowCountPerReq);
                postman.setNextRequest(reRouteRequestName);
            } else clearAndExit();
        }
        if (predicate()) clearAndExit();
        else if (retryCountPerReq < numberOfRetrys) retry();
        else if (reRouteRequestName != '') reFlow();
        else clearAndExit();
    }
    return {
        common: {
            sleepByAsyncDelayTime,
            sleep,
            retryOnFailure
        }
    };
}
6za6bjd0

6za6bjd04#

几个小时后,我已经结束了这样一个函数:

function retryOnFailure(successCode, numberOfRetrys) {
        var key = request.name + '_counter';
        var execCounter = postman.getEnvironmentVariable(key) || 1;

        var sleepDuration = 1000;
        var waitUntilTime = new Date().getTime() + sleepDuration;
        if (responseCode.code !== successCode && execCounter <= numberOfRetrys) {
            while (new Date().getTime() < waitUntilTime) {
                // Do Nothing -> Wait
            }
            console.log('Retrying: ' + request.name + '\nGot: ' + responseCode.code + ' Expected: ' + successCode + '\nWaited: ' + sleepDuration / 1000 + 'sec  \nRetry Number: ' + execCounter + ' of ' + numberOfRetrys);
            execCounter++;
            postman.setEnvironmentVariable(key, execCounter);
            postman.setNextRequest(request.name);
        }
    }

用法:

retryOnFailure(404, 4);

相关问题