【问题标题】:Pre-request script doesn't change the collection variable using Postman预请求脚本不会使用 Postman 更改集合变量
【发布时间】:2023-02-01 04:32:27
【问题描述】:

预请求脚本:

let user_id = pm.collectionVariables.get("user_id");
pm.sendRequest(`http://security.postman-breakable.com/account/${user_id}/summary`, function (err, response) {
    if(response.status == "FORBIDDEN"){
        pm.collectionVariables.set("status_code", 403);
    }else if(response.status == "OK"){
        pm.collectionVariables.set("status_code",200);
    }
});

测试:

let status_code = parseInt(pm.collectionVariables.get("status_code"));
pm.test(`Status code is ${status_code}`, function () {
    pm.response.to.have.status(status_code);
});

The response code is 200 but it reads the previous response code which was 403.

尽管我尝试在响应代码更改时通过编写预请求脚本来更改名为“status_code”的集合变量,但它并没有改变。

【问题讨论】:

  • 当您阅读状态代码时,可能 pm.sendRequest 仍未决。

标签: javascript testing postman postman-pre-request-script


【解决方案1】:

我能够重现类似的行为,你有没有机会做过这样的事情?预请求脚本在哪里调用与实际请求不同的端点?

另外,不知道它是否有帮助,在我的邮递员中,Forbidden 不是大写的

【讨论】:

  • 我再次检查,端点是相同的,在我的情况下禁止是大写的。
  • 你能分享用户ID吗?所以我可以尝试您使用的确切端点?
【解决方案2】:

我可以 100% 地复制这个。寻找解决方案把我带到了这里。

我真的认为这是一个错误:似乎预请求脚本(在 10.8.7 中)获得了发送时集合变量所处的任何状态的浅表副本,或者 pm.collectionVariables 和集合变量之间的绑定已损坏。我无法想象这种行为是故意的。

现在,我建议您将其重构为请求,并在测试中使用代码执行 pm.collectionVariables.set()

以下内容不适用于您的特定用例,但可能与在错误修复之前发现此问题的任何人相关:为了我自己的使用,我构建了一个实用程序对象,该对象具有操作集合中“清理”列表的功能变量,但更改不会持续存在。我的案例的解决方法是在调用时从测试沙箱传递 pm.collectionVariables 引用,因为该实例似乎绑定到 UI 中的集合变量。

我的收藏的预请求脚本:

utils = {
    addCleanup: (collection, route, id) => {
        const list = JSON.parse(collection.get('test_cleanup_list'));
        list.push({ route, id, id_field: `${route}id`});
        collection.set('test_cleanup_list', JSON.stringify(list));
        return list;
    }
};

然后在稍后的运行中从请求中的测试:

utils.addCleanup(pm.collectionVariables, 'account', account.id);

【讨论】:

    猜你喜欢
    • 2018-02-28
    • 2020-02-29
    • 2019-07-18
    • 1970-01-01
    • 2019-04-25
    • 2019-02-04
    • 2021-10-24
    • 2021-05-03
    • 2022-01-16
    相关资源
    最近更新 更多