温馨提示×

centos环境postman如何集成CI/CD

小樊
39
2025-11-23 17:18:03
栏目: 智能运维

在 CentOS 环境中将 Postman 集成到 CI/CD 的落地方案


一 方案总览与前置准备

  • CentOS 构建机或 Runner 上,使用 Newman(Postman 的命令行运行器)执行导出的 Collection JSONEnvironment JSON,通过 CLI 或 JUnit 报告Jenkins/GitLab CI 等流水线打通。
  • 前置动作:
    • 安装 Node.js 与 npm(Newman 依赖)。
    • 全局安装 Newman:npm i -g newman。
    • 在 Postman 中将测试集合与环境分别导出为 collection.jsonenvironment.json,纳入代码仓库(便于版本化管理与审计)。

二 在 CentOS 上安装与本地验证

  • 安装 Node.js 与 npm(示例):
    • 使用 NodeSource 仓库安装较新版本(以 Node.js 18 为例):
      • curl -fsSL https://rpm.nodesource.com/setup_18.x | bash -
      • yum install -y nodejs
  • 安装 Newman:npm i -g newman
  • 本地快速验证(确保集合与环境文件在工作目录):
    • newman run collection.json -e environment.json --reporters cli
  • 说明:Postman GUI 在 CentOS 桌面环境可用,但 CI 场景只需 Newman 即可完成无头执行。

三 在 CI/CD 中运行 Newman 的两种方式

  • 方式 A 使用 Newman(推荐,离线、轻量)

    • 典型命令:
      • newman run collection.json -e environment.json --reporters cli,junit --reporter-junit-export report.xml
    • Jenkinsfile 中的片段:
      • stage(‘Run Postman Tests’) { steps { sh ‘npm i -g newman’ sh ‘newman run collection.json -e environment.json --reporters cli,junit --reporter-junit-export report.xml’ } }
    • GitLab CI 中的片段:
      • test:postman: image: node:18 script: - npm i -g newman - newman run collection.json -e environment.json --reporters cli,junit --reporter-junit-export report.xml artifacts: when: always paths: - report.xml
    • 报告与质量门禁:JUnit 报告可上传为流水线产物,并用于失败判定与趋势展示。
  • 方式 B 使用 Postman CLI(云托管集合与变量)

    • 适用场景:集合与环境托管在 Postman 云端,通过 Postman API Key 在流水线中直接运行。
    • 步骤:
      • 在仓库 Settings > Secrets 中配置 POSTMAN_API_KEY
      • 在 CentOS Runner 安装 Postman CLI(Linux 64-bit 安装脚本),登录并执行集合运行:
        • curl -o- “https://dl-cli.pstmn.io/install/linux64.sh” | sh
        • postman login --with-api-key $POSTMAN_API_KEY
        • postman collection run <collection_id> --environment <environment_id>
    • 说明:该方式无需将 collection.jsonenvironment.json 纳入仓库,但需妥善管理 API Key 与云端资源权限。

四 实践要点与常见问题

  • 变量与机密管理
    • 建议将 环境/全局变量 以文件形式纳入代码库(不含机密),机密(如 API Key、数据库密码)通过 Jenkins CredentialsGitLab CI Variables 注入;Newman 可通过 -e 指定环境文件,变量在集合中以 {{变量名}} 引用。
  • 报告与质量门禁
    • 使用 JUnit 报告在 Jenkins 中发布测试结果、绘制趋势;在 GitLab CI 中将 report.xml 设为产物并配置失败阈值,实现质量门禁。
  • 稳定性与可维护性
    • 为接口依赖准备 Mock Server测试专用实例;将用例按业务域拆分为多个集合,配合 Collection Runner/文件夹 组织;在 Runner 页面可点击 Automate runs via CLI 生成适配不同平台的命令模板,减少手写命令出错概率。

0