Postman interface test seven

table of Contents

Postman common test results verification and usage skills


Postman common test results verification and usage skills

Postman's test is essentially JavaScript code. Through our writing test code, each test returns True or False.
Each test is actually a test case

The official document gives a lot of verification methods, we learn through examples

The interface returns the result as json

{
  "status": 301,
  "message": "购买商品库存不足",
  "lists": [11]
}
  • 1

  • 2

  • 3

  • 4

  • 5

1. Check whether the response body contains a string

tests["测试点"] = responseBody.has("需要查找的字符串");
  • 1

Example:

tests["status code"] = responseBody.has("301");
tests["status是否存在"] = responseBody.has("status");
tests["lists是否存在"] = responseBody.has("lists");
tests["lists值为11"] = responseBody.has("11");
  • 1

  • 2

  • 3

  • 4

Note: When the value in json is integer, the value to be searched can be without double quotes,
tests["xxx"]xxx represents the name of your test point, which can be Chinese
tests["xxx"]xxx in a script If it appears multiple times, then only execute the first one, so try not to repeat it.
When the value is equal to a Chinese string, this method does not seem to be very useful, but we have other methods to verify.

2. Check whether the Response Body is equal to the string

tests["测试点"] = responseBody === "Response Body返回的内容";
  • 1

This can be used when the interface returns a pure string to directly check the correctness of the entire returned result.
Example:
interface return: haha

tests["返回为哈哈"] = responseBody === "哈哈";
tests["返回为哈哈"] = responseBody === "哈";
  • 1

  • 2

The second one will return False and must match exactly

3. Check the corresponding time

tests["Response time 小于200毫秒"] = responseTime < 200;
tests["Response time 大于200毫秒"] = responseTime > 200;
  • 1

  • 2

4. Check the status code

This is easy to understand, is the http request status code

tests["Status code is 200"] = responseCode.code === 200;
  • 1

Note:
The status code here is not the same as the "status" in the json we used above

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

My understanding of this is to check the string corresponding to the HTTP code. For example, the list given below is the
corresponding table below. If you use fiddler to simulate the corresponding return, pay attention to the case of the fiddler return. There is a problem with the string
1 message (1 word Head)
▪ 100 Continue
2 Success (head 2)
▪ 200 OK
3 Redirect (head 3)
▪ 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 (some omitted)

6. Set environment variables/global variables

pm.environmentVariable.set("key", "value");
pm.globalVariable.set("key", "value");
  • 1

  • 2

7. Convert the XML body into a JSON object:

var jsonObject = xml2Json(responseBody);
  • 1

8. Check the value of json

var jsonData = JSON.parse(responseBody);tests["Your test name"] = jsonData.value === 100;
还拿上面的json数据做测试
tests["状态码为301"] = jsonData["status"] == "301";
tests["message"] = jsonData["message"] == "购买商品库存不足";
tests["list"] = jsonData["lists"][0] == "11";
  • 1

  • 2

  • 3

  • 4

  • 5

9. Check that there is information

tests["Content-Type is present"] = postman.getResponseHeader("content-Type");//不区分大小写
tests["Content-Type is present"] = responseHeaders.hasOwnProperty("Content-Type");//区分大小写
  • 1

  • 2

10.POST request status code

tests["Successful POST request"] = responseCode.code === 201 || responseCode.code === 202;
201 - Created 服务器已经创建了文档,Location头给出了它的URL。
202 - Accepted 已经接受请求,但处理尚未完成。
  • 1

  • 2

  • 3

The official document also gives a verification example for json.
This is a specification that defines the JSON data structure based on the JSON format, we call it

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 are test data, and the schema is equivalent to verifying the json specification. In the
example, it is verified whether the values ​​in data1 and data2 are all boolean types.

First understand the keywords commonly used in writing json specification documents

Keyword description
$schema The status of the $schema keyword indicates that this mode is consistent with the v4 specification draft.
title Use it to provide a title to our pattern.
description A description of the pattern.
type The type keyword defines the first constraint on our JSON data: it must be a JSON object.
properties Define various keys and their value types, as well as the minimum and maximum values ​​used in the JSON file.
required Store the list of necessary attributes.
minimum The constraint condition set for the value indicates the minimum acceptable value.
exclusiveMinimum If "exclusiveMinimum" exists and has a boolean value of true, the instance is valid if it is strictly greater than the value of "minimum".
maximum The constraint condition set for the value indicates the maximum acceptable value.
exclusiveMaximum If "exclusiveMinimum" exists and has the boolean value true, the instance is valid if it is strictly less than the value of "maximum".
multipleOf If the result of dividing the instance by the value of this key is a number, it means that the number instance immediately adjacent to "multipleOf" is valid.
maxLength The maximum length value of a character string instance.
minLength The minimum length value of a character string instance.
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": "检查list值",
                "id": "",
                "title": "",
                "type": "integer"
            },
            "type": "array"
        },
        "message": {
            "default": "购买商品库存不足",
            "description": "message信息",
            "id": "",
            "title": "",
            "type": "string"
        },
        "status": {
            "default": 301,
            "description": "返回状态值",
            "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 verification specification
can delete some keys according to the actual situation, but the red mark should keep the
default default value, and write according to the actual situation. The status code of the above example "when the product is insufficient in inventory" is 301. If you want to check the status and message The value of is verified, then default can be added. If it is only verified that the returned value is of integer or string type, it can be ignored. You can
also add restrictions such as maximum and minimum values.

Below is the test code

var jsonData = JSON.parse(responseBody);

var schema = {
  "properties": {
    "lists": {
      "items": {
        "default": 11,
        "description": "库存不足的商品id",
        "type": "integer"
      },
      "type": "array"
    },
    "message": {
      "default": "购买商品库存不足",
      "description": "id为11的商品库存不足",
      "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格式验证"] = tv4.validate(jsonData, schema); //验证json格式
tests["返回状态码是200"] = responseCode.code === 200;
tests["状态码为301"] = jsonData["status"] == "301"; 
tests["message"] = jsonData["message"] == "购买商品库存不足";
tests["list"] = jsonData["lists"][0] == "11";
  • 1

  • 2

  • 3

  • 4

  • 5

In this way, we can verify the json structure and data returned by the interface.

tv4 is an external library introduced by Postman. If you want to know about it, you can read the official documents.
In addition, Postman also provides some methods such as:

responseCookies
request.data["key"]=="value"
request.headers["key"]=="value"
request.method
request.url
request
responseHeaders
responseBody
responseTime
responseCode 包含code,name,detail
iteration
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

These methods can help us do more things, such as getting the cookie value through an interface, and then setting the cookie as a global variable and providing it to other interfaces.

When we write test scripts, we may encounter script writing errors or need some logs to help us improve the script.
We can open View->Show Postman Console. After opening, we can use console.log(xxx) to output logs and View error message

For an interface, when we know the parameters and the results corresponding to the parameters, we can judge by postman to verify whether the returned data is equal to the expected data. This can make our interface test more convenient and concise.

 

1. Prepare the data.

 

 The file format that postman can accept is shown in the figure. Generally speaking, the data we need to parameterize can be stored in the excel table. As shown in the figure below, when postman reads the data, it reads according to the column name in the first row. In excel, multiple parameters can be separated by commas, which is not as troublesome as txt.

 

In the figure, city and income are the parameters required by the interface, and Insurance_ability and score are the expected return values. Of course, they may not correspond to the parameter names returned by the interface.

 

When reading data in postman, the table name is assumed to be data by default. So when reading data, such as reading the data in the city column, write it as data.city. Postman will read the data according to the data.city reading method until the data is empty.

 

It should be noted that: the data saved in excel, please save it as csv format when saving, and use Notepad++ to convert it to utf-8 format, otherwise it will be recognized in postman as a garbled format, which will cause errors in the judgment of the data.

 

2. Postman parameter settings

In this interface, the parameters we need to parameterize are city and income. For these two parameters, use { {}} to include.

 

3. Before sending the request, set the parameters

We need to parameterize the data in the table. Before sending the request, we need to enable postman to read the data in the file. In postman, the statement postman in the Pre-request Script will be executed before the request is sent. So the operation of reading the statement, we put it here for execution.

The code statement is read.

 

var city = data.city;

var income =data.income;

4. Perform judgment operations in Tests

The fourth step should be the most important operation. Now that we have read the file data before sending the request, how do we judge it? We perform this step in Tests. Tests will be executed after the request. Tests are also called assertions.

 

The thinking on how to judge whether the returned data is correct is:

 

1. Set the expected result in the file as an environment variable

 

2. Get the returned data

 

3. Make judgments

 

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 asserts output, returns 200 and prints code is 200

    var d = JSON.parse(responseBody); //Parse the returned data into json format

if( d. score==score&&d. insurance capability==Insurance_ability){ //Compare the returned data with environmental variables, if both are satisfied

    var a=1; //Because the pm.test statement contains function () setting to meet the conditions is a=1,

    pm.test("Test passed",function(){ //if judged to be true, then assert that the input test passed

        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){//Assertion output when the status is 500

    

}else{

    tests["code is 400"]=responseCode.code===400 //Assertion output when the status is 400

}

5. Parameterized execution

After the preparation of the above work is completed, we can start the formal parameterized execution

 

1. Click Runner

 

 

2. Interface selection, environment preparation, and file selection

 

 

3. Click Run to start execution

 

4. Check the execution result

After the data is run, we can see the results directly on the page, where pass and failed are the number of assertions passed by the code tests. Among them, we can see the test passed and the code is 200 prompt.

 

We see that the number of failed is 1, we find the request

Seeing that the status of coed is 200 is FALL and the status of coed is 500 is pass, it can be judged that the status code of the request is 500

 

At this point, you can view the request address and return parameters of the request, and then compare the data to see where the error is.

Open the request address and return content, you can see that we passed the parameters incorrectly. The reason should be that the row of data in my form is empty, so he directly passed { {ciry}} and { {income}},

 

to sum up

The above is how to use postman to determine whether the returned result is correct. If there is any bad writing, please advise.

 

In addition, there are also problems. For example, when the amount of data is large, it will be more troublesome to compare the results, and the output in the tests is only an assertion output, and it is impossible to judge how many pass or fail the run. The use case failed, so this one needs to be studied.

 

You can also use various operations and printing in the tests to make yourself able to judge where the data is the problem by judging the output.

 

Update

I wrote an hour’s update. I clicked Google’s control+s and the page collapsed. I was helpless and could only rewrite it.

 

Previously, we have implemented a basic judgment on the expected data and the returned data, but it is still very difficult to see how many test case data has passed, how many test case data have not passed, and it is still very difficult to find the wrong data from the running results. trouble.

 

Looking at the data, we found that for the tests statement, we can set his results, that is, set pass or fail, so our new idea is:

 

1. Judge the expected results and returned results

 

2. If the judgment is equal, set the tests statement to true

 

3. If the judgment is not equal, set the tests statement to false, that is, fail, and print the parameters, expected results, and actual results, so that we can know that our data is incorrect from the runner running interface, so we don't need to spend a lot of time to find those data errors. .

 

The statement is as follows:

 

tests["test passed"]=true; //Set to true, it means pass at runtime

tests["The test failed"]=false; //Set to false, it means fail when running

The sentence to realize the whole judgment is 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 ability==Insurance_ability){

        tests["test passed"]=true;

    }else{

        tests["Test failed"+"(input parameters "+city+','+income+") Expected result (score="+score+", insurance capability"+Insurance_ability+") (actual result score="+d.score+ ", insurance capability="+d. insurance capability+')']=false;

        }

As shown in the figure, in the data table, there are 19 use cases, 17 passed and two failed. For the failed use cases, you can clearly see the parameters, expected results, and return results.

 

 

If there is a lot of data, we can directly find the failed data through the use case displayed in the red box (failure area) on the running result page.

 

 

Code update:

 

In view of the problems in the interface, it is briefly divided into three situations, server problems, client problems, and data verification, so the verification code has been updated.

 

var state=responseCode.code;//Get the return status

var number=(state.toString()).substr(0,1);//Convert the returned number type to string type and get the first place

switch(number){

case '2':

    test();

    break;

case '4':

    clientQue(); //The state at the beginning of 4 is simply defined as a client problem

    break;

case '5':

    serverQue(); //The status at the beginning of 5 is simply defined as a server problem

    break;

default:

    tests['test failed, status='+state]=false; //If there are other situations, print the status, and the test fails

    break;

}

 

function test(){ //A function executed with a status of 200

var city = data.city;

var income =data.income;

var score=(data.score); //request can be used. url get url, parse parameter field

var Insurance_ability=(data.Insurance_ability);

 

var result = JSON.parse(responseBody);

 if(result.score==score&&result. insurance ability==Insurance_ability){

        tests["test passed"]=true;

    }else{

        tests["Test failed"+"(input parameters "+city+','+income+") expected result (score="+score+", insurance capability"+Insurance_ability+") (actual result score="+result.score+" 、Insurance capability="+result.Insurance capability+')']=false;

       

        }

}

 

//Client issue

function clientQue(){

    tests['Client problem (request parameter or method error)---Test failed---status code is'+state+' requestURl is'+request.url]=false;

}

 

//Server or gateway problem

function serverQue(){

    tests['Server or gateway problem---test failed---status code is'+state+' requestURl is'+request.url]=false;

}

 

Through the above knowledge, we can solve most of the problems, if we want to go further, we need a certain js foundation

Guess you like

Origin blog.csdn.net/weixin_37018468/article/details/106193514