Postman Pre-request After-request Scripts~UUID作成~Timestamp取得~SHA256変換
はじめに
Web APIをテストするにはPostmanはよく使われていますよね、前はほとんど簡単なテストなので直接Requestを投げてResponseをもらうだけです。
最近はちょっとだけ複雑なテストをやってRequest前後は簡単なスクリプトを実行する必要があります、唯一なUUIDや、今現在のシステム時間を取得など。またはサーバーのTokenを取得した後に次のRequestでセットする。
Postman画面
❶はPre-requestの書く場所
❷はAfter-requestの書く場所
Pre-request Scripts
UUID作成
❶番Pre-requestのタブに下記のスクリプトで
var uuid = require('uuid');
postman.setEnvironmentVariable('myuuid', uuid.v4());
使う時にRequestのBodyに
{
"uuid": "{{$myuuid}}",
...略...
}
更に簡単な書き方
RequestのBodyに{{$guid}}
を使います、事前定義などは要りません
{
"uuid": "{{$guid}}",
...略...
}
Timestamp取得
❶番Pre-requestのタブに下記のスクリプトで
const moment = require('moment')
pm.globals.set('logTime', moment().format('YYYY-MM-DD HH:mm:SS'))
console.log(pm.globals.get('logTime'))
使う時は上記と同じRequestのBodyに{{$logTime}}
で取得
SHA256変換
Pre-requestのタブに下記のスクリプトで
var sha256Value = CryptoJS.SHA256("123456789");
postman.setGlobalVariable("sha256Value", sha256Value);
※postman.setGlobalVariable()/postman.getGlobalVariable()はpm.globals.set()/pm.globals.get()と同じ
使う時は上記と同じRequestのBodyに{{$sha256Value}}
で取得
After-request Scripts
❷番Testsのタブに下記のスクリプトで
token = pm.response.json()['data']['token']
console.log(token)
postman.setGlobalVariable("token", token);
最後に
というのは、PostmanはRequestの前後にJavaScriptを実行する能力が持ちます、なので事前事後のデータ処理、引数設定などが可能です。上記の例だけではなくJavaScript実行さえであればいろんな可能性がありますよね。
Author And Source
この問題について(Postman Pre-request After-request Scripts~UUID作成~Timestamp取得~SHA256変換), 我々は、より多くの情報をここで見つけました https://qiita.com/nakamurahiro/items/b155ccc6db0271e8d40d著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .