postman的sandbox
——pre-request scripts 和 test scripts
Postman的sandbox是一个JavaScript的执行环境,这使得你能够为request写pre-request scripts和test scripts 。不论你写的代码是pre-request scripts还是test script都会在sandbox中执行。
sandbox中常用的库和工具:
(1)Lodash: JS utility library (2)jQuery (Deprecated,已弃用): Cross-platform JavaScript library. This will be removed in future versions of the sandbox. (3)BackboneJS (Deprecated,已弃用): Provides simple models, views, and collections. This will be removed in future versions of the sandbox. (4)SugarJS: Extends native JS objects with useful methods (5)tv4 JSON schema validator: Validates JSON objects against v4 of the json-schema draft (6)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 (7)xml2Json(xmlString): This function behaves the same in Newman and Postman (8)xmlToJson(xmlString)(Deprecated,已弃用): This function does NOT behave the same in Newman and Postman (9)postman.getResponseHeader(headerName) (Test-only,只能在 Test 中使用 ): 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.
(10)postman.getResponseCookie(cookieName)(Test-only,只能在 Test 中使用 ):
Gets the response cookid with the giben name. You will need to enable the interceptor for this to work.
Request/response相关属性
request {object}: Postman makes the request object available to you while writing scripts. This object is read-only. Changing properties of this object will have no effect. Note: Variables will NOT be resolved in the request object. The request object is composed of the following: data {object}: this is a dictionary of form data for the request. (request.data["key"]=="value") headers {object}: this is a dictionary of headers for the request (request.headers["key"]=="value") method {string}: GET/POST/PUT etc. url {string}: the url for the request. responseHeaders {object}(Test-only)(Deprecated): This is a map of the response headers. This is case-sensitive, and should not be used. Check thepostman.getResponseHeader() method listed above. responseBody {string}(Test-only): A string containing the raw response body text. You can use this as an input to JSON.parse, or xml2Json. responseTime {number}(Test-only): The response time in milliseconds responseCode {object}(Test-only): Contains three properties: code {number}: The response code (200 for OK, 404 for Not Found etc) name {string}: The status code text detail {string}: An explanation of the response code tests {object}(Test-only): This object is for you to populate. Postman will treat each property of this object as a boolean test. iteration {number}: Only available in the Collection Runner and Newman. Represents the current test run index. Starts from 0.
旧版语法和新版语法区别(当前postman工具同时兼容这些新旧版语法):
1、旧版语法用 “ postman.*** ”,新版语法用 “ pm.*** ”;
2、旧版语法:responseCode.code、responseCode.name、responseTime、responseBody、JSON.parse(responseBody).***
新版语法:response.code、response.status、response.responseTime、response.text()、response.json().***
一、postman的环境变量
1、旧版环境变量语法:
1 postman.setEnvironmentVariable(variableName, variableValue) 2 3 postman.setGlobalVariable(variableName, variableValue) 4 5 postman.clearEnvironmentVariable(variableName) 6 7 postman.clearGlobalVariable(variableName) 8 9 postman.clearEnvironmentVariables() 10 11 postman.clearGlobalVariables() 12 13 14 environment: A dictionary of variables in the current environment. Use environment["foo"] to access the value of the "foo" environment variable. 15 16 globals: A dictionary of global variables. Useglobals["bar"] to access the value of the "bar" global variable.
2、新版环境变量语法:
pm.environment.get("variable_key"); //Get an environment variable pm.globals.get("variable_key"); //Get a global variable pm.variables.get("variable_key"); //Get a variable pm.collectionVariables.get("variable_key"); //Get a collection variable pm.environment.set("variable_key", "variable_value");//Set a environment variable pm.globals.set("variable_key", "variable_value"); //Set a global varlable pm.collectionVariables.set("variable_key", "variable_value"); //Set a coilection variable pm.environment.unset("variable_key"); //Clear an environment variable pm.globals.unset("variable_key"); //Clear a global variable pm.collectionVariables.unset("variable_key"); //Clear a collection variable
3、postman的动态变量——环境变量的使用
注意:动态变量不可以用于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
二、postman常用函数
//Send a request pm.sendRequest("https://postman-echo.com/get", function (err, response) { console.log(response.json()); }); //Response body:Convert XML body to a JSoN Obiect var jsonObject = xml2Json(responseBody); //Use Tiny Validator for JSON data var schema = { "items": { "type": "boolean" } }; var data1 = [true, false]; var data2 = [true, 123]; pm.test('Schema is valid', function () { pm.expect(tv4.validate(data1, schema)).to.be.true; pm.expect(tv4.validate(data2, schema)).to.be.true; });
三、postman的断言
JavaScript中的断言,常用的“相等(==)”和“等同(===)”的区别:
1.相等(==)和不相等(!=)是比较运算符,但当类型不同时会进行类型转换,例如false==0这个条件为真;
2.等同(===)和不等同(!==)是判断一不一样,但是不会进行类型转换,类型不同就判断它们不同,所以false===0这个条件为假;
3.一般为了安全起见,都是使用===进行比较的;
1、使用 tests 方式断言
1 '' 2 //tests断言功能,相当于python中print()函数的输出功能,可以在断言结果中显示 3 //tests断言语法:tests["断言后的输出文案或者用例名称"] = 判断结果的布尔值 4 // 说明:多个断言语句中,tests后面的中括号里面的文案不能重复,否则只会显示一个 5 // 如果等号后边的值为“true”,那么就断言成功,否则断言失败 6 '' 7 tests["这是测试断言文案01"] = true; 8 tests["这是测试断言文案02"] = false; 9 tests["这是测试断言文案03"] = 1+1 === 2; 10 tests["这是测试断言文案04"] = 1+1 > 2; 11 tests["这是测试断言文案05"] = 2>1 && 2>2; 12 tests["这是测试断言文案06"] = 2>1 || 2>2; 13 tests["这是测试断言文案07"] = !(2>1 || 2>2); 14 tests["这是测试断言文案08"] = "123456abcdef".has("56a"); 15 16 17 tests["1、断言响应结果中包含success"] = responseBody.has("success"); 18 tests["2、断言响应结果中包含success"] = JSON.parse(responseBody).msg === "success"; 19 tests["3、断言响应结果中包含success"] = pm.response.text().has("success"); 20 tests["4、断言响应结果中包含success"] = pm.response.json().msg.has("success");
2、使用 chai.js库 断言
chai.js是一套TDD(测试驱动开发)/BDD(行为驱动开发)的断言库,包含有3个断言库,支持BDD风格的expect/should和TDD风格的assert。可以高效的和任何js测试框架(支持在postman中应用)搭配使用。
1 // 断言语法:pm.test("用例文案",function(){ 断言语句 }) 2 pm.test('case01',function(){ 3 pm.response.to.have.status(200); 4 pm.response.to.have.status("OK"); 5 }) 6 7 pm.test('case02',function(){
pm.expect(1+1==2).to.be.true; 8 pm.expect(responseCode.code) === 200; 9 pm.expect(pm.response.code).to.equal(200); //等价于上面一句的用法 10 11 pm.expect(responseCode.name).to.equal("OK"); 12 pm.expect(pm.response.status).to.equal("OK"); 13 pm.expect(pm.response.status).to.contain("OK"); 14 pm.expect(pm.response.status).to.contains("OK"); 15 16 pm.expect(responseTime).to.greaterThan(10); 17 pm.expect(pm.response.responseTime).to.greaterThan(10); 18 19 //responseBody是一个字符串文本 20 pm.expect(responseBody).to.contains("success"); 21 //如果要取出responseBody里面的值,可以先将其转换成json对象再进行取值 22 pm.expect(JSON.parse(responseBody).msg).to.equal("success"); 23 //pm.response.text() 是字符串文本 24 pm.expect(pm.response.text()).to.contains("success"); 25 pm.expect(pm.response.text()).to.have.string("success"); 26 //pm.response.json() 是一个json对象,里面的值如果是字典格式要用点(.),如果是数组格式要用中括号([])来取值 27 pm.expect(pm.response.json().msg).to.contains("success"); 28 29 //语法中的postman不能换成pm 30 pm.expect(postman.getResponseHeader("Connection")).to.equal("keep-alive"); 31 //注意不要省掉了【postman.getResponseCookie('cookies的name值').value】后面的value 32 // pm.expect(postman.getResponseCookie('cookies的name值').value).to.contain("要包含的字符"); 33 })
3、postman中断言——正则表达式
1 tests["判断是否包含某些字符"] = "123456abcdef".match(new RegExp('12(.+?)de')); 2 3 tests[responseBody] = true; 4 var m = responseBody.match(new RegExp('\"msg\"\:\"(.+?)\"\,\"data\"'))[1]; 5 tests["提取响应体中的msg值:"+ m] = true;