当前位置:网站首页>Postman interface test VII
Postman interface test VII
2022-07-07 10:09:00 【Splendid Qianyang 813】
Catalog
Postman Common test results verification and use skills
Postman Common test results verification and use skills
Postman Of test Essentially, JavaScript Code , By writing test code , every last tests return True, or False.
every last tests It's actually a test case
The official document gives a lot of verification methods , We learn through examples
The result returned by the interface is json
{
"status": 301,
"message": " There's not enough stock to buy ",
"lists": [11]
}
1
2
3
4
5
1. Check response Of body Whether there is a string in
tests[" Test point "] = responseBody.has(" String to find ");
1
example :
tests["status code"] = responseBody.has("301");
tests["status Whether there is "] = responseBody.has("status");
tests["lists Whether there is "] = responseBody.has("lists");
tests["lists The value is 11"] = responseBody.has("11");
1
2
3
4
notes : When json in value by integer when , The value to be searched can be without double quotation marks ,
tests[“xxx”]xxx It represents the name of your test site , It can be in Chinese
tests[“xxx”]xxx If there are multiple occurrences in a script , Then only execute the first , So try not to repeat
When value When equal to Chinese string , This method seems to be not very easy to use , But we have other ways to verify , To look down
2. Check Response Body Is equal to the string
tests[" Test point "] = responseBody === "Response Body What's coming back ";
1
This can be used when the content returned by the interface is a pure string , Directly check the correctness of the whole returned result ,
Example :
Interface to return : ha-ha
tests[" Return as haha "] = responseBody === " ha-ha ";
tests[" Return as haha "] = responseBody === " Ha ";
1
2
The second will return False, Must match exactly
3. Check the corresponding time
tests["Response time Less than 200 millisecond "] = responseTime < 200;
tests["Response time Greater than 200 millisecond "] = responseTime > 200;
1
2
4. Check the status code
It's easy to understand , Namely http Request status code
tests["Status code is 200"] = responseCode.code === 200;
1
notes :
The status code here , Follow the one we used above json Inside "status" It's not the same thing
5.Code name contains a string
tests["Status code name has string"] = responseCode.name.has("Created");
tests["502"] = responseCode.name.has("Server");
tests["502"] = responseCode.name.has("Unreachable Server");
1
2
3
This is my understanding , Check HTTP code Corresponding string, As given below list
The corresponding table below , If you use fiddler Simulate the corresponding return , Be careful fiddler There is a problem with the returned case , Use the following table string
1 news (1 initial )
100 Continue
2 success (2 initial )
200 OK
3 Redirect (3 initial )
300 Multiple Choices
301 Moved Permanently
302 Move temporarily
.....
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
600 Unparseable Response Headers( Omit some )
6. Set the environment variable / Global variables
pm.environmentVariable.set("key", "value");
pm.globalVariable.set("key", "value");
1
2
7. hold XML Of body convert to JSON object :
var jsonObject = xml2Json(responseBody);
1
8. Check json Value
var jsonData = JSON.parse(responseBody);tests["Your test name"] = jsonData.value === 100;
And take the one on it json Test data
tests[" Status code for 301"] = jsonData["status"] == "301";
tests["message"] = jsonData["message"] == " There's not enough stock to buy ";
tests["list"] = jsonData["lists"][0] == "11";
1
2
3
4
5
9. Check for information
tests["Content-Type is present"] = postman.getResponseHeader("content-Type");// Case insensitive
tests["Content-Type is present"] = responseHeaders.hasOwnProperty("Content-Type");// Case sensitive
1
2
10.POST request Status code
tests["Successful POST request"] = responseCode.code === 201 || responseCode.code === 202;
201 - Created The server has created the document ,Location The head gives its URL.
202 - Accepted Request accepted , But the processing has not been completed .
1
2
3
The official documents also provide information about json Verification example of
This is based on JSON Format definition JSON Specification of data structure , We call him
The official example
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);
1
data1 and data2 It's test data ,schema Equivalent to verifying json The specification of
Verify in the example data1 and data2 Medium value Are they all boolean type
First understand writing json Standardize the keywords commonly used in documents
keyword | describe |
---|---|
$schema | $schema Keyword status , Indicates that this pattern is related to v4 The draft specification is consistent . |
title | Use it to provide a title for our pattern . |
description | Description of the pattern . |
type | type Keywords are in our JSON The first constraint is defined on the data : Must be a JSON object . |
properties | Define various keys and their value types , And for JSON Minimum and maximum values in the file . |
required | Store the necessary attribute list . |
minimum | Constraints set for values , Indicates the minimum acceptable value . |
exclusiveMinimum | If there is “exclusiveMinimum” And it has a Boolean value true, If it is strictly greater than “minimum” The value of is valid for the instance . |
maximum | Constraints set for values , Indicates the maximum acceptable value . |
exclusiveMaximum | If there is “exclusiveMinimum” And it has a Boolean value true, If it is strictly less than “maximum” The value of is valid for the instance . |
multipleOf | If the result of dividing an instance by the value of this keyword is a number, it means close to “multipleOf” The numerical example of is valid . |
maxLength | The maximum length value of a string instance character . |
minLength | The minimum length value of the string instance character . |
pattern | If the regular expression matches the instance successfully, the string instance is considered valid . |
Take the first json As an example
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "",
"properties": {
"lists": {
"id": "",
"items": {
"default": 11,
"description": " Check list value ",
"id": "",
"title": "",
"type": "integer"
},
"type": "array"
},
"message": {
"default": " There's not enough stock to buy ",
"description": "message Information ",
"id": "",
"title": "",
"type": "string"
},
"status": {
"default": 301,
"description": " Returns the status value ",
"id": "",
"title": "",
"type": "integer"
}
},
"type": "object"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
A complete JSON Schema Validation specification
You can delete some according to the actual situation key, But keep the ones marked in red
default The default value is , Write according to the actual situation , The above example “ When the inventory of goods is insufficient ” The status code of is 301, If you want to status and message To verify , that default You can add , If only verify the returned value yes integer or string type , You can ignore
You can also add restrictions such as maximum and minimum
Here is the test code
var jsonData = JSON.parse(responseBody);
var schema = {
"properties": {
"lists": {
"items": {
"default": 11,
"description": " Under stocked goods id",
"type": "integer"
},
"type": "array"
},
"message": {
"default": " There's not enough stock to buy ",
"description": "id by 11 Our stock of goods is insufficient ",
"type": "string"
},
"status": {
"description": "status",
"type": "integer"
}
},
"type": "object"
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
tests["json Format validation "] = tv4.validate(jsonData, schema); // verification json Format
tests[" The return status code is 200"] = responseCode.code === 200;
tests[" Status code for 301"] = jsonData["status"] == "301";
tests["message"] = jsonData["message"] == " There's not enough stock to buy ";
tests["list"] = jsonData["lists"][0] == "11";
1
2
3
4
5
In this way, the interface returns json We can verify the structure and data .
tv4 by Postman Imported external library , If you want to know, you can go to the official documents
in addition Postman Some methods are also provided, such as :
responseCookies
request.data["key"]=="value"
request.headers["key"]=="value"
request.method
request.url
request
responseHeaders
responseBody
responseTime
responseCode contain code,name,detail
iteration
1
2
3
4
5
6
7
8
9
10
11
These methods can help us do more , For example, get through an interface cookie value , And then put cookie Set to global variable , Provide for other interfaces
When we write test scripts , You may encounter script writing errors or need some log To help us improve the script ,
We can open it View->Show Postman Console, After opening, we can pass console.log(xxx) To output logs and view error messages
For an interface , When we know the parameters and their corresponding results , Can pass postman Judge , Verify whether the returned data is equal to the expected data . This can make our interface testing more convenient and concise .
1、 Prepare the data .
postman The acceptable file format is shown in the figure , Generally speaking, the data we need to parameterize can be stored in excel In the table , As shown in the figure below ,postman While reading the data , Read according to the column name in the first row , And in excel, Multiple parameters can be separated by commas , No, txt So much trouble .
In the figure ,city and income Is the parameter required by the interface ,Insurance_ability and score Is the expected return value , Of course, it can also be different from the parameter name returned by the interface .
postman When reading data in , The table name will be regarded as data. So when reading data , For example, reading city The data in this column , Then write as data.city.postman According to data.city Read the data until the data is empty .
It should be noted that : Use excel Saved data , Please save as csv Format , And use Notepad++ Convert it to utf-8 The format of , Otherwise, in the postman Chinese recognition is a garbled format , The judgment of data leads to mistakes .
2、postman Parameter setting
In this interface , The parameters we need to parameterize are city and income, For these two parameters , Use { {}} Include .
3、 Before the request is sent , Parameter setting
We need to parameterize the data in the table , Before sending the request , We're going to let postman Can read the data in the file , stay postman in ,Pre-request Script The statement in postman Will be executed before the request is sent , So the operation of reading statements , Let's put it here .
Code statement to read .
var city = data.city;
var income =data.income;
4、 stay Tests To judge
The fourth step should be the most important operation , Now we have read the data of the file before sending the request , So how to judge ? Here we are Tests In the middle of ,Tests Will be executed after the request ,Tests Also known as assertion .
How to judge whether the returned data is correct is :
1、 Set the expected result in the file to the environment variable
2、 Get the returned data
3、 Judge
var score=(data.score);// Get the data in the file
var Insurance_ability=(data.Insurance_ability);// Set to environment variable
pm.environment.set("score",score);
pm.environment.set("Insurance_ability",Insurance_ability);
if(tests["code is 200"]=responseCode.code===200){ //[postman Assert that the output , return 200 Print code is 200
var d = JSON.parse(responseBody); // Parse the returned data into json Format
if( d. score ==score&&d. Insurance capacity ==Insurance_ability){ // Compare the returned data with the environment variables , If both
var a=1; // because pm.test Statement contains function() The setting meets the conditions a=1,
pm.test(" The test passed ",function(){ //if It's true in the test , Assert that the input test passes
if(a==1);
});
}
else{
var a=0;
pm.test(" The test failed ",function(){
if(a===0);
});
}
}else if(tests["code is 500"]=responseCode.code===500){// Status as 500 Assert output
}else{
tests["code is 400"]=responseCode.code===400 // Status as 400 Assert output
}
5、 Parameterized execution
After the above work preparation , We can start formal parameterization
1、 Click on Runner
2、 Interface selection , Environmental preparation , Select File
3、 Click on Run, Start execution
4、 Check the execution results
After the data runs , We can see the results directly on the page , among pass and failed It's code tests The number of interruptions passed , among , We can see that the test passed , and code is 200 A hint of ,
We see failed The number of 1, We found the request
notice coed is 200 Status as FALL,coed is 500 Status as pass, It can be judged that the request status code is 500
At this point, you can view the request address and return parameters of the request , Then compare the data , Check the specific error .
Open the request address and return content , We can see that we passed the wrong parameters , The reason should be that this row of data in my table is empty , So he passed it directly { {ciry}} and { {income}},
summary
That's how to use postman The left and right process of judging whether the return result is correct , If there is anything bad written , In the .
besides , Also encountered problems , For example, when there is a large amount of data , Then compare the results , It will be more troublesome , also tests The output in is just an assertion output , It is impossible to judge how many use cases fail through the passing or failure of the operation , So this is something that needs to be studied .
You can also use the tests The various operations and printing in enable you to determine where the data is by judging the output .
to update
I wrote an hour's update , Click Google control+s, Page collapse , Xiaobian is helpless , Can only rewrite .
Previously, we have achieved a basic judgment on the expected data and the returned data , But we can't simply see how many test case data have passed from the running results , Not many test case data passed , And it's still troublesome to find the wrong data .
Look up the data and find , in the light of tests sentence , We can set his result , Is to set whether to pass or not , So our new idea is :
1、 Judge the expected result and the returned result
2、 If equal, set tests Statement for true
3、 If the judgment is not equal, set tests Statement for false, Failure , And print parameters 、 Expected results 、 The actual result , In this way, we briefly start from runner The operation interface knows that our data is wrong , You don't have to spend a lot of time looking for those data errors .
The statement is as follows :
tests[" The test passed "]=true; // Set to true, Runtime means pass
tests[" The test failed "]=false; // Set to false, Runtime means fail
The sentences to realize the whole judgment are as follows :
var city = data.city;
var income =data.income;
var score=(data.score);
var Insurance_ability=(data.Insurance_ability);
pm.environment.set("score",score);
pm.environment.set("Insurance_ability",Insurance_ability);
var d = JSON.parse(responseBody);
if(d. score ==score&&d. Insurance capacity ==Insurance_ability){
tests[" The test passed "]=true;
}else{
tests[" The test failed "+"( Input parameters "+city+'、'+income+") Expected results ( score ="+score+"、 Insurance capacity "+Insurance_ability+")( Actual result score ="+d. score +"、 Insurance capacity ="+d. Insurance capacity +')']=false;
}
Pictured , In the data table , There is 19 A use case , adopt 17 individual , Two failures , And for failed use cases , You can clearly see the parameters 、 Expected results and returned results .
If there are many data , We can run the red square of the result page directly ( Failure area ) The displayed use case finds the failed data .
Code update :
For interface problems , It is briefly divided into three situations , Server problem 、 Client issues 、 data verification , So I updated the validation code
var state=responseCode.code;// Get the return status
var number=(state.toString()).substr(0,1);// Will return number Type to string type , And get the first
switch(number){
case '2':
test();
break;
case '4':
clientQue(); //4 The state at the beginning , It is simply defined as a client problem
break;
case '5':
serverQue(); //5 The state at the beginning , Simply defined as a server problem
break;
default:
tests[' The test failed , state ='+state]=false; // In case of other circumstances , Print status , And fail the test
break;
}
function test(){ // Status as 200 Executed function
var city = data.city;
var income =data.income;
var score=(data.score); // You can use request.url obtain url, Parse parameter fields
var Insurance_ability=(data.Insurance_ability);
var result = JSON.parse(responseBody);
if(result. score ==score&&result. Insurance capacity ==Insurance_ability){
tests[" The test passed "]=true;
}else{
tests[" Test to fail "+"( Input parameters "+city+'、'+income+") Expected results ( score ="+score+"、 Insurance capacity "+Insurance_ability+")( Actual result score ="+result. score +"、 Insurance capacity ="+result. Insurance capacity +')']=false;
}
}
// Client issues
function clientQue(){
tests[' Client issues ( Request parameter or method error )--- Test to fail --- Status code for '+state+' requestURl by '+request.url]=false;
}
// Server or gateway problems
function serverQue(){
tests[' Server or gateway problems --- Test to fail --- Status code for '+state+' requestURl by '+request.url]=false;
}
Through the above knowledge , We can solve most problems , If you want to go further , Need certain js Basics
边栏推荐
- C# 初始化程序时查看初始化到哪里了示例
- MCU与MPU的区别
- 网上可以开炒股账户吗安全吗
- ORM model -- associated fields, abstract model classes
- Integer inversion
- Performance optimization record of the company's product "yunzhujia"
- Please ask me a question. I started a synchronization task with SQL client. From Mysql to ADB, the historical data has been synchronized normally
- 使用BigDecimal的坑
- request对象对请求体,请求头参数的解析
- Codeforces - 1324d pair of topics
猜你喜欢
随机推荐
Why are social portals rarely provided in real estate o2o applications?
STM32基础知识—内存映射
ORM -- database addition, deletion, modification and query operation logic
ISP、IAP、ICP、JTAG、SWD的编程特点
The Himalaya web version will pop up after each pause. It is recommended to download the client solution
Postman interface test II
嵌入式背景知识-芯片
使用BigDecimal的坑
Introduction to uboot
Enterprise practice | construction of banking operation and maintenance index system under complex business relations
Garbage disposal method based on the separation of smart city and storage and living digital home mode
ORM--查询类型,关联查询
Selenium+bs4 parsing +mysql capturing BiliBili Tarot data
终于可以一行代码也不用改了!ShardingSphere 原生驱动问世
Analyze Android event distribution mechanism according to popular interview questions (II) -- event conflict analysis and handling
Application of C # XML
Can't connect to MySQL server on '(10060) solution summary
14th test
ES6中的原型对象
Postman interface test V