Linux中Postman脚本编写方法与自动化实践
一 环境准备与脚本入口
sudo ln -s /opt/Postman/Postman /usr/local/bin/postman。完成后直接运行 postman 启动 GUI。为便于团队协作,建议使用 Snap 安装:sudo snap install postman。npm install -g newman,随后执行 newman run collection.json -e environment.json。二 脚本类型与基本语法
pm.variables、pm.environment、pm.globals、pm.collectionVariables(按优先级就近覆盖);pm.request(如 pm.request.headers.add() 动态加头)、pm.response(如 pm.response.json()、pm.response.to.have.status(200));pm.sendRequest(url, (err, res) => { ... });postman.setNextRequest('RequestName' | requestId | null);pm.visualizer.set(template, data)。三 常用脚本示例
// 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