温馨提示×

Postman在CentOS上如何进行自定义脚本编写

小樊
43
2025-12-15 09:33:49
栏目: 智能运维

在 CentOS 上编写 Postman 自定义脚本的两种路径

  • 使用桌面版 Postman 的Pre-request ScriptTests面板,用 JavaScript 编写请求前置逻辑与响应断言,适合本地调试与交互式开发。
  • 使用命令行工具 Newman 在服务器上批量运行集合,通过 Shell/Node.js 脚本编排执行、生成报告与集成 CI/CD,适合自动化与无人值守场景。

在桌面版 Postman 中编写脚本

  • 前置脚本 Pre-request Script:在发送请求前执行,常用于生成时间戳随机数签名、读取/设置环境变量等。
  • 测试脚本 Tests:在收到响应后执行,使用 pm.testChai.js BDD 断言语法验证状态码、响应体、响应头、耗时等。
  • 常用示例
    • 生成时间戳并设为环境变量
      const ts = Date.now();
      pm.environment.set("ts", ts);
      
    • 校验状态码与响应体
      pm.test("Status is 200", () => pm.response.to.have.status(200));
      pm.test("Body has property id", () => pm.expect(pm.response.json()).to.have.property("id"));
      
    • 校验响应时间
      pm.test("Response time < 500ms", () => pm.expect(pm.response.responseTime).to.be.below(500));
      
    • 读取环境变量并在请求中使用
      const token = pm.environment.get("auth_token");
      pm.request.headers.add({ key: "Authorization", value: `Bearer ${token}` });
      
  • 调试技巧
    • 打开控制台:View > Show Postman Console,查看 console.log 与请求/响应细节,便于定位脚本问题。

在 CentOS 服务器用 Newman 编写自动化脚本

  • 安装 Node.js 与 Newman
    sudo yum install -y nodejs npm
    sudo npm install -g newman
    node -v && npm -v && newman -v
    
  • 导出与运行
    • 在桌面版 Postman 导出集合 Collection环境 Environment(JSON)。
    • 运行集合
      newman run collection.json -e environment.json
      
  • Shell 自动化脚本示例 run_postman.sh
    #!/usr/bin/env bash
    set -e
    COLLECTION="tests/collection.json"
    ENVIRONMENT="tests/environment.json"
    REPORT_DIR="reports/$(date +%F_%H-%M-%S)"
    mkdir -p "$REPORT_DIR"
    
    newman run "$COLLECTION" \
      -e "$ENVIRONMENT" \
      --reporters cli,json,html \
      --reporter-json-export "$REPORT_DIR/result.json" \
      --reporter-html-export "$REPORT_DIR/report.html"
    
    chmod +x run_postman.sh
    ./run_postman.sh
    
  • Node.js 脚本编排示例 run-tests.js
    const newman = require('newman');
    
    newman.run({
      collection: require('./tests/collection.json'),
      environment: require('./tests/environment.json'),
      reporters: ['cli', 'json', 'html'],
      reporter: {
        json: { export: 'reports/result.json' },
        html: { export: 'reports/report.html' }
      }
    }, function (err, summary) {
      if (err) {
        console.error('Newman run failed:', err);
        process.exit(1);
      }
      console.log('Collection run complete.');
      if (summary.run.failures.length > 0) process.exit(1);
    });
    
    node run-tests.js
    
  • 作为 systemd 服务定时/常驻运行(可选)
    sudo tee /etc/systemd/system/postman-runner.service >/dev/null <<'EOF'
    [Unit]
    Description=Newman Postman Collection Runner
    After=network.target
    
    [Service]
    Type=simple
    User=your_username
    ExecStart=/usr/bin/newman run /opt/tests/collection.json -e /opt/tests/environment.json --reporters cli,json --reporter-json-export /opt/reports/result.json
    Restart=on-failure
    
    [Install]
    WantedBy=multi-user.target
    EOF
    
    sudo systemctl daemon-reload
    sudo systemctl enable --now postman-runner.service
    sudo systemctl status postman-runner.service
    
  • 集成 CI/CD
    • Jenkins/GitLab CI 等流水线中安装 Node.js 与 Newman,执行上述脚本,并根据 退出码报告 判定构建结果。

脚本编写与排错要点

  • 变量作用域与优先级:data < environment < collection < global;在脚本中用 pm.environment.set/getpm.globals.set/get 管理。
  • 时间与随机数:用 Date.now()Math.random() 生成时间戳nonce,避免缓存与重复。
  • 认证与签名:在 Pre-request 中按接口规范计算 HMAC/签名,写入 Authorization 头或请求参数。
  • 断言可读性与可维护性:使用 pm.test 描述性标题与 Chai 链式断言,必要时分组与复用。
  • 报告与留存:在 Newman 中启用 json/html 报告,归档到 reports/,便于审计与回溯。
  • 调试与网络问题:桌面版用 Postman Console 查看输出;服务器上用 newman run -v 提升日志级别;遇到 HTTPS 证书问题时,仅在受控环境下使用 –insecure 临时绕过,生产环境应导入可信证书。

0