postman断言脚本示例

# 数据处理

## 一、前置处理器

1、Example1: 拼接Sign签名

接口地址     http://{{host}}/api2/OpenAccountApi.getUserToken 

请求方式     POST 

请求参数     ?_app_key=[]&_time=[]&_sign=[] 

请求正文 {“account”:“账号信息”}

 响应正文 {“result”: { “token”: “”,“user_id”: ?},“status”: 0}




// 前置处理器:计算请求签名
var _app_secret = pm.environment.get("provider_app_secret");
var _time = (new Date()).valueOf();
var _pre_sign = 'requestBody=' + pm.request.body.raw + ',time=' + _time + ',appSecret=' + _app_secret;
var _sign = CryptoJS.MD5(_pre_sign).toString();
pm.environment.set("_time", _time);
pm.environment.set("_sign", _sign);

console.log('[Pre]OpenAccountApi.getUserToken _pre_sign='+_pre_sign+',_sign=' + _sign);



 二、后置处理器

1、Example1:拼接Sign签名

```json
// 响应断言
pm.test("Body matches token", function () {
    pm.expect(pm.response.text()).to.include("\"token\":");
    
    // 提取Token
    var result = pm.response.json().result;
    pm.environment.set("_userid", result.user_id);
    pm.environment.set("_token", result.token);
    console.log('[Tests]OpenAccountApi.getUserToken _token=' + result.token + ',user_id=' + result.user_id);
});
```

2、Example2:获取响应中的列表数据  

    var jsonData = JSON.parse(responseBody);
    pm.test("Status code is 200", function () {
        pm.response.to.have.status(200);
    });
    var jsonData = pm.response.json();
    
    pm.environment.set("krName", JSON.stringify(jsonData.data.krList));
    console.log(JSON.stringify(jsonData.data.krList)) 

取到的值在下一个接口中的pre-request Script中pm.environment.get("krName");

# 环境

## 一、环境变量

### 1、设置环境变量


pm.environment.set("variable_key", "variable_value");


注意:设置完之后在右上角眼睛处查看变量有没有设置成功

### 2、将嵌套对象设置为环境变量


var array = [1, 2, 3, 4];
pm.environment.set("array", JSON.stringify(array, null, 2));

var obj = { a: [1, 2, 3, 4], b: { c: 'val' } };
pm.environment.set("obj", JSON.stringify(obj));


### 3、获取环境变量


var value = pm.environment.get("variable_key");


如果值为字符串化JSON:


// These statements should be wrapped in a try-catch block if the data is coming from an unknown source.

var array = JSON.parse(pm.environment.get("array"));
var obj = JSON.parse(pm.environment.get("obj"));


### 4、清除环境变量


pm.environment.unset("variable_key");


## 二、集合变量

### 1、设置集合变量


pm.collectionVariables.set(variableName:String, variableValue:String);


### 2、获取集合变量


pm.collectionVariables.get(variableName:String);


### 3、清除集合变量


pm.collectionVariables.unset(variableName:String);


## 三、全局变量

### 1、设置全局变量


pm.globals.set("variable_key", "variable_value");


### 2、获取全局变量


pm.globals.get("variable_key");


### 3、清除全局变量


pm.globals.unset("variable_key"

### 4、变量

此函数在全局变量和活动环境中搜索变量。

```js
var value = pm.variables.get("variable_key");
```

# 响应处理

## 一、字符串的处理

### 1、检查响应主体是否包含字符串

pm.test("Body matches string", function () {
    pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});


### 2、检查响应主体是否等于字符串


pm.test("Body is correct", function () {
    pm.response.to.have.body("response_body_string");
});


## 二、JSON的处理

### 1、检查JSON值


pm.test("Body is correct", function () {
    pm.response.to.have.body("response_body_string");
});


## 三、状态码的处理

### 1、状态码为200


pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});


### 2、状态码中包含字符串

pm.test("Status code name has string", function () {
    pm.response.to.have.status("Created");
});


### 3、成功的POST请求状态码


pm.test("Successful POST request", function () {
    pm.expect(pm.response.code).to.be.oneOf([201,202]);
});


## 四、响应头的处理

### 1、存在Content-Type标头


pm.test("Content-Type header is present", function () {
    pm.response.to.have.header("Content-Type");
});


## 五、响应时间的处理

### 1、响应时间小于200ms


pm.test("Response time is less than 200ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(200);
});


## 六、验证响应结构的处理

### 1、使用TV4进行JSON模式验证


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;
});


### 2、使用AJV进行JSON模式验证


var Ajv = require('ajv'),
    ajv = new Ajv({logger: console}),
    schema = {
        "properties": {
            "alpha": {
                "type": "boolean"
            }
        }
    };

pm.test('Schema is valid', function() {
    pm.expect(ajv.validate(schema, {alpha: true})).to.be.true;
    pm.expect(ajv.validate(schema, {alpha: 123})).to.be.false;
});


## 七、将XML主体转换成JSON对象


var jsonObject = xml2Json(responseBody


# 断言

### 1、断言目标中是否存在子字符串

pm.test("Check if pattern is in target string",function () {
      pm.expect('foobar').to.have.string('bar');
  });


### 2、精确比较数字相等


 const TEN = 10;
  pm.test('Check if number is equal to 10', function () {
      pm.expect(TEN).to.equal(10);
  });


### 3、宽泛的比较


pm.test("Our JSON is loosely equal to the provided JSON", function () {
   pm.expect(data1).to.deep.equal(data2);
  });


1. `.deep` causes all `.equal`, `.include`, `.members`, `.keys`, and `.property` assertions that follow in the chain to use deep equality(loose equality) instead of strict (===) equality.
2. While the `.eql` also compares loosely, `.deep.equal` causes deep equality comparisons to also be used for any other assertions that follow in the chain while `.eql` does not.

### 4、断言返回值


pm.test("Check response value", function () {
      var jsonData = pm.response.json();
      pm.expect(jsonData.value).to.eql(100);
  });


### 5、断言当前环境变量


pm.test("Check if environment is production", function () {
      pm.expect(pm.environment.get('env')).to.equal('production');
  });


### 6、断言目标类型与给定字符串类型相等

pm.test("Check if target is string", function () {
     pm.expect('Postman').to.be.a('string');
    });



pm.test("Check if target is an object", function () {
     pm.expect({a: 1}).to.be.an('object');
    });



pm.test("Check if target is undefined", function () {
     pm.expect(undefined).to.be.an('undefined');
    });


**注意:**

1. 通常最好在对同一目标进行更多断言之前先`.a`检查目标的状态`type`。
2. 类型不区分大小写。

### 7、断言目标为空


pm.test("Check if array is empty", function () {
     expect([]).to.be.empty;
    });



pm.test("Check if string is empty", function () {
     pm.expect('').to.be.empty;
    });


### 8、断言目标中包含已传递的key值


pm.test("Check if object contains all provided keys", function () {
     pm.expect({a: 1, b: 2}).to.have.all.keys('a', 'b');
    });


pm.test("Checking if object contains any ONE of the keys", function () {
     pm.expect({a: 1, b: 2}).to.have.any.keys('a', 'b');
    });



pm.test("Check if object contains any NONE of the provided keys", function () {
     pm.expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd');
    });


### 9、断言目标包含所述属性


pm.test("Check if object contains the property", function () {
     pm.expect({a: 1}).to.have.property('a');
    });


**注意:**

1. 目标可以是`object`,`set`,`array`或`map`。
2. 如果`.keys`在不使用`.all`或`.any`的情况下运行,则表达式默认为`.all`。
3. 由于`.keys`不根据目标的不同的东西`type`,建议检查目标的`type`使用之前`.keys`使用`.a`。


pm.test("Check if object contains all the keys", function () {
     pm.expect({a: 1, b: 2}).to.be.an('object').that.has.all.keys('a', 'b');
    });


### 10、断言目标长度


pm.test("Check the length of the target", function () {
     pm.expect('foo').to.have.lengthOf(3);
    });



pm.test("Check the size of the target", function () {
     pm.expect([1, 2, 3]).to.have.lengthOf(2);
    });


### 11、断言目标数组具有与给定数组集相同的成员


pm.test("Check if the target has same members as the array set", function () {
     pm.expect([1, 2, 3]).to.have.members([2, 1, 3]);
    });


**注意:**

1. 默认情况下,`.members`进行严格比较。
2. 成员的顺序无关紧要。

### 12、断言目标包含所提供的项目

pm.test("Check if the target array includes the number provided", function () {
     pm.expect([1, 2, 3]).to.include(2);
    });


pm.test("Check if the target object includes the properties provided", function () {
     pm.expect({a: 1, b: 2, c: 3}).to.include({a: 1, b: 2});
    });


**注意:** 建议先声明目标的类型,因为要`.include`对各种类型进行操作。因此,建议`.a`在使用时进行连锁`.include`。


pm.test("Check if the target is an array that includes the number specified", function () {
     pm.expect([1, 2, 3]).to.be.an('array').that.includes(2);
    });


# 分支与循环

### 1、循环当前请求

postman.setNextRequest("request_name"


### 2、停止执行工作流程


postman.setNextRequest(null)


关于`postman.setNextRequest()`以下几点要点:

1. 指定后续请求的名称或ID,收集运行器将处理其余的请求。
2. 它可以在预请求或测试脚本中使用。如果有多个分配,则最后一个设置值优先。
3. 如果`postman.setNextRequest()`请求中不存在,则收集运行器默认为线性执行并移至下一个请求

 

posted @ 2020-05-25 18:28  美女爱找茬  阅读(440)  评论(0编辑  收藏  举报