linux

Linux中Postman的脚本编写方法

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

Linux中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");
});
// 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"); // 成功则执行指定请求
}
// Tests
const data = pm.response.json();
const template = `<h3>User: {{name}}</h3><p>ID: {{id}}</p>`;
pm.visualizer.set(template, data);

四 命令行自动化与CI集成

npm install -g newman
newman run collection.json -e env.json --reporters cli,html,json

0
看了该问题的人还看了