postman 请求内容处理:
脚本基本语法
:
打印语句:console.log();
打印返回内容:console.log(responseBody);
假如返回内容为{“ret”:1,“message”:“sucessful”}
- 使用json提取返回内容里的字段值
var re=JSON.parse(responseBody);//定义一个变量,将json化的返回内容转化为一个变量
console.log(re); //打印这个变量,就是请求内容
console.log(re.ret); //打印ret字段的值
pm.globals.set(“ret”,re.ret); //将ret字段得值设置为全部变量,变量名称为ret - 使用正则表达式提取返回内容里的字段值,match匹配
var re = responseBody.match(new RegExp(’“ret”:"(.*?)"’));
console.log(re);//取到两个值,一个“ret”:1 一个 1
console.log(re[1]);//打印ret字段的值
pm.globals.set(“ret”,re.ret); //将ret字段得值设置为全部变量,变量名称为ret - 引用全局变量: { {ret}} // 双大括号+变量名
postman内置动态参数 以及自定义的动态参数
-
postman内置动态参数
{ { KaTeX parse error: Expected 'EOF', got '}' at position 10: timestamp}̲} 当前时间的时间戳 { { randomInt}}0-1000之间的随机数
{ {$guid}} 速记guid字符串 -
引用内置动态参数: { {$timestamp}} //直接将该参数复制到请求内容所需要的位置
-
per-scripts 内代码获取时间戳
var times=Date.now(); //手动获取时间戳
pm.globals.set(“times”,times);// 设置为全局变量
脚本使用:
Status code:Code is 200:返回的状态码是否为200
Response body:Contains string 检查响应中是否包含指定字符
Response body:Json value check 检查响应中json的值
Response body:is equal to a string 检查响应 是否等于一个字符串
Response headers:Content-Type 检查是否包含Content-Type
Response time is less than 200ms:检查请求耗时小于200ms
断言
//状态断言
pm.test(“检查返回状态码200”,function(){
pm.response.to.hava.status(200);
});
//业务断言
pm.test(“Body matches string”, function () {
pm.expect(pm.response.text()).to.include(“string_you_want_to_search”);
});
注意:include 内不可以直接引用postman自带的动态参数,可使用自定义动态参数,
1.如:include("string{
{$times}}") //非正确方法不能使用,报错
如:include("string{
{$timestamp}} ")//内置动态参数不能使用,报错
自定义动态参数可使用以下方法引用:
1、include("string"+pm.globals.get("times"))
2、include("string"+globals["times"])
3、include("string"+globals.times)
-
单个接口断言:接口 —Tests 下编写脚本即可
扫描二维码关注公众号,回复: 13770899 查看本文章 -
全局断言: collections----Tests 下编写脚本即可
-
断言内如何取文件的数据?
如:csv内容 :
name ,sexy, age
lili,1,23data.name ,即可获取csv的name属性
如:console.log(data.name); //打印csv 的name属性