在 CentOS 上编写 Postman 自定义脚本的两种路径
在桌面版 Postman 中编写脚本
const ts = Date.now();
pm.environment.set("ts", ts);
pm.test("Status is 200", () => pm.response.to.have.status(200));
pm.test("Body has property id", () => pm.expect(pm.response.json()).to.have.property("id"));
pm.test("Response time < 500ms", () => pm.expect(pm.response.responseTime).to.be.below(500));
const token = pm.environment.get("auth_token");
pm.request.headers.add({ key: "Authorization", value: `Bearer ${token}` });
在 CentOS 服务器用 Newman 编写自动化脚本
sudo yum install -y nodejs npm
sudo npm install -g newman
node -v && npm -v && newman -v
newman run collection.json -e environment.json
#!/usr/bin/env bash
set -e
COLLECTION="tests/collection.json"
ENVIRONMENT="tests/environment.json"
REPORT_DIR="reports/$(date +%F_%H-%M-%S)"
mkdir -p "$REPORT_DIR"
newman run "$COLLECTION" \
-e "$ENVIRONMENT" \
--reporters cli,json,html \
--reporter-json-export "$REPORT_DIR/result.json" \
--reporter-html-export "$REPORT_DIR/report.html"
chmod +x run_postman.sh
./run_postman.sh
const newman = require('newman');
newman.run({
collection: require('./tests/collection.json'),
environment: require('./tests/environment.json'),
reporters: ['cli', 'json', 'html'],
reporter: {
json: { export: 'reports/result.json' },
html: { export: 'reports/report.html' }
}
}, function (err, summary) {
if (err) {
console.error('Newman run failed:', err);
process.exit(1);
}
console.log('Collection run complete.');
if (summary.run.failures.length > 0) process.exit(1);
});
node run-tests.js
sudo tee /etc/systemd/system/postman-runner.service >/dev/null <<'EOF'
[Unit]
Description=Newman Postman Collection Runner
After=network.target
[Service]
Type=simple
User=your_username
ExecStart=/usr/bin/newman run /opt/tests/collection.json -e /opt/tests/environment.json --reporters cli,json --reporter-json-export /opt/reports/result.json
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now postman-runner.service
sudo systemctl status postman-runner.service
脚本编写与排错要点