作者:夕夕石(碩爺)
QQ:2470798103
Postman介紹
- Postman是一個(gè) Chrome 擴(kuò)展,能提供強(qiáng)大的 Web API & HTTP 請求調(diào)試功能。
- Postman能夠發(fā)送任何類型的http請求,支持GET/PUT/POST/DELETE等,請求頭中可以附帶任何數(shù)量的headers信息。
- Postman支持不同的認(rèn)證機(jī)制(basic,digest,OAuth)。
- Postman非常簡單易用,通過填寫URL、header、body等就可以發(fā)送一個(gè)請求。
- 沒有中文支持。
- Postman是使用chrome里面的接口。
- Postman是基于js語言的。
官方地址
- 官網(wǎng)地址:https://www.getpostman.com/
- 官方文檔地址: https://www.getpostman.com/docs/
- 問題反饋官方地址:https://go.pstmn.io/app-issues
- 官方git地址:https://github.com/postmanlabs
- 官方實(shí)例學(xué)習(xí):http://blog.getpostman.com/case-studies/
- 官方blog: http://blog.getpostman.com/
- 官方下載地址:https://www.getpostman.com/apps/
版本分別有:
- chrome插件版本
- mac版本
- linux版本(32/64)
- windows客戶端版本(32/64)
newman:
https://www.npmjs.com/package/newman
- 用來運(yùn)行postman腳本的包。
- 基于nodejs。
- 專為postman而生。
- 功能強(qiáng)大,可以生成html等各種報(bào)告,可以做持續(xù)集成。
一、postman下載與安裝
1、下載
- (1)第一種:夕夕石百度網(wǎng)盤下載地址:
鏈接:https://pan.baidu.com/s/1hlKY_X8rFdUj2hq3X2K2SQ
提取碼:w465
- (2)第二種:官網(wǎng)下載:
2、安裝
windows版本,下載后一路安裝即可。
安裝完畢后打開,注冊一個(gè)賬號就能用。
注冊賬號需要一個(gè)個(gè)人郵箱,自己取一個(gè)用戶名,設(shè)置密碼
二、postman界面熟悉
1、集合欄
2、請求欄
3、新建欄
4、有用的小按鈕
三、詳細(xì)功能介紹
1、全局設(shè)置
(1)全局設(shè)置入口
- 入口1:
- 入口2:
(2)全局設(shè)置--Genaral
全局設(shè)置--Genaral:可以設(shè)置字號、SSL證書認(rèn)證等
(3)全局設(shè)置--主題
可以設(shè)置兩個(gè)主題:默認(rèn)白、暗黑
(4)全局設(shè)置--查看版本
2、集合
(1)新建集合
(2)新建集合時(shí)編輯各字段
可以編輯集合的 名稱、描述、認(rèn)證、前置腳本、后置腳本、變量。
一般只編輯名稱、描述、即可。
(3)集合可以進(jìn)行哪些操作?
重命名、編輯、添加接口請求、添加文件夾、復(fù)制、導(dǎo)出、刪除
3、接口請求
(1)接口請求的url
(2)發(fā)送接口請求
(3)保存接口請求
有 save(保存)和 save as(另存為)兩種
(4)get請求的入?yún)?/h4>
get請求的入?yún)⒁獙懺?Params 中:
(5)post請求的入?yún)?/h4>
- post請求的入?yún)⒁旁?body 中
image
- postman支持的post入?yún)㈩愋?/li>
image
- 常用的 urlencoded 與 form-data 類型的區(qū)別:
<table>
<tr style="font-weight: bolder">
<td>post請求不同的傳參方式</td>
<td>特點(diǎn)</td>
</tr>
<tr>
<td>application/x-www-form-urlencoded</td>
<td>不指定時(shí)默認(rèn)方式, key1=value1&key2=value2</td>
</tr>
<tr>
<td>multipart/form-data</td>
<td>一般用于表單需要文件上傳</td>
</tr>
</table>
(6)前置腳本
- 前置腳本放在 Pre-request Script 中:
(7)后置腳本
- 后置腳本放在 Tests 中:
(8)響應(yīng)數(shù)據(jù)
- Pretty查看(美化查看) :
- Raw 查看:
- Preview 查看:
(9)運(yùn)行集合
- A.運(yùn)行入口:
- B.運(yùn)行集合界面認(rèn)識:
- C.運(yùn)行完一個(gè)集合后,會看到運(yùn)行結(jié)果:
- D.點(diǎn)擊下圖中的橘黃色按鈕“Run Summary”,查看匯總結(jié)果:
- E.匯總結(jié)果展示:
四、postman常用腳本之?dāng)嘌?/h2>
1、狀態(tài)碼及說明
==(1)狀態(tài)代碼是200==
pm.test("Status code is 200", function () {
pm.response.to.have.status(200); # 200是int類型
});
(2)狀態(tài)碼名稱(OK、Not Found……)
pm.test("Status code name has string", function () {
pm.response.to.have.status("Created"); # Created:string類型
});
(3)實(shí)際狀態(tài)碼在預(yù)期幾個(gè)狀態(tài)碼其中
pm.test("狀態(tài)碼是200或201", function () {
pm.expect(pm.response.code).to.be.oneOf([201,202]);
});
2、響應(yīng)中字符串?dāng)嘌?/h3>
**(1)檢查響應(yīng)主體是否 **等于字符串****
pm.test("響應(yīng)數(shù)據(jù) = 某個(gè)string", function () {
pm.response.to.have.body("response_body_string");
});
==**(2)檢查響應(yīng)主體是否 **包含字符串****==
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});
3、檢查JSON值(※極其重要※)
==(1)檢查響應(yīng)數(shù)據(jù)某 字段的值是否等于 xxx==
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.student.count).to.eql(100);
});
==(2)判斷響應(yīng)中 某字段下是否包含某字段(用js語言)==
hasOwnProperty
pm.test("檢查響應(yīng)中choose_subject字段是否包含name字段",function(){
var jsonData = pm.response.json();
pm.expect(jsonData.choose_subject.hasOwnProperty("name")).to.eql(true);
});
jsonData.choose_subject.containsKey.every(item => "name" in item); //(這個(gè)不用看)
下面這是加了js循環(huán)的(可以不看):
pm.test("檢查響應(yīng)中choose_subject字段是否包含name字段",function(){
var jsonData = pm.response.json();
for (i=0; i<jsonData.choose_subject.length; i++ ){
oneJson = jsonData.choose_subject[i];
pm.expect(oneJson.hasOwnProperty("name")).to.eql(true);
console.log(bool);
}
});
// jsonData.choose_subject.containsKey.every(item => "name" in item);
==(3)判斷響應(yīng)中某字段下某字段的值是否包含某字符串(用js語言)==
to.include
pm.test("響應(yīng)中包含buy_status字段,其下subject_name字段值包含字符串語文、數(shù)學(xué)、英語", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.buy_status[0].subject_name).to.include('語文');
});
==(4)判斷響應(yīng)中某字段的值不為空(不為0、“”、[]、{}等)==
pm.test("響應(yīng)content字段的值不為空", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.content ? true:false).to.eql(true);
});
4、header中某key存在
pm.test("Content-Type is present", function () {
pm.response.to.have.header("Content-Type");
});
5、判斷響應(yīng)中字段數(shù)據(jù)類型
我大概整理一下幾種類型的:
number 、string 、object 、array 、boolean 、undefind(空)
pm.test("term_type 是整型", function () {
pm.expect(typeof(jsonData.return_list[0].term_type) === "number").to.eql(true);
});
pm.test("id 是字符串", function () {
pm.expect(typeof(jsonData.return_list[0].id) === "string").to.eql(true);
});
pm.test("success 是布爾值", function () {
pm.expect(typeof(jsonData.success) === "boolean").to.eql(true);
});
pm.test("return_list 是 array數(shù)組", function () {
pm.expect(jsonData.return_list instanceof Array).to.eql(true);
});
pm.test("name字段未定義(或者說不存在)", function () {
var jsonData = pm.response.json();
pm.expect(typeof(jsonData.name) === "undefined").to.eql(true);
});
擴(kuò)展一下js語言(for循環(huán)):
var jsonData = pm.response.json();
for (i=0; i<jsonData.choose_subject.length; i++ ){
oneJson = jsonData.choose_subject[i];
console.log(oneJson );
}
6、響應(yīng)時(shí)間
- 響應(yīng)時(shí)間小于200毫秒
pm.test("Response time is less than 200ms", function () {
pm.expect(pm.response.responseTime).to.be.below(200);
});
- 響應(yīng)時(shí)間大于10毫秒
pm.test("響應(yīng)時(shí)間小于200毫秒", function () {
pm.expect(pm.response.responseTime).to.be.above(10);
});
7、json高級
(1)使用TinyValidator獲取JSON數(shù)據(jù)
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)JSON模式驗(yàn)證器
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;
});
(3)將XML主體轉(zhuǎn)換為JSON對象
var jsonObject = xml2Json(responseBody);
8、解碼base64編碼數(shù)據(jù)
var intermediate,
base64Content, // assume this has a base64 encoded value
rawContent = base64Content.slice('data:application/octet-stream;base64,'.length);
intermediate = CryptoJS.enc.Base64.parse(base64content); // CryptoJS is an inbuilt object, documented here: https://www.npmjs.com/package/crypto-js
pm.test('Contents are valid', function() {
pm.expect(CryptoJS.enc.Utf8.stringify(intermediate)).to.be.true; // a check for non-emptiness
});
五、postman進(jìn)階腳本
1、發(fā)送請求(pm.sendRequest)
(1)發(fā)送get請求
//const 是定義常量
const url = 'http://115.28.108.130:5000/api/user/getToken/?appid=136425';
// 發(fā)送get請求
pm.sendRequest(url, function (err, res) { //err, res這兩個(gè)命名隨便,但是必須第一個(gè)表示異常,第二個(gè)表示響應(yīng)
console.log(err ? err : res.text()); // 控制臺打印請求文本。res.text()、res.json()
});
(2)發(fā)送表單式post請求
//構(gòu)造一個(gè)登錄請求
const loginRequest = {
url: 'http://115.28.108.130:5000/api/user/login/',
method: "POST",
body: {
mode: 'urlencoded', // 模式為表單url編碼模式
urlencoded: 'name=張三&password=123456'
}
};
// 發(fā)送請求
pm.sendRequest(loginRequest, function (err, res) {
console.log(err ? err : res.text());
});
(3)發(fā)送JSON格式請求
// 構(gòu)造一個(gè)注冊請求
const regRequest = {
url: 'http://115.28.108.130:5000/api/user/reg/',
method: 'POST',
header: 'Content-Type: application/json', //注意要在Header中聲明內(nèi)容使用的類型
body: {
mode: 'raw', // 使用raw(原始)格式
raw: JSON.stringify({ name: '小小', password: '123456' }) //要將JSON對象轉(zhuǎn)為文本發(fā)送
}
};
// 發(fā)送請求
pm.sendRequest(regRequest, function (err, res) {
console.log(err ? err : res.json()); // 響應(yīng)為JSON格式可以使用res.json()獲取到JSON對象
});
(4)發(fā)送XML格式請求
發(fā)送XML格式和發(fā)送JSON格式差不多, 只要指定內(nèi)容格式并發(fā)送相應(yīng)的內(nèi)容即可
//構(gòu)造請求
const demoRequest = {
url: 'http://httpbin.org/post',
method: 'POST',
header: 'Content-Type: application/xml', // 請求頭種指定內(nèi)容格式
body: {
mode: 'raw',
raw: '<xml>hello</xml>' // 按文本格式發(fā)送xml
}
};
//發(fā)送請求
pm.sendRequest(demoRequest, function (err, res) {
console.log(err ? err : res.json());
});
2、更改接口請求順序
用處:有時(shí)候我們不希望集合按照嚴(yán)格順序執(zhí)行接口。這時(shí)候就可以更改接口請求的順序。
舉例:
假如你的集合下有三個(gè)接口A、B、C,其中A接口返回字段有一個(gè)content_type,
當(dāng)content_type=1時(shí),我們期望執(zhí)行B接口,再執(zhí)行C接口結(jié)束;
當(dāng)content_type=2時(shí),我們期望直接執(zhí)行C接口結(jié)束;
(1)一般模式
- postman.setNextRequest('接口請求的名稱');
//更改接口執(zhí)行順序
postman.setNextRequest("用腳本發(fā)送post請求");
(2)分支模式
var jsonData = pm.response.json()
if(jsonData.args.a == 'a'){
postman.setNextRequest("D");
}
else{
postman.setNextRequest("B");
}
(3)輪詢模式
場景:當(dāng)本接口響應(yīng)數(shù)據(jù)為 "{}\n"時(shí),再一次執(zhí)行本接口,直到響應(yīng)數(shù)據(jù)改變
if(pm.response.text() == "{}\n"){
postman.setNextRequest("自身接口的名稱");
}
3、腳本中打印請求url、入?yún)?、響?yīng)信息
(1)打印請求所有信息(包括url、入?yún)?、headers等)
console.log(request);
(2)打印請求的 url
console.log(request.url);
get請求的url是帶參數(shù)的;
post請求的url不帶參數(shù)
(3)打印get請求的所有入?yún)?/p>
如get請求的url是:
https://pMobile/recite_word/tlist.vpage?clazz_level={{tuobi_qiaoSuan_grade}}&sid={{student_id}}
console.log(request.url.split('?')[1]);
(4)打印get請求的所有入?yún)⒛硞€(gè)入?yún)?/p>
如get請求的url是:
https://pMobile/recite_word/tlist.vpage?clazz_level={{tuobi_qiaoSuan_grade}}&sid={{student_id}}
我想打印 sid 這個(gè)入?yún)⒌闹担?/p>
- 第一種方法:
console.log(request.url.split('?')[1].split('&')[1].split('=')[1]);
- 第二種方法:
上面這個(gè)方法,當(dāng)入?yún)㈨樞蜃兓瘯r(shí),會取錯(cuò)值,為了取正確,優(yōu)化成這樣寫:
var keys = request.url.split('?')[1].split('&');//獲取到所有的參數(shù),組成數(shù)組
for(index in keys){
key = keys[index].split('=')[0]; //獲取到參數(shù)對的key
value = keys[index].split('=')[1]; //獲取到參數(shù)對的value
if(key === 'sid'){ //當(dāng)參數(shù)對的key=我要的sid時(shí)
let sid = value; 自定義一個(gè)變量叫sid,值等于上面參數(shù)對的value
console.log(sid);
}
}
(5)獲取post參數(shù)的所有入?yún)?/p>
console.log(request.data);
(6)獲取post參數(shù)的入?yún)⒅小癿obile”這個(gè)參數(shù)
console.log(request.data.mobile);
(7)獲取請求的headers
console.log(request.headers);
4、腳本中打印響應(yīng)信息
(1)獲取響應(yīng)所有信息
console.log(pm.response);
(2)獲取響應(yīng)的headers
console.log(pm.response.headers.members[0]['key']);
console.log(pm.response.headers.members[2]['value']);
(3)獲取響應(yīng)狀態(tài)碼及說明
console.log(pm.response.code);
console.log(pm.response.status);
5、計(jì)算數(shù)組長度
function count(o){
var t = typeof o;
if(t == 'string'){ //計(jì)算字符串的長度
return o.length;
}else if(t == 'object'){//計(jì)算數(shù)組的長度
var n = 0;
for(var i in o){
n++;
}
return n;
}
return false;
}
var lesson = jsonData.lessons[0];
console.log(count(lesson));//調(diào)用count方法
六、獲取一個(gè)返回的HTML文件進(jìn)行校驗(yàn)
詳見我的另一篇文章
var html, titleText;
// load the response body as HTML using cheerio
// and using cheerio's jQuery like .find API, get the H1 tag
html = cheerio(responseBody);
titleText = html.find('h1').text();
// add a test that ensures that there is some H1 content
tests["page must have h1 heading"] = Boolean(titleText);
—— 碩爺
—— 專注互聯(lián)網(wǎng)測試