postman自动化测试
程序员文章站
2022-07-12 11:35:05
...
测试工具主要包括三部分:(1)发起请求前运行的Pre-request script;(2)收到应答之后运行的Test;(3)一次运行所有请求的Collection Runner。
postman是Postman提供的全局对象,environment和global同名时,优先用environment;global只建议用在1种场景:定义公共函数
-
Pre-request script
适用于request header中包含时间戳或者在url参数中发送一个随机字符串
设置环境变量
postman.setEnvironmentVariable('timestampHeader',new Date());
- 获取环境变量
postman.getEnvironmentVariable('variableKey')
- 清除环境变量
postman.clearEnvironmentVariable('variableKey')
- 设置全局变量
postman.setGlobalVariable("key", "value");
- 获取全局变量
postman.getGlobalVariable("key");
- 检查response的body中是否包含字符串
tests["Body matches string"] = responseBody.has("string_you_want_to_search");
- 把XML的body转换成JSON对象
var jsonObject = xml2Json(responseBody);
- 检查response的body是都为一个字符串
tests["Body is correct"] = responseBody === "response_body_string";
- 检查JSON的值
var data = JSON.parse(responseBody);
tests["Your test name"] = data.value === 100;
-
内容类型存在
- 检查不区分大小写
tests["Content-Type is present"] = postman.getResponseHeader("Content-Type"); //返回的是这个请求头的值
- 区分大小写
tests["Content-Type is present"] = responseHeaders.hasOwnProperty("Content-Type");
- response的响应时间小于200ms:
tests["Response time is less than 200ms"] = responseTime < 200;
- 状态码为200:
tests["Status code is 200"] = responseCode.code === 200;
- Code name contains a string:
tests["Status code name has string"] = responseCode.name.has("Created");
- 成功的POST request状态码
tests[Successful POST request] = responseCode.code === 201 || responseCode.code === 202;
- 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);
- Tests常用函数
assertNotTimeout: var hasResponse = postman.getResponseHeader('Content-Type') ? true : false;
if (!hasResponse) tests['服务端在超时前没返回任何数据,请检查相关服务、网络或反向代理设置(以下跳过其他断言)'] = false;
logParams: if (hasResponse) tests[` [INFO]请求参数(仅限POST,超时没返回时不解析):$ {
JSON.stringify(request.data)
}`] = true;
getResponseJson: try {
if (hasResponse) var json = JSON.parse(responseBody);
} catch (err) {
tests['服务端没返回合法的JSON格式,请检查相关服务、网络或反向代理设置(以下跳过其他断言)'] = false;
tests[` [INFO]返回:$ {
responseBody
}`] = true;
console.error(err);
}
assertType: var assertType = (name, value, type) = > {
let isType = (type === 'array') ? Array.isArray(value) : typeof value === type;
tests[`$ {
name
}为$ {
type
}(实际值:$ {
value
})`] = isType;
};
assertEqual: var assertEqual = (name, actual, expected) = > {
tests[`$ {
name
}等于$ {
expected
}(实际值:$ {
actual
})`] = actual === expected;
};
assertNotEqual: var assertNotEqual = (name, actual, expected) = > {
tests[`$ {
name
}不等于$ {
expected
}(实际值:$ {
actual
})`] = actual !== expected;
};
- Console调试:
console.log();
如何通过chrome的调试模式查看console的输出内容;在Chrome浏览器中输入chrome://flags/
搜索packed,找到如下扩展,点击“启用”
上一篇: Ubuntu18.04下安装CUDA
下一篇: Recorder-List