CentOS中Postman如何使用脚本
导读:一、前提准备:安装Postman与Newman 在CentOS中使用Postman脚本自动化测试,需先安装Postman桌面应用(用于编写脚本)和Newman命令行工具(用于自动化运行脚本)。 安装Postman桌面应用: 访问Postm...
一、前提准备:安装Postman与Newman
在CentOS中使用Postman脚本自动化测试,需先安装Postman桌面应用(用于编写脚本)和Newman命令行工具(用于自动化运行脚本)。
- 安装Postman桌面应用:
访问Postman官方网站下载Linux版本安装包(.tar.gz格式),解压至指定目录(如/opt
),并创建符号链接以便终端直接调用:
安装完成后,终端输入sudo tar -xzf Postman-linux-x64-*.tar.gz -C /opt sudo ln -s /opt/Postman/Postman /usr/bin/postman
postman
即可启动应用。 - 安装Newman命令行工具:
Newman是Postman的命令行伴侣,需依赖Node.js环境。通过以下命令安装:
安装完成后,通过sudo yum install -y nodejs npm # 安装Node.js和npm sudo npm install -g newman # 全局安装Newman
newman --version
验证是否成功。
二、Postman脚本类型与编写
Postman脚本主要分为两类,分别作用于请求生命周期的不同阶段:
- Pre-request Script(预请求脚本):
在请求发送至服务器前执行,主要用于动态设置变量(如生成时间戳、获取环境变量)、构造请求参数或预处理数据。
示例:从环境变量获取token并设置为请求头:const token = pm.environment.get("auth_token"); // 获取环境变量 pm.request.headers.add({ key: "Authorization", value: `Bearer ${ token} `} ); // 添加请求头 console.log("Pre-request script executed, token set.");
- Tests Script(测试脚本):
在请求响应返回后执行,主要用于验证响应结果(如状态码、响应时间、数据格式),是自动化测试的核心。
示例:断言响应状态码为200且响应时间小于200ms:
更多常用函数:pm.test("Status code is 200", function() { pm.expect(pm.response.code).to.equal(200); // 断言状态码 } ); pm.test("Response time is less than 200ms", function() { pm.expect(pm.response.responseTime).to.be.below(200); // 断言响应时间 } );
pm.response.to.have.jsonBody()
(验证JSON响应体)、pm.globals.set()
(设置全局变量)、pm.expect().to.eql()
(深度断言)。
三、脚本执行:通过Newman运行集合
- 导出集合与环境文件:
在Postman中创建集合(Collection),添加请求并编写Pre-request Script/Tests Script。右键点击集合,选择“Export”,导出为JSON格式(如collection.json
);若使用了环境变量,同样导出环境文件(如environment.json
)。 - 运行Newman命令:
使用Newman运行集合,指定集合文件和环境文件路径:
示例输出会显示每个请求的执行结果(如状态码、断言是否通过)。newman run /path/to/collection.json -e /path/to/environment.json
四、自动化扩展:Shell脚本与Systemd服务
- Shell脚本自动化:
创建Shell脚本(如run_postman.sh
),封装Newman命令,实现一键运行:
赋予执行权限并运行:#!/bin/bash COLLECTION_FILE="/path/to/collection.json" ENVIRONMENT_FILE="/path/to/environment.json" newman run "$COLLECTION_FILE" -e "$ENVIRONMENT_FILE"
chmod +x run_postman.sh ./run_postman.sh
- Systemd服务(可选):
若需让Newman在后台持续运行(如定时执行测试),可创建Systemd服务:- 创建服务文件
/etc/systemd/system/postman.service
:[Unit] Description=Newman Postman Collection Runner After=network.target [Service] ExecStart=/usr/local/bin/newman run /path/to/collection.json -e /path/to/environment.json Restart=always User=your_username [Install] WantedBy=multi-user.target
- 启用并启动服务:
sudo systemctl daemon-reload sudo systemctl enable postman.service sudo systemctl start postman.service sudo systemctl status postman.service # 查看状态
- 创建服务文件
五、注意事项
- 确保环境变量与全局变量在Postman中正确设置,脚本中通过
pm.environment.get()
或pm.globals.get()
获取。 - 测试脚本中的断言需覆盖关键业务场景(如接口可用性、数据准确性),避免遗漏。
- 集成到CI/CD时,可将Shell脚本或Newman命令添加至Jenkins、GitLab CI等工具的流水线中,实现自动化测试。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: CentOS中Postman如何使用脚本
本文地址: https://pptw.com/jishu/717344.html