APIテスト:ポストマン/ニューマン
1)なぜ郵便配達人/ニューマン
Postmanはスクリプトやクエリのコレクションに便利なIDEです。Newmanは、CI/CDでGUIなしで同じコレクションを実行するCLIエンジンです。彼らは一緒に与えます:- 反復可能な後退および急速な喫煙;
- 環境/シークレットのパラメータ化;
- 質の測定基準および機械読解可能なレポート。
2)ベースモデル
コレクション-共通のスクリプトを持つクエリとフォルダのツリー。
環境-dev/stage/prod (URL、キー)に'{{vars}}'を設定します。
事前リクエストスクリプト-準備:署名、トークン、データの相関。
テスト-変数/アーティファクトのアサーションと保存。
Data-files-データ駆動の実行のためのCSV/JSON。
モック/モニター-群れと定期的なチェック。
<API v1>
├─ _bootstrap (auth, health, seeds)
├─ Public
├─ Authenticated
│ ├─ Accounts
│ ├─ Payments
│ └─ Reports
└─ _teardown (cleanup)
3)変数と秘密
変数を'baseUrl'、 'tenant'、 'clientId'と明示的な接頭辞で参照してください。
CI環境変数に秘密(パスワード、client_secret、 HMACキー)を保持し、リポジトリにコミットしないでください。
スコープ:local→collection→environment→globalsを使用します。
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(クライアント資格情報)
事前リクエスト: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);
});
}
リクエスト:'Authorization: Bearer {{access_token}}'。
4.2 HMAC (Webhooks/Partners)
事前リクエスト: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)'。
その後のステップのIDを'pm経由で保存します。collectionVariables。'を設定します。
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スキーマをコレクション変数または別のファイルに保存します。
OpenAPIの場合:事前リクエスト/テスト(ajv、 tv4)-via 'pmで既製のlibsを使用します。sendRequest'をrawファイルまたはJSONインラインに送信します。
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(トークンなし/無効なスコープ/ロール)。
- 400/422(スキームの検証、必須フィールド、制限)。
- 404 (BOLA/エイリアンリソース)。
- 409(競合、idempotentキー)。
- 429 (limits)-'Retry-After'をチェックします。
- 5xx-正しい劣化とレトロクライアント。
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) Idempotence、 retraeのpagination
'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) ニューマン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')をエクスポートします。
パイプラインでは、ジャブを分離します:煙(高速)、回帰(完全)、セキュリティ(負/境界)。
10.4 Docker
docker run --rm -v $PWD:/etc/newman postman/newman \
run collection. json -e stage-eu. json
11)モキとモニタリング
モックサーバーポストマン-フロントと契約のための高速スタック。
モニタ-クラウドからのクラウドの定期的な実行(レイテンシ、5xx、 SSL)。
リポジトリでは、決定的なモックのためにサンプル応答ファイルを保持します。
12)テストデータおよびクリーニング
エンティティの作成/削除(_bootstrap/_teardown)。
接頭辞'e2e _'とTTLを持つテストオブジェクトをラベル付けします。
js pm. collectionVariables. set("uniq", Date. now()+"_"+Math. floor(Math. random()1e6));
13)パフォーマンス「膝の上」
Postmanは読み込みツールではありませんが、:- 午後を測って。応答します。responseTime';
- 5-10の反復を実行し、p95/しきい値を修正します。
- 重いパフォーマンスが実行されます-JMeter/k6/Gatlingで(この記事の外)。
14)ローカリゼーションとマルチテナンシー
変数'tenant'、 'region'、 'lang';環境のスイッチ。
テストは、テナント間のデータが「流れ」ないことを確認する必要があります(BOLA読み取り、クロステナント禁止)。
地域の機能(限度、通貨)のための個別のコレクション/フォルダ。
15)報告およびアーティファクト
CIアーティファクトを保存する:HTMLレポート、'junit。xml'、レスポンスボディ。
ショックドロップのSlack/Teams通知を接続します。
16)質および適用範囲
コーティングマトリックス:- リソースあたりのCRUD (200/201/204+ネガ)。
- 認可:ロール/スコープ/マルチテナント。
- ペジネーション/フィルタ/ソート。
- 独断と退却。
- 限界:413/414/431/429。
- フォーマットとスキーマ(JSON スキーマ/OpenAPI)。
- 統合(HMAC/mTLSとのWebhook)-アンチリプレイ。
17) Antipatterns
陰性検査なしの1つの「幸せな方法」。
コレクション/リポジトリ内の長寿命トークン。
テストデータと本番データの混在。
明示的な相関関係のない潜在的なテスト順序依存性。
サンプリングなしの巨大なデータファイル。
JUnit/HTMLレポートがない→CIの可視性がない。
18) Prod Readinessチェックリスト
- コレクションはドメインによって分解され、'_bootstrap/_ teardown'があります。
- dev/stage/prodの環境;CI-secret-storageからの秘密。
- Pre-request (OAuth2/HMAC);トークンはキャッシュされ、回転されます。
- テスト:陽性+陰性、スキーム(JSONスキーマ)、ペジネーション、429/Retry-After。
- Idempotency: 'Idempotency-Key'をチェックします。
- データ駆動型CSV/JSON、一意性のためのランダムサフィックス。
- CIのニューマン:JUnit/HTMLレポート、ビルド出力としてのアーティファクト。
- 主要ルートのモック/モニター;イチジクのSLA。
- 変数、タグ、および起動順序のドキュメント。
19) TL;DRについて
テスト・ロジックをPostmanコレクション、環境内のパラメータに保存し、JUnit/HTMLレポートを使用してNewman経由でCIで実行します。ネガ、スキーマ、idempotency、ペジネーションと制限をカバーします。ステップを変数と関連付け、データ駆動の入力と洗浄/モニタを使用します。シークレット-CIからのみ、レポート-アーティファクトを構築します。