postman——预处理和断言
一、预处理
Pre-request Scrip 1、Pre-request Script是集合中请求发送之前需要执行的代码片段
2、请求参数中包含一个随机数或者请求header中包括一个时间戳,或者你的请求参数需要加密
Pre-request Script常用代码
右侧提供了一些常用的代码
二、断言
postman断言是JavaScript语言编写的,在postman客户端指定区域编写即可。
断言会在请求返回之后,运行,并根据断言的pass\fail情况体现在最终测试结果中。
clear a global variable | 清除全局变量 | pm.globals.unset("variable_key"); |
Clear an environment variable | 清除环境变量 | pm.environment.unset("variable_key"); |
get a global variable | 得到一个全局变量 | pm.globals.get("variable_key"); |
get a variable | 得到一个变量 | pm.variables.get("variable_key"); |
Get an environment variable | 得到一个环境变量 | pm.environment.get("variable_key"); |
response body:contains string | 检查response body包含字符串 | pm.test("Body matches string", function () { pm.expect(pm.response.text()).to.include("string_you_want_to_search"); }); |
response body:convert XML body to a JSON object | response body:将XML转换为JSON对象 | var jsonObject = xml2Json(responseBody); |
response body:is equal to a string | 检查response body等于指定字符串 | pm.test("Body is correct", function () { pm.response.to.have.body("response_body_string"); }); |
response body:JSON value check | 检查response body中JSON某字段值 | pm.test("Your test name", function () { var jsonData = pm.response.json(); pm.expect(jsonData.value).to.eql(100); }); |
response headers:content-Type header check | 检查content-Type是否包含在header返回 | pm.test("Content-Type is present", function () { pm.response.to.have.header("Content-Type"); }); |
response time is than 200ms | 响应时间超过200ms | pm.test("Response time is less than 200ms", function () { pm.expect(pm.response.responseTime).to.be.below(200); }); |
send s request | 发送一个请求 | pm.sendRequest("https://postman-echo.com/get", function (err, response) { console.log(resp onse.json()); }); |
set a global variable | 设置一个全局变量 | pm.globals.set("variable_key", "variable_value"); |
set an environment variable | 设置一个环境变量 | pm.environment.set("variable_key", "variable_value"); |
status code:Code is 200 | 状态码:代码是200 | pm.test("Status code is 200", function () { pm.response.to.have.status(200); }); |
status code:code name has string | 状态码:代码中有指定字符串 | pm.test("Status code name has string", function () { pm.response.to.have.status("Created"); }); |
status code:successful POST request | 状态码:成功的post请求 | pm.test("Successful POST request", function () { pm.expect(pm.response.code).to.be.oneOf([201,202]); }); |
use tiny validator for JSON data | 为json数据使用tiny验证器 | 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; }); |