读后笔记 -- Python 全栈测试开发 Chapter9:Postman + Newman 实现接口自动化
9.1 Postman 工具
9.1.4 Postman 基本操作
1. Get 请求
GET 请求的参数通过 Params 设置,最后出现在 url 地址栏上,拼接在 API 后面。

2. Post 请求
Post 请求的参数通过 Body 传送,不会出现在 url 中,有4种格式提供支持:form-data、x-www-form-urlencoded、raw、binary

3. Collection
可以创建多级目录,对接口测试用例进行管理
点击 Run 后,可以选择用例 执行

9.1.5 Postman 脚本
1. Tests(请求之后执行的脚本)
- Tests 下可以创建脚本进行断言,脚本用例可以参照右边的 SNIPPETS 参考
- 还可以设置 变量,通过获取脚本进行分析,传参给下一个脚本

在线文档: https://learning.postman.com/docs/writing-scripts/test-scripts/
主要 API : https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/
2. Pre-req. (请求发送前执行的脚本)

3. 脚本
| 对象 | 说明 |
| pm.environment.x | 环境变量 |
| pm.variables |
变量, 1)范围上:variables < environment < globas 2)优先级:variables > 环境变量(environment or globals) |
| pm.globals.x | 全局变量 |
| pm.collectionVariables | Collections 下的集合变量 |
| pm.info.x | 当前脚本的相关信息 |
| pm.request.x | 当前请求对象的相关信息 |
| pm.response.x | 当前响应对象的相关信息 |
| pm.sendRequest | 发送请求,示例可看下面或 api 文档 |
| pm.response.to.x | 响应对象的断言 |



多个请求整合在一个脚本中: 下面的例子中,有三个脚本,其顺序分别是 1- > 2 -> 3

4. cheerio
是 jquery 核心功能的一个快速灵活而又简单的实现,主要用在服务器端需要对 DOM 进行操作的地方。可以实现对 html 的解析

5. Code:请求转换成 其他语言脚本

9.2 Postman Collections
1. Environment v.s. Globals
- 下面是创建的 environment
- 点击上面的 "Globals",可查看所有 globals 变量
2. Collections 使用数据文件
- 修改被测试接口,参数使用数据文件的字段(如图1,用户名密码使用 {{userName}},{{Password}}) ->
- Collections, 选择要运行的 Folder,右键 Run Folder ->
- Runner tab,选择数据文件以及文件类型(数据之前使用 “,” 隔开) ->
- 断言结果及日志打印(console)正确显示




9.3 Newman 工具
1. newman 是 postman 推出的一个 nodejs 库,直接可以运行 postman 所生成导出的 json 文件,以命令行的形式运行;
- newman 可以非常方便运行和测试集合,可以实现接口自动化的持续集成;
- newman 安装基于 nodejs 库,需要使用 npm 命令(npm install -g newman)-- 【前提:安装 nodejs,并将 nodejs 目录添加到环境变量 PATH】
- 安装定制化报告(npm install -g newman-reporter-html / npm install -g newman-report-htmlextra)

2. 自动化接口测试
- 1)选择要测试的 Collection,右键 Export,导出为 json 格式文件
- 2)点开需要搭配的环境变量,点击...,选择 export,导出为 json 格式文件
- 3)选择对应测试的数据文件
newman run catback.postman_collection.json -e catback.postman_environment.json -d catback.logindata.txt

3. 定制化报告
// cmd 窗口 --- 生成 html report
newman run catback.postman_collection.json -e catback.postman_environment.json -d catback.logindata.txt -r html --reporter-html-export report.html

// cmd 窗口,生成 htmlextra 报告 newman run catback.postman_collection.json -e catback.postman_environment.json -d catback.logindata.txt -r htmlextra --reporter-htmlextra-export reportextra.html

浙公网安备 33010602011771号