CentOS下Postman脚本编写技巧
导读:CentOS下Postman脚本编写的实用技巧 1. 环境准备:安装Postman与Newman 在CentOS上使用Postman脚本前,需先安装Postman客户端及命令行工具Newman(用于自动化运行测试)。 安装Postman:...
CentOS下Postman脚本编写的实用技巧
1. 环境准备:安装Postman与Newman
在CentOS上使用Postman脚本前,需先安装Postman客户端及命令行工具Newman(用于自动化运行测试)。
- 安装Postman:推荐通过YUM仓库安装(官方源,便于更新),步骤如下:
安装完成后,通过sudo rpm --import https://dl.pstmn.io/release/key.asc # 导入GPG密钥 sudo vi /etc/yum.repos.d/postman.repo # 创建仓库文件 # 添加以下内容到文件中 [postman] name=Postman Repository baseurl=https://dl.pstmn.io/download/linux64 enabled=1 gpgcheck=1 gpgkey=https://dl.pstmn.io/release/key.asc sudo yum install postman # 安装Postmanpostman命令启动应用。 - 安装Newman:Newman是Postman的命令行伴侣,需通过npm安装(需提前安装Node.js):
sudo yum install -y nodejs npm # 安装Node.js和npm sudo npm install -g newman # 全局安装Newman
2. 环境与变量管理:实现多环境配置
变量是Postman脚本的核心,用于动态管理不同环境(开发、测试、生产)的配置,避免硬编码。
- 变量类型与作用域:
- 环境变量:适用于同一环境下的多请求共享(如
apiBaseUrl),作用域为当前环境; - 全局变量:适用于所有环境(如
authToken),作用域为全局; - 集合变量:仅适用于所属集合内的请求,作用域最小。
- 环境变量:适用于同一环境下的多请求共享(如
- 变量操作方法:
- 获取变量:
pm.environment.get("变量名")(环境变量)、pm.globals.get("变量名")(全局变量); - 设置变量:
pm.environment.set("变量名", "值")(字符串类型,若需存储JSON需用JSON.stringify)、pm.globals.set("变量名", "值"); - 删除变量:
pm.environment.unset("变量名")。
- 获取变量:
- 环境配置示例:
在Postman中创建“Development”“Testing”等环境,添加apiBaseUrl(如https://dev.api.example.com)、authToken等变量。在请求URL中使用{ { apiBaseUrl} } /endpoint格式,Postman会自动替换为实际值。
3. 前置脚本(Pre-request Script):请求前的动态准备
前置脚本在请求发送前执行,常用于动态生成参数、设置请求头或验证前置条件。
- 常见用途:
- 动态生成随机数(如验证码):
var randomNum = Math.floor(1000 + Math.random() * 9000); // 生成1000-9999的随机数 pm.request.url.addQueryParams([{ key: "random", value: randomNum.toString() } ]); - 设置认证头部:
const token = pm.environment.get("authToken"); pm.request.headers.add({ key: "Authorization", value: `Bearer ${ token} ` } ); - 验证前置变量:
const apiUrl = pm.environment.get("apiBaseUrl"); pm.test("API base URL is set", () => { pm.expect(apiUrl).not.toBeNull(); pm.expect(apiUrl).not.toBe(""); } );
- 动态生成随机数(如验证码):
4. 后置脚本(Tests):响应后的验证与数据处理
后置脚本在收到响应后执行,用于验证响应状态、解析响应体或存储数据供后续请求使用。
- 常见用途:
- 验证状态码:
pm.test("Status code is 200", () => { pm.response.to.have.status(200); } ); - 验证响应时间:
pm.test("Response time is less than 500ms", () => { pm.expect(pm.response.time).toBeLessThan(500); } ); - 解析并验证JSON响应体:
pm.test("Check user email in response", () => { const jsonData = pm.response.json(); // 解析JSON响应体 pm.expect(jsonData.email).to.eql("user@example.com"); } ); - 存储响应数据到环境变量(供后续请求使用):
const authToken = pm.response.json().token; pm.environment.set("authToken", authToken); // 存储token到环境变量
- 验证状态码:
5. 自动化测试:Newman命令行运行脚本
通过Newman将Postman集合自动化,集成到CI/CD流程(如Jenkins)中。
- 导出集合与环境文件:在Postman中选中集合,点击“Export”导出为JSON文件(如
collection.json);同理导出环境文件(如environment.json)。 - 运行测试:
常用选项:newman run /path/to/collection.json -e /path/to/environment.json-r html:生成HTML格式报告(需添加--reporter-html-templatePath指定模板路径);--reporter-json-export report.json:导出JSON格式报告。
- 自动化集成示例:创建Shell脚本
run_postman.sh,实现一键运行:赋予执行权限并运行:#!/bin/bash COLLECTION_FILE="/path/to/collection.json" ENVIRONMENT_FILE="/path/to/environment.json" newman run "$COLLECTION_FILE" -e "$ENVIRONMENT_FILE" --reporters cli,html --reporter-html-export report.htmlchmod +x run_postman.sh ./run_postman.sh
6. 调试技巧:快速定位脚本问题
调试是脚本编写的关键,以下方法可快速定位问题:
- 使用
console.log打印变量:在脚本中添加console.log语句,查看变量值或中间结果(如console.log("Token:", pm.environment.get("authToken")))。 - 查看Postman日志:在Postman界面点击“Console”(底部面板),查看请求/响应详情及脚本执行日志。
- 使用
pm.test断言:通过pm.test编写单元测试,验证脚本逻辑(如pm.test("Variable is set", () => { pm.expect(myVar).toBeTruthy(); } ))。 - 分步执行:对于复杂脚本,可拆分为多个
pm.test块,逐步执行验证。
7. 高级技巧:数据驱动测试与第三方库集成
- 数据驱动测试:通过CSV/JSON文件提供多组测试数据,提高用例覆盖率。
- 准备数据文件(如
testdata.csv):username,password user1,pass1 user2,pass2 - 在Postman中选择“Runner”,导入集合、环境及数据文件,Newman会自动遍历数据执行测试。
- 准备数据文件(如
- 第三方库集成:通过
pm.sendRequest发送异步请求,或使用child_process执行系统命令(如生成报告)。- 异步请求示例:
pm.sendRequest({ url: pm.environment.get("apiBaseUrl") + "/async-endpoint", method: "GET" } , (error, response) => { if (error) { console.error("Request failed:", error); } else { pm.test("Async request succeeded", () => { pm.expect(response.status).to.eql(200); } ); } } );
- 异步请求示例:
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: CentOS下Postman脚本编写技巧
本文地址: https://pptw.com/jishu/741222.html
