centos

CentOS下Postman如何使用脚本功能

小樊
46
2025-10-13 00:49:51
栏目: 智能运维

CentOS下Postman脚本功能使用指南

一、Postman脚本的核心类型

Postman的脚本功能分为两类,分别作用于请求生命周期的不同阶段:

二、基础脚本编写步骤

1. 打开脚本编辑界面

在Postman中创建或选中一个请求,点击顶部选项卡中的Pre-request Script(预请求脚本)或Tests(测试脚本),即可进入对应的脚本编辑窗口。

2. 编写预请求脚本(示例)

若需在请求头中添加动态时间戳,可使用以下代码:

// 生成当前时间戳(ISO格式)并设置为环境变量
const timestamp = new Date().toISOString();
pm.environment.set("timestampHeader", timestamp);

发送请求时,{{timestampHeader}}会自动替换为脚本生成的值(如2025-10-13T08:00:00.000Z)。

3. 编写测试脚本(示例)

若需验证响应状态码为200且响应体包含"user_id"字段,可使用以下代码:

// 检查响应状态码是否为200
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

// 解析响应体为JSON,检查是否包含"user_id"
pm.test("Response contains user_id", function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property("user_id");
});

发送请求后,Postman会在Tests标签页显示测试结果(通过/失败)。

三、环境变量与脚本交互

Postman的脚本可通过pm.environment对象与环境变量交互,实现数据的动态传递:

四、常见应用场景示例

1. 用户注册与登录流程自动化

通过预请求脚本生成测试数据,测试脚本验证登录逻辑并保存token,后续请求使用该token访问受保护接口:

// 预请求脚本:生成随机邮箱并发送注册请求
const email = `user${Math.floor(Math.random() * 1000)}@example.com`;
const password = "password123";
pm.sendRequest({
    url: pm.environment.get("apiBaseUrl") + "/register",
    method: "POST",
    body: JSON.stringify({email, password}),
    headers: {"Content-Type": "application/json"}
}, (error, response) => {
    pm.expect(response.status).to.eql(200);
});

// 测试脚本:发送登录请求并保存token
pm.test("Login successfully", function () {
    const response = pm.response;
    pm.expect(response.status).to.eql(200);
    const token = response.json().token;
    pm.environment.set("authToken", token); // 保存token到环境变量
});

2. 动态参数化请求

通过预请求脚本生成随机参数,避免重复使用同一数据:

// 预请求脚本:生成随机用户ID
const userId = Math.floor(Math.random() * 1000);
pm.environment.set("currentUserId", userId);

// 请求URL中使用环境变量
// 例如:GET /users/{{currentUserId}}

3. 验证响应数据完整性

通过测试脚本检查响应体中的关键字段是否存在或符合预期:

// 测试脚本:验证商品列表接口返回的商品数量
pm.test("Product list is not empty", function () {
    const products = pm.response.json();
    pm.expect(products.length).to.be.above(0);
});

五、调试与优化技巧

通过以上步骤,可在CentOS下充分利用Postman的脚本功能,实现API测试的自动化、动态化和数据驱动化,提升测试效率。

0
看了该问题的人还看了