Postman 进阶(pre-request scripts&test script)
Postman 进阶
1. pre-request scripts
pre-request scripts我一般用来处理接口鉴权
pre-request scripts是一个关联了收藏夹内request,并且在发送request之前执行的代码片段。这对于在request header中包含时间戳或者在URL参数中发送一个随机字符串都是非常有用的。
例如:如果要在request的header中包含一个时间戳,你可以设置一个环境变量由一个函数返回他的值。
postman.setEnvironmentVariable('timestampHeader',new Date());
你可以在header中使 timestampHeader 变量,当request发送的时候,你的pre-request script将被执行,这个timestampHeader 变量的值将会替换{{timestampHeader}}。
注意:我们设置的环境对使用的环境变量必须是有效的。
2.Tests
1)基本结构
Postman给了你一个环境让你能够为每个request编写、执行你的test,而不用担心任何额外的设置。
一个Postman的test本质上是JavaScript的代码可以用来为一些特殊的test设置值。你可以在对象中设置一个描述性的键作为一个元素,然后声明他如果是true或false。
tests[“Body contains user_id”] = responseBody.has(“user_id”)
这回核对body中是否包含了user_id这个字符串。如果你需要,你可以增加更多的键,这取决于你要用test做多少的事情。
test被保存为收藏夹request的一部分。
2)SNIPPETS
在写test的时候这里有些事情需要注意,Postman尝试使得列出常用的片段更简单。你可以选择你想添加的片段,然后适当的代码将被添加到test的编辑器中。这是一个很好的方法来快速的构建test
3.Testing Sandbox
Postman的sandbox是一个JavaScript的执行环境,这使得你能够为request写pre-request scripts和test scripts 。不论你写的代码是pre-request scripts还是test script都会在sandbox中执行。
1.常用的库和工具
-
Lodash:
JS utility library -
jQuery (Deprecated):
Cross-platform JavaScript library. This will be removed in future versions of the sandbox. -
BackboneJS (Deprecated):
Provides simple models, views, and collections. This will be removed in future versions of the sandbox. -
SugarJS:
Extends native JS objects with useful methods -
tv4 JSON schema validator:
Validates JSON objects against v4 of the json-schema draft -
CryptoJS:
standard and secure cryptographic algorithms. Supported algorithms: AES, DES, EvpKDF, HMAC-MD5, HMAC-SHA1/3/256/512, MD5, PBKDF2, Rabbit, SHA1/3/224/256/512, TripleDES -
xml2Json(xmlString)
:
This function behaves the same in Newman and Postman -
xmlToJson(xmlString)
(Deprecated):
This function does NOT behave the same in Newman and Postman -
postman.getResponseHeader(headerName)
(Test-only):
returns the response header with name "headerName", if it exists. Returns null if no such header exists. Note: According to W3C specifications, header names are case-insensitive. This method takes care of this.
postman.getResponseHeader("Content-type") and postman.getResponseHeader("content-Type") will return the same value.
2.动态变量
Postman也有一些动态变量,你可以用在你的request中。这个现在主要还是在实现阶段,更多的功能以后被被添加进来。注意:动态变量不可以用于SandBox中,你只能在request的URL、headers、body中以放在双花括号中间的形式
-
{{$guid}}: Adds a v4 style guid {{$timestamp}}: Adds the current timestamp. {{$randomInt}}: Adds a random integer between 0 and 1000
代码示例
注意:test脚本在从服务器收到response后执行
1.设置环境变量:
postman.setEnvironmentVariable("key", "value");
2.设置全局变量:
postman.setGlobalVariable("key", "value");
3.检查response的body中是否包含字符串:
tests["Body matches string"] = responseBody.has("string_you_want_to_search");
4.把XML的body转换成JSON对象:
var jsonObject = xml2Json(responseBody);
5.检查response的body是都为一个字符串:
tests["Body is correct"] = responseBody === "response_body_string";
6.检查JSON的值:
var data = JSON.parse(responseBody); tests["Your test name"] = data.value === 100;
7.内容类型存在(检查不区分大小写)
tests["Content-Type is present"] = postman.getResponseHeader("Content-Type"); //Note: the getResponseHeader() method returns the header value, if it exists.
8.内容类型存在(区分大小写):
tests["Content-Type is present"] = responseHeaders.hasOwnProperty("Content-Type");
9.response的响应时间小于200ms:
tests["Response time is less than 200ms"] = responseTime < 200;
10.状态码为200:
tests["Status code is 200"] = responseCode.code === 200;
11.Code name contains a string:
tests["Status code name has string"] = responseCode.name.has("Created");
12.成功的POST request状态码:
tests["Successful POST request"] = responseCode.code === 201 || responseCode.code === 202;
13.Use TinyValidator for JSON data
var schema = { "items": { "type": "boolean" } }; var data1 = [true, false]; var data2 = [true, 123]; console.log(tv4.error); tests["Valid Data1"] = tv4.validate(data1, schema); tests["Valid Data2"] = tv4.validate(data2, schema);
Postman接口关联测试
进行接口关联测试,主要是将第一个接口返回的值设置为环境变量,然后再通过获取环境变量去获取对应第一个接口返回的值
例如,
场景:用户先登录系统,获取token令牌,下一步操作购买接口使用登录返回的token令牌进行操作,这时两个接口就放在同一个collections文件夹;
第一个登录接口,设置tests--环境变量设置响应的token值,
第二个购买接口,传参{{token}}引用环境变量,进行相应的其他操作。
var jsonData = JSON.parse(responseBody); //获取响应json格式报文 postman.setEnvironmentVariable("token", jsonData.data.result.token); //设置环境变量 token,值为jsonData.data.result.token tests["token"]=jsonData.data.result.token; //验证响应报文里有token参数返回 tests["Body matches string"] = responseBody.has("User"); //断言test响应报文结果是否包涵
var 定义一个变量jsonData ,设置token变量,jsonData.data.result.token 这个值是一级一级往下走的json数据
pre-request script(js)处理接口鉴权
var SECRET_KEY = pm.environment.get('secret'); var localtime = parseInt(new Date().getTime()); var timestamp = new Date(localtime).toISOString().substring(0,19) + "Z"; pm.environment.set('timestamp', timestamp); //生成uuid var guuid = function guid() { function S4() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); } return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); } var uuid = guuid() pm.environment.set('uuid', uuid); var percentEncode = function(value) { value = encodeURIComponent(value).replace(/!/g, '%21').replace(/\*/g, '%2A').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\+/g, "%20").replace(/\*/g, "%2A").replace(/%7E/g, "~"); return value; } var params = {}; var keys = []; var paramsString = request.url.split('?')[1].split("&"); console.log("ab:"+request); for(var key in request.data){ if(key == 'Signature'){ continue; } params[key] = (request.data[key]); keys.push(key); } for(let p in paramsString){ let t = paramsString[p].split('='); if(t[0] == 'Signature'){ continue; } if(t[1] == '{{timestamp}}'){ params[t[0]] = timestamp }else if(t[1] == '{{ak}}'){ params[t[0]] = pm.environment.get('ak') }else if(t[1] == '{{version}}'){ params[t[0]] = pm.environment.get('version') }else if(t[1] == '{{sigMethod}}'){ params[t[0]] = pm.environment.get('sigMethod') }else if(t[1] == '{{sigVersion}}'){ params[t[0]] = pm.environment.get('sigVersion') }else if(t[1] == '{{uuid}}'){ params[t[0]] = uuid }else{ params[t[0]] = t[1]; } keys.push(t[0]); } keys.sort(); var pieces = []; for(let i = 0, len = keys.length; i < len; i++){ pieces.push(percentEncode(keys[i]) + "=" + percentEncode(params[keys[i]])); } console.log("cd:"+pieces.join("&")) var normalizeString = percentEncode(pieces.join("&")); console.log(normalizeString) var strToSign = request.method + "&" + percentEncode("/") + "&" + (normalizeString); console.log("strToSign:"+strToSign); console.log(strToSign, SECRET_KEY + "&"); var sign = CryptoJS.HmacSHA1(strToSign, SECRET_KEY + "&"); console.log(sign); console.log(CryptoJS.enc.Base64.stringify(sign)); pm.environment.set('sign', encodeURIComponent(CryptoJS.enc.Base64.stringify(sign))); console.log(request.url)
Postman 进阶