GH GambleHub

API测试:Postman/Newman

1)为什么Postman/Newman

Postman是用于脚本和查询集合的方便IDE。Newman是CLI引擎,可在CI/CD中运行相同的没有GUI的集合。他们一起给出:
  • 可重复的倒退和快速的烟雾;
  • 环境/秘密参数化;
  • 质量指标和机器可读报告。

2)基本模型

集合-具有常见脚本的查询和文件夹树。
环境-dev/stage/prod (URL, keys)的'{vars}集合。
预请求脚本-准备:签名,令牌,数据共振。
测试-批准和保存变量/工件。
数据文件-用于数据驱动运行的CSV/JSON。
Mock/Monitor-稳定和定期检查。

收藏结构(建议):

<API v1>
├─ _bootstrap (auth, health, seeds)
├─ Public
├─ Authenticated
│  ├─ Accounts
│  ├─ Payments
│  └─ Reports
└─ _teardown (cleanup)

3)变量和秘密

将变量命名为显式前缀:"baseUrl"、"tenant"、"clientId"。
保存CI环境变量中的秘密(密码、client_secret、HMAC密钥),不要向存储库发送。
使用scope: local → collection → environment → globals(最小可能)。

环境示例(fragment JSON):
json
{
"name": "stage-eu",
"values": [
{"key":"baseUrl","value":"https://api. stage. example. com","type":"text","enabled":true},
{"key":"tenant","value":"eu-1","type":"text","enabled":true}
]
}

4)身份验证: 模板

4.1 OAuth2/OIDC (Client Credentials)

Pre-request:

js if (!pm.environment. get("access_token")          Date. now() > pm. environment. get("token_exp")) {
pm. sendRequest({
url: pm. environment. get("authUrl"),
method: 'POST',
header: {'Content-Type':'application/x-www-form-urlencoded'},
body: { mode:'urlencoded', urlencoded:[
{key:'grant_type',value:'client_credentials'},
{key:'client_id',value:pm. environment. get('clientId')},
{key:'client_secret',value:pm. environment. get('clientSecret')},
{key:'scope',value:'payments:read payments:write'}
]}
}, (err, res) => {
pm. environment. set("access_token", res. json(). access_token);
pm. environment. set("token_exp", Date. now()+ (res. json(). expires_in-30)1000);
});
}

在查询中: "授权:Bearer {{access_token}}".

4.2个HMAC(webhooks/合作伙伴)

Pre-request:

js const body = pm. request. body? pm. request. body. raw          '': '';
const ts = Math. floor(Date. now()/1000);
const msg = `${ts}.${body}`;
const sig = CryptoJS. HmacSHA256(msg, pm. environment. get('hmacSecret')). toString();
pm. variables. set('ts', ts);
pm. variables. set('sig', sig);

标题:"X-Timestamp:{ts}},"X-Signature:{sig}"。

5)测试: 断言和扩张

使用'pm。expect(...)` и `pm.test("...", fn)`.

通过'pm保存后续步骤的ID。collectionVariables.set`.

示例:
js pm. test("HTTP 200", () => pm. response. to. have. status(200));
pm. test ("Scheme is valid," () => {
const schema = pm. collectionVariables. get("schema_wallet");
pm. expect(tv4. validate(pm. response. json(), JSON. parse(schema))). to. be. true;
});
pm. test ("Contains id," () => {
const id = pm. response. json(). id;
pm. expect(id). to. be. a('string');
pm. collectionVariables. set("wallet_id", id);
});

6)方案验证(OpenAPI/JSON方案)

将JSON Schema存储在集合变量或单独的文件中。
对于OpenAPI:在pre-request/test (ajv, tv4)-通过'pm.sendRequest"到原始文件或JSON inline。

示例模式存储:
js pm. collectionVariables. set("schema_wallet", JSON. stringify({
"type":"object",
"required":["id","currency","balance"],
"properties":{
"id":{"type":"string"},
"currency":{"type":"string","pattern":"^[A-Z]{3}$"},
"balance":{"type":"number","minimum":0}
}
}));

7)数据驱动脚本

CSV:


email, password, currency u1@example. com, P@ss1, EUR u2@example. com, P@ss2, USD

查询使用"{email}",{{currency}"。

启动:

newman run collection. json -e stage-eu. json -d users. csv

JSON(对象数组)-适用于复杂的桉例/结构。

8)负面桉例和可持续性

覆盖:
  • 401/403(无令牌/不正确的scope/角色)。
  • 400/422(方桉验证、强制性字段、限制)。
  • 404(BOLA/其他资源)。
  • 409(冲突,等效密钥)。
  • 429(限制)-检查"Retry-After"。
  • 5xx-正确的客户降级和恢复。
"Retry-After"验证示例:
js pm. test ("There is Retry-After at 429," () => {
if (pm. response. code === 429) pm. expect(pm. response. headers. has('Retry-After')). to. be. true;
});

9)异位性,复古,分离

传送"Idempotency-Key"并确保重播产生相同的"id/status"。
测试分页:"limit/offset"/"cursor",复制和跳过细节。
模拟测试脚本中的转发:使用相同键连续调用。

js pm. test ("Idempotent repetition," () => {
pm. sendRequest(pm. request, (err, res2) => {
pm. expect(res2. code). to. eql(pm. response. code);
pm. expect(res2. json(). id). to. eql(pm. response. json(). id);
});
});

10) Newman в CI/CD

10.1启动


newman run collection. json \
-e stage-eu. json \
-d data. csv \
--timeout-request 30000 \
--reporters cli,htmlextra,junit \
--reporter-htmlextra-export./reports/report. html \
--reporter-junit-export./reports/junit. xml

10.2 GitHub行动(片段)

yaml
- uses: actions/setup-node@v4 with: { node-version: '20' }
- run: npm i -g newman newman-reporter-htmlextra
- run: newman run collection. json -e stage-eu. json --reporters cli,junit --reporter-junit-export reports/junit. xml
- uses: actions/upload-artifact@v4 with: { name: newman-reports, path: reports }

10.3 Jenkins/GitLab CI

导出JUnit("--reporter-junit-export")进行本机可视化。
在pipline中,分开jobs: smoke(快速)、regression(完整)、security(否定/边界)。

10.4 Docker


docker run --rm -v $PWD:/etc/newman postman/newman \
run collection. json -e stage-eu. json

11)洗涤和监测

Mock servers Postman是前线和合同的快速稳定。
监视器是从云中定期运行的smokes(latency,5xx,SSL)。
在存储库中保留确定性湿疹的示例响应文件。

12)测试数据和清洁

创建/删除实体(_bootstrap/_teardown)。
用"e2e_"和TTL前缀标记测试对象。

对于冲突字段,使用随机后缀:
js pm. collectionVariables. set("uniq", Date. now()+"_"+Math. floor(Math. random()1e6));

13)"跪下"表演"

Postman不是负载工具,但是:
  • 测量'pm。response.responseTime`;
  • 运行5-10次迭代并固定p95/阈值;
  • 重型性能运行-在JMeter/k6/Gatling(本文之外)。

14)本地化和多范围

变量"tenant","region","lang";在周围切换。
测试应验证数据不被intertenant"流动"(BOLA读数、交叉值禁令)。
针对区域特征(限值、货币)的单个集合/文件夹。

15)报告和文物

保存CI工件:HTML报告,"junit。xml',无响应响应的逻辑(响应对象)。
插入Slack/Teams滑块下降通知。

16)质量和覆盖范围

涂层矩阵:
  • CRUD按资源(200/201/204+负值)。
  • 授权:角色/漏斗/多角色。
  • 分离/过滤器/排序。
  • 相同性和retrai。
  • 限制:413/414/431/429。
  • 格式和模式(JSON Schema/OpenAPI)。
  • 集成(带有HMAC/mTLS的webhooks)-反复制。

17)反模式

一个没有负面测试的"快乐之路"。
集合/存储库中的长寿令牌。
将测试数据与prod数据混合。
没有明显共振的测试顺序的隐性依赖性。
没有采样的巨型数据文件。
缺少JUnit/HTML报告→ CI中没有可见性。

18)准备就绪支票清单

  • 集合按域分列,有'_bootstrap /_teardown'。
  • dev/stage/prod的环境;来自CI秘密存储的秘密。
[] Pre-request для auth (OAuth2/HMAC);令牌被缓存和轮换。
  • 测试:正面+负面,电路(JSON Schema),分位,429/Retry-After。
  • 等效性:检查"Idempotency-Key",双调用等效。
  • 数据驱动的CSV/JSON,用于唯一性的随机后缀。
  • Newman in CI: JUnit/HTML报告,工件作为构建外包。
  • 主要路线的洗涤器/监视器;Smokes的SLA。
  • 变量、标记和启动顺序文档。

19) TL;DR

将测试逻辑存储在Postman集合中,将参数存储在环境中,并通过Newman在CI中运行JUnit/HTML报告。覆盖底片,电路,幂等,分期和限制。将步骤与变量相关联,使用数据驱动输入和洗涤器/监视器。秘密-仅来自CI,报告-法案文物。

Contact

联系我们

如需任何咨询或支持,请随时联系我们。我们随时准备提供帮助!

Telegram
@Gamble_GC
开始集成

Email — 必填。Telegram 或 WhatsApp — 可选

您的姓名 可选
Email 可选
主题 可选
消息内容 可选
Telegram 可选
@
如果填写 Telegram,我们也会在 Telegram 回复您。
WhatsApp 可选
格式:+国家代码 + 号码(例如:+86XXXXXXXXX)。

点击按钮即表示您同意数据处理。