Postman 脚本
Pre-Request 脚本
// 设置环境变量
pm.environment.set("timestamp", Date.now());
pm.environment.set("requestId", pm.variables.replaceIn("{{$guid}}"));
// 计算认证 token
const token = btoa("username:password");
pm.environment.set("basicAuth", `Basic ${token}`);
// 生成 HMAC 签名
const CryptoJS = require('crypto-js');
const secret = pm.environment.get("apiSecret");
const body = pm.request.body.raw;
const signature = CryptoJS.HmacSHA256(body, secret).toString();
pm.request.headers.add({ key: "X-Signature", value: signature });
测试脚本 — pm.test()
pm.test("状态码为 200", () => {
pm.response.to.have.status(200);
});
pm.test("响应时间 < 500ms", () => {
pm.expect(pm.response.responseTime).to.be.below(500);
});
const json = pm.response.json();
pm.test("用户有必填字段", () => {
pm.expect(json).to.have.property("id");
pm.expect(json.name).to.be.a("string");
pm.expect(json.email).to.include("@");
});
// 保存到环境变量供后续请求使用
pm.environment.set("userId", json.id);
pm.environment.set("authToken", json.token);
pm.environment 与 pm.variables
// 环境变量(每个环境独立)
pm.environment.set("key", "value");
pm.environment.get("key");
pm.environment.unset("key");
// 全局变量
pm.globals.set("globalToken", "abc123");
// Collection 变量
pm.collectionVariables.set("baseUrl", "https://api.example.com");
// 变量优先级:local > data > environment > collection > global
// 内置动态变量:
// {{$guid}} — UUID v4
// {{$timestamp}} — Unix 时间戳
// {{$randomInt}} — 随机整数 0-1000
// {{$randomEmail}} — 随机邮箱
pm.response — 响应检查
pm.response.code; // 200
pm.response.responseTime; // 毫秒
pm.response.headers.get("Content-Type");
pm.response.json(); // 解析 JSON
pm.response.text(); // 原始字符串
pm.response.to.be.ok;
pm.response.to.have.status(201);
// JSON Schema 校验
const schema = {
type: "object",
required: ["id", "name"],
properties: {
id: { type: "number" },
name: { type: "string" }
}
};
pm.test("Schema 合法", () => {
pm.response.to.have.jsonSchema(schema);
});
集合级脚本 — 自动刷新 Token
const token = pm.collectionVariables.get("accessToken");
const expiry = pm.collectionVariables.get("tokenExpiry");
if (!token || Date.now() > expiry) {
pm.sendRequest({
url: pm.environment.get("authUrl") + "/token",
method: "POST",
header: { "Content-Type": "application/json" },
body: {
mode: "raw",
raw: JSON.stringify({
client_id: pm.environment.get("clientId"),
client_secret: pm.environment.get("clientSecret"),
grant_type: "client_credentials"
})
}
}, (err, res) => {
if (!err) {
const data = res.json();
pm.collectionVariables.set("accessToken", data.access_token);
pm.collectionVariables.set("tokenExpiry",
Date.now() + data.expires_in * 1000);
}
});
}
pm 对象速查表
| 对象/方法 | 用途 |
|---|---|
pm.test(name, fn) | 定义测试断言 |
pm.expect(val) | Chai 风格断言 |
pm.response.json() | 解析响应体为 JSON |
pm.environment.set(k,v) | 设置环境变量 |
pm.globals.set(k,v) | 设置全局变量 |
pm.sendRequest(opts, cb) | 在脚本中发起子请求 |