温馨提示×

CentOS中Postman如何自定义脚本

小樊
32
2025-12-23 06:36:47
栏目: 智能运维

CentOS中Postman自定义脚本实用指南

一 脚本类型与执行时机

  • 在 Postman 中可编写两类自定义脚本:
    • Pre-request Script:在请求发送前执行,常用于动态生成参数、签名、请求头、URL 等。
    • Tests(Post-request):在收到响应后执行,用于断言校验、提取数据供后续请求使用。
  • 脚本运行在 Postman 的 Sandbox 环境,通过全局对象 pm 访问请求、响应、变量与断言能力。
  • 变量作用域包含:环境变量全局变量集合变量(以及请求级变量);同名时优先级通常为:请求 > 集合 > 环境 > 全局

二 编写脚本的核心语法与示例

  • 常用变量读写
    • 读取与设置环境变量:pm.environment.get("key")pm.environment.set("key", "value")
    • 读取全局/集合变量:pm.globals.get("key")pm.collectionVariables.get("key")
    • 读取响应:pm.response.text()pm.response.json()
    • 读取请求信息:pm.request.urlpm.request.headers
  • 常用断言
    • 状态码:pm.test("Status is 200", () => pm.response.to.have.status(200));
    • 响应时间:pm.test("Response < 200ms", () => pm.expect(pm.response.responseTime).to.be.below(200));
    • 响应体内容:pm.test("Body contains ok", () => pm.expect(pm.response.text()).to.include("ok"));
    • JSON 字段:pm.test("id equals 123", () => pm.expect(pm.response.json().id).to.eql(123));
  • 实用示例
    • Pre-request:动态 Authorization 头
      const token = pm.environment.get("token");
      pm.request.headers.add({ key: "Authorization", value: "Bearer " + token });
      
    • Tests:提取并传递数据
      const json = pm.response.json();
      pm.environment.set("userId", json.id);
      pm.test("Status 200", () => pm.response.to.have.status(200));
      pm.test("Has name", () => pm.expect(json.name).to.be.a("string"));
      
    • 旧式写法兼容:tests["Status code is 200"] = responseCode.code === 200;(仍可用但不推荐)。

三 在CentOS桌面版与Newman中的使用

  • 桌面版 Postman
    • 在请求或集合的 Pre-request Script / Tests 面板直接粘贴脚本;使用左下角 Console 查看 console.log 输出进行调试。
  • 无头运行与CI(Newman)
    • 安装 Node.js 与 Newman:sudo yum install -y nodejs npm 后执行 sudo npm install -g newman
    • 运行集合:newman run collection.json -e environment.json
    • 使用 Node 脚本驱动 Newman(便于自定义流程与集成):
      // run-tests.js
      const newman = require('newman');
      newman.run({
        collection: 'collection.json',
        environment: 'environment.json'
      }, function (err, summary) {
        if (err) { console.error(err); process.exit(1); }
        console.log('Collection run complete, summary:', summary.run.stats);
        process.exit(summary.run.failures.length > 0 ? 1 : 0);
      });
      // 执行:node run-tests.js
      
    • Jenkins/GitLab CI 等 CI 环境中以 Newman 步骤执行即可完成自动化回归。

四 调试技巧与常见问题

  • 调试
    • 使用 Postman Console 查看 console.log 输出;在桌面版左下角打开控制台即可。
    • 在脚本中打印关键变量与响应片段,快速定位问题。
  • 常见问题
    • 变量只能存 字符串:对象/数组请使用 JSON.stringify() 存储,读取时用 JSON.parse() 还原。
    • 作用域与优先级:同名变量按 请求 > 集合 > 环境 > 全局 取值,必要时显式指定作用域。
    • 旧语法与兼容性:tests["..."] = ... 仍可用,建议优先使用 pm.test()pm.expect() 链式断言。
    • HTTPS/证书:如遇证书校验问题,可在 Newman 中按需配置忽略校验(仅测试环境),生产环境请导入可信证书。

0