当前位置: 首页 > news >正文

postman断言脚本(2)

https://learning.postman.com/docs/writing-scripts/script-references/test-examples/#parsing-response-body-data

状态码

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

多重断言

pm.test("The response has all properties",()=>{//parse the response JSON and test three propertiesconst responseJson = pm.response.json();pm.expect(responseJson.type).to.eql('vip');pm.expect(responseJson.name).to.be.a('string');pm.expect(responseJson.id).to.have.lengthOf(1);});

解析response body

To parse JSON data, use the following syntax:

const responseJson = pm.response.json();

To parse XML, use the following:

const responseJson =xml2Json(pm.response.text());
If you're dealing with complex XML responses you may find console logging useful.

To parse CSV, use the CSV parse utility:

const parse =require('csv-parse/lib/sync');const responseJson =parse(pm.response.text());

To parse HTML, use cheerio:

const $ = cheerio.load(pm.response.text());//output the html for testing
console.log($.html());

If you can't parse the response body to JavaScript because it's not formatted as JSON, XML, HTML, CSV, or any other parsable data format, you can still make assertions on the data.

Test if the response body contains a string:

pm.test("Body contains string",()=>{pm.expect(pm.response.text()).to.include("customer_id");});

This doesn't tell you where the string was encountered because it carries out the test on the whole response body. Test if a response matches a string (which will typically only be effective with short responses):

pm.test("Body is string",function(){pm.response.to.have.body("whole-body-text");});

断言 HTTP response

Your tests can check various aspects of a request response, including the body, status codes, headers, cookies, response times, and more.

响应体

Check for particular values in the response body:

pm.test("Person is Jane",()=>{const responseJson = pm.response.json();pm.expect(responseJson.name).to.eql("Jane");pm.expect(responseJson.age).to.eql(23);});

状态码

Test for the response status code:

pm.test("Status code is 201",()=>{pm.response.to.have.status(201);});

If you want to test for the status code being one of a set, include them all in an array and use oneOf:

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

Check the status code text:

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

响应头

Check that a response header is present:

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

Test for a response header having a particular value:

pm.test("Content-Type header is application/json",()=>{pm.expect(pm.response.headers.get('Content-Type')).to.eql('application/json');});

cookie

Test if a cookie is present in the response:

pm.test("Cookie JSESSIONID is present",()=>{pm.expect(pm.cookies.has('JSESSIONID')).to.be.true;});

Test for a particular cookie value:

pm.test("Cookie isLoggedIn has value 1",()=>{pm.expect(pm.cookies.get('isLoggedIn')).to.eql('1');});

响应时间

Test for the response time to be within a specified range:

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

一般性断言

断言value type

/* response has this structure:
{"name": "Jane","age": 29,"hobbies": ["skating","painting"],"email": null
}
*/const jsonData = pm.response.json();
pm.test("Test data type of the response",()=>{pm.expect(jsonData).to.be.an("object");pm.expect(jsonData.name).to.be.a("string");pm.expect(jsonData.age).to.be.a("number");pm.expect(jsonData.hobbies).to.be.an("array");pm.expect(jsonData.website).to.be.undefined;pm.expect(jsonData.email).to.be.null;});

断言数组属性

Check if an array is empty, and if it contains particular items:

/*
response has this structure:
{"errors": [],"areas": [ "goods", "services" ],"settings": [{"type": "notification","detail": [ "email", "sms" ]},{"type": "visual","detail": [ "light", "large" ]}]
}
*/const jsonData = pm.response.json();
pm.test("Test array properties",()=>{//errors array is emptypm.expect(jsonData.errors).to.be.empty;//areas includes "goods"pm.expect(jsonData.areas).to.include("goods");//get the notification settings 
objectconst notificationSettings = jsonData.settings.find(m=> m.type ==="notification");pm.expect(notificationSettings).to.be.an("object","Could not find the setting");//detail array must include "sms"pm.expect(notificationSettings.detail).to.include("sms");//detail array must include all listedpm.expect(notificationSettings.detail).to.have.members(["email","sms"]);});

断言object属性

Assert that an object contains keys or properties:

pm.expect({a:1,b:2}).to.have.all.keys('a','b');
pm.expect({a:1,b:2}).to.have.any.keys('a','b');
pm.expect({a:1,b:2}).to.not.have.any.keys('c','d');
pm.expect({a:1}).to.have.property('a');
pm.expect({a:1,b:2}).to.be.an('object').that.has.all.keys('a','b');
Target can be an object, set, array or map. If .keys is run without .all or .any, the expression defaults to .all. As .keys behavior varies based on the target type, it's recommended to check the type before using .keys with .a.

断言值在集合里

check a response value against a list of valid options:

pm.test("Value is in valid list",()=>{pm.expect(pm.response.json().type).to.be.oneOf(["Subscriber","Customer","User"]);});

断言包含object

Check that an object is part of a parent object:

/*
response has the following structure:
{"id": "d8893057-3e91-4cdd-a36f-a0af460b6373","created": true,"errors": []
}
*/pm.test("Object is contained",()=>{const expectedObject ={"created":true,"errors":[]};pm.expect(pm.response.json()).to.deep.include(expectedObject);});

Using .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. 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 doesn't.

验证响应结构

Carry out JSON schema validation with Tiny Validator V4 (tv4):

const schema ={"items":{"type":"boolean"}};
const data1 =[true,false];
const 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;});

Validate JSON schema with the Ajv JSON schema validator:

const schema ={"properties":{"alpha":{"type":"boolean"}}};
pm.test('Schema is valid',function(){pm.response.to.have.jsonSchema(schema);});

发送异步请求

Send a request from your test code and log the response.

pm.sendRequest("https://postman-echo.com/get",function(err, response){console.log(response.json());});
http://www.lryc.cn/news/25184.html

相关文章:

  • js中?.、??的具体用法
  • 刷题笔记1 | 704. 二分查找,27. 移除元素
  • 柔性电路板的优点、分类和发展方向
  • OpenCV入门(二)快速学会OpenCV1图像基本操作
  • Redis源码---有序集合为何能同时支持点查询和范围查询
  • 从计费出账加速的设计谈周期性业务的优化思考
  • 垃圾回收的概念与算法(第四章)
  • 让您的客户了解您的制造过程“VR云看厂实时数字化展示”
  • CV——day80 读论文:DLT-Net:可行驶区域、车道线和交通对象的联合检测
  • 工具篇4.5数据可视化工具大全
  • 京东前端二面常考手写面试题(必备)
  • 如何用AST还原某音的JSVMP
  • 【蓝桥杯试题】 递归实现指数型枚举例题
  • 【用Group整理目录结构 Objective-C语言】
  • JavaScript高级程序设计读书分享之8章——8.1理解对象
  • 代码随想录算法训练营第四十天 | 343. 整数拆分,96.不同的二叉搜索树
  • 数据结构与算法系列之顺序表的实现
  • 基于Linux_ARM板的驱动烧写及连接、挂载详细过程(附带驱动程序)
  • python-爬虫-字体加密
  • 计算机组成原理4小时速成5:输入输出系统,io设备与cpu的链接方式,控制方式,io设备,io接口,并行串行总线
  • 安全狗受聘成为福州网信办网络安全技术支撑单位
  • RV1126 在Ubuntu18.04开发环境搭建
  • 如何在 C++ 中调用 python 解析器来执行 python 代码(一)?
  • 操作系统权限提升(二十三)之Linux提权-通配符(ws)提权
  • Zookeeper下载和安装
  • Biomod2 (上):物种分布模型预备知识总结
  • 操作指南:如何高效使用Facebook Messenger销售(二)
  • 计算机三级|网络技术|中小型网络系统总体规划与设计方案|IP地址规划技术|2|3
  • 为什么一定要做集成测试?
  • 前端:CSS