温馨提示×

Linux中Postman的脚本编写方法

小樊
46
2025-11-22 08:53:26
栏目: 智能运维

Linux中Postman脚本编写方法与自动化实践

一 环境准备与脚本入口

  • Linux 上安装 Postman:可从官网下载 Linux 64 位安装包,解压至 /opt/Postman,并创建符号链接以便命令行启动:sudo ln -s /opt/Postman/Postman /usr/local/bin/postman。完成后直接运行 postman 启动 GUI。为便于团队协作,建议使用 Snap 安装:sudo snap install postman
  • 脚本入口有两个:
    1. GUI 中每个请求的 Pre-request Script(请求前)与 Tests(请求后);
    2. 命令行通过 Newman 运行集合,实现批量与 CI/CD 自动化:npm install -g newman,随后执行 newman run collection.json -e environment.json

二 脚本类型与基本语法

  • 基本语法与内置对象:Postman 脚本运行在沙盒化的 JavaScript 环境,支持 var/let/const、条件与循环、函数与箭头函数、数组/对象操作、JSON.parse/stringifytry/catch/finallyDate、以及 正则表达式;提供 pm 对象用于变量、请求、响应与断言等操作。
  • 常用内置 API:
    • 变量作用域:pm.variablespm.environmentpm.globalspm.collectionVariables(按优先级就近覆盖);
    • 请求与响应:pm.request(如 pm.request.headers.add() 动态加头)、pm.response(如 pm.response.json()pm.response.to.have.status(200));
    • 断言:基于 Chaipm.test / pm.expect
    • 异步请求:pm.sendRequest(url, (err, res) => { ... })
    • 工作流控制:postman.setNextRequest('RequestName' | requestId | null)
    • 可视化:pm.visualizer.set(template, data)
  • 变量与动态值:在请求中通过 {{variable}} 引用变量;可使用 Postman 提供的 动态变量(如时间戳、随机值等)增强测试数据多样性。

三 常用脚本示例

  • 前置脚本:生成时间戳并设置为变量,动态添加请求头
// Pre-request Script
const ts = new Date().toISOString();
pm.variables.set("timestamp", ts);
pm.request.headers.add({
  key: "X-Request-Time",
  value: ts
});
  • 测试脚本:状态码、响应体字段、响应时间、响应头与内容断言
// Tests
pm.test("Status is 200", () => pm.response.to.have.status(200));

pm.test("Response has userId", () => {
  const json = pm.response.json();
  pm.expect(json).to.have.property("userId").that.is.a("number");
});

pm.test("Response time < 500ms", () => {
  pm.expect(pm.response.responseTime).to.be.below(500);
});

pm.test("Content-Type is application/json", () => {
  pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");
});

pm.test("Body contains success", () => {
  pm.expect(pm.response.text()).to.include("success");
});
  • 异步请求与数据传递:先请求登录接口,拿到 token 再用于后续请求
// Pre-request or Tests
pm.sendRequest({
  url: pm.environment.get("auth_url"),
  method: 'POST',
  header: { 'Content-Type': 'application/json' },
  body: { mode: 'raw', raw: JSON.stringify({ user: 'test', pwd: '123456' }) }
}, (err, res) => {
  if (err) {
    pm.test("Auth should succeed", () => { throw err; });
  } else {
    const json = res.json();
    pm.expect(json).to.have.property("token");
    pm.environment.set("auth_token", json.token);
  }
});
  • 工作流控制:按条件跳过或指定下一请求
// Tests
const code = pm.response.code;
if (code !== 200) {
  postman.setNextRequest(null); // 失败则停止
} else {
  postman.setNextRequest("GetUserInfo"); // 成功则执行指定请求
}
  • 响应可视化:将结构化数据渲染为 HTML 片段
// Tests
const data = pm.response.json();
const template = `<h3>User: {{name}}</h3><p>ID: {{id}}</p>`;
pm.visualizer.set(template, data);
  • 变量优先级与覆盖:理解“本地变量 > 迭代变量 > 环境变量 > 集合变量 > 全局变量”的覆盖顺序,避免误写与调试困难。

四 命令行自动化与CI集成

  • 导出 集合 Collection环境 EnvironmentJSON 文件(例如:collection.json、env.json)。
  • 本地运行:安装 Newman 并执行集合
npm install -g newman
newman run collection.json -e env.json --reporters cli,html,json
  • Jenkins/GitHub Actions/GitLab CI 中加入 Newman 步骤,实现每次提交或部署后的自动化回归测试;结合 HTML/JSON 报告 与阈值判断,保障接口质量与可观测性。

0