CentOS环境下Postman自定义脚本实践
一 环境准备与安装
sudo tar -xzf Postman-linux-x64-*.tar.gz -C /optsudo ln -s /opt/Postman/Postman /usr/bin/postmanpostmansudo yum install -y nodejs npmsudo npm install -g newman二 编写自定义脚本的核心要点
pm.environment.set/get、pm.globals.set/get、pm.collectionVariables.set/get、pm.variables.set/getpm.response.json()/text()、pm.response.to.have.status(200)、pm.expect(...).to...pm.request.headers.add({key, value})、pm.request.url = '...'console.log(...) 输出调试信息;在桌面版通过 View → Show Postman Console 查看。三 桌面版脚本示例
pm.variables.set("timestamp", new Date().getTime());pm.test("Status code is 200", () => pm.response.to.have.status(200));pm.test("Response time < 500ms", () => pm.expect(pm.response.responseTime).to.be.below(500));const json = pm.response.json(); pm.expect(json.id).to.be.a('number');pm.environment.set("userId", json.id);四 无界面自动化与CI集成
newman run collection.json -e environment.jsonnewman run collection.json -e environment.json -d data.csvnewman run collection.json -e environment.json -r html,cli#!/bin/bashCOLLECTION_FILE="/path/to/collection.json"ENVIRONMENT_FILE="/path/to/environment.json"newman run "$COLLECTION_FILE" -e "$ENVIRONMENT_FILE" -r cli,htmlchmod +x run_postman.sh./run_postman.sh五 常见问题与排错