温馨提示×

Postman在CentOS上如何使用脚本

小樊
41
2026-01-03 23:20:09
栏目: 智能运维

在 CentOS 上使用 Postman 的脚本方式

CentOS 上,Postman 的“脚本”主要有两类:一类是在 Postman 应用内的 Pre-request ScriptTests(JavaScript),另一类是在服务器上用 Newman 执行集合的命令行脚本(Shell/Bash)。前者用于单接口调试与断言,后者用于批量、定时与 CI/CD 自动化。下面给出可直接复用的步骤与示例。


一 环境准备

  • 安装 Postman(图形界面)
    • 下载 Linux 版压缩包并解压到 /optsudo tar -xzf Postman-linux-x64-*.tar.gz -C /opt
    • 建立软链便于启动:sudo ln -s /opt/Postman/Postman /usr/bin/postman
    • 启动:postman
  • 安装 Newman(命令行运行器)
    • 安装 Node.js 与 npm:sudo yum install -y nodejs npm
    • 全局安装 Newman:sudo npm install -g newman
  • 准备集合与环境
    • 在 Postman 中创建 Collection,按需添加 Environment,并导出为 collection.jsonenvironment.json,用于后续命令行运行。

二 在 Postman 应用内使用脚本

  • Pre-request Script(请求前)
    • 动态设置时间戳请求头:
      pm.environment.set("timestampHeader", new Date().toISOString())
      
    • 在请求 Headers 中使用变量:{{timestampHeader}}
  • Tests(请求后)
    • 状态码断言:
      pm.test("Status code is 200", () => {
        pm.response.to.have.status(200);
      });
      
    • 响应体包含指定字符串:
      pm.test("Body matches string", () => {
        pm.expect(pm.response.text()).to.include("成功");
      });
      
  • 变量与数据驱动
    • 使用环境与全局变量:pm.environment.set("api_key", "your_api_key"),在 URL/Header/Body 中以 {{api_key}} 引用
    • 数据驱动:在 Runner 中选择 CSV/JSON 数据文件,结合迭代数据进行批量测试。

三 使用 Newman 在 CentOS 上运行脚本

  • 基本运行
    • 运行集合与环境:
      newman run collection.json -e environment.json
      
  • 生成报告(示例:HTML)
    • 安装 Newman HTML 报告器:sudo npm install -g newman-reporter-html
    • 运行并输出报告:
      newman run collection.json -e environment.json -r html --reporter-html-export report.html
      
  • Shell 自动化脚本
    • 示例脚本 run_postman.sh:
      #!/usr/bin/env bash
      set -e
      COLLECTION="/path/to/collection.json"
      ENVIRONMENT="/path/to/environment.json"
      REPORT="/path/to/report.html"
      
      newman run "$COLLECTION" -e "$ENVIRONMENT" -r html --reporter-html-export "$REPORT"
      
    • 赋权并运行:
      chmod +x run_postman.sh
      ./run_postman.sh
      
  • 作为 systemd 服务定时/后台执行(可选)
    • 新建服务文件 /etc/systemd/system/postman.service
      [Unit]
      Description=Newman Postman Collection Runner
      After=network.target
      
      [Service]
      ExecStart=/usr/local/bin/newman run /path/to/collection.json -e /path/to/environment.json -r html --reporter-html-export /path/to/report.html
      Restart=always
      User=your_username
      
      [Install]
      WantedBy=multi-user.target
      
    • 启用与启动:
      sudo systemctl daemon-reload
      sudo systemctl enable --now postman.service
      sudo systemctl status postman.service
      
    以上步骤覆盖 Newman 的安装、运行、报告与自动化集成,适合在 CentOS 服务器上做批量与持续化执行。

四 常见问题与实用建议

  • 无头环境运行:Newman 可在 无图形界面 的 CentOS 服务器上直接执行,适合 CI/CD 与定时任务。
  • 变量优先级:集合变量 < 环境变量 < 数据文件(迭代数据),在脚本中用 pm.environment.get/setpm.iterationData.get 明确取值来源。
  • 报告与归档:结合 HTML/JSON 报告与 git/制品库做历史留存与对比分析。
  • 依赖与版本:保持 Node.js/npmNewman 为较新稳定版本,避免插件兼容性问题。

0