如何在Linux系统中使用Postman脚本
Postman脚本主要用于接口自动化测试和流程编排,分为Pre-request Script(请求前置脚本)(请求发送前执行,用于参数准备)和Tests Script(测试脚本)(请求完成后执行,用于响应验证)两类。以下是在Linux环境下使用Postman脚本的详细步骤:
在Linux系统中使用Postman前,需先完成基础安装:
.tar.gz格式)下载。tar -xzf Postman-linux-x64-*.tar.gz -C /opt解压;创建符号链接sudo ln -s /opt/Postman/Postman /usr/bin/postman,实现终端直接输入postman启动应用。Pre-request Script用于请求发送前的动态准备,常见场景包括生成随机参数、设置环境变量、获取前置接口数据等。
var randomNum = Math.floor(1000 + Math.random() * 9000); // 生成1000-9999的随机数
pm.request.url.addQueryParams([{ key: "random", value: randomNum.toString() }]);
const authToken = pm.environment.get("authToken"); // 获取环境变量中的令牌
pm.request.headers.add({ key: "Authorization", value: `Bearer ${authToken}` });
// 假设前置接口返回的响应体包含access_token字段
const response = pm.response.json();
const token = response.access_token;
pm.globals.set("globalToken", token); // 存入全局变量,供后续请求使用
Tests Script用于请求完成后的响应验证,常见场景包括状态码检查、响应体字段断言、响应时间限制等。
pm.test("Status code is 200", function () {
pm.response.to.have.status(200); // 使用Chai断言库的to.have.status方法
});
pm.test("Check user name in response", function () {
const jsonData = pm.response.json(); // 解析响应体为JSON对象
pm.expect(jsonData.user.name).to.eql("John Doe"); // 断言name字段值为John Doe
});
pm.test("Response time is less than 300ms", function () {
pm.expect(pm.response.responseTime).to.be.below(300); // 断言响应时间小于300ms
});
Newman是Postman的命令行工具,可用于Linux服务器上的自动化测试(如CI/CD流水线)。
npm install -g newman(需提前安装Node.js和npm)。collection.json);同理导出环境变量为environment.json。newman run /path/to/collection.json -e /path/to/environment.json
-e:指定环境变量文件(可选,用于替换集合中的变量)。--reporters cli,json生成命令行报告和JSON报告,或--reporter-html-export report.html生成HTML报告。let/const,避免全局污染)。pm.environment.get/set)或全局变量(pm.globals.get/set)管理动态参数,确保脚本的可复用性。console.log()输出调试信息,可在Postman的Console面板(点击顶部菜单栏的View→Show Postman Console)查看。