This is the 10th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Background: I joined an Internet company in P2P industry in 2017, and was introduced by the leader to use Postman for interface test. I am used to using JMeter for interface test. Of course, I have heard of this tool, which is often used by developers to debug interfaces. At that time, however, most of my colleagues used Postman’s limited functionality. For example, they did not implement the Integrated Automation environment (Newman), did not purchase the paid version of its interface for performance testing, and only used the Collections function. For example, if the next interface requests the token that the previous interface responds to, the interface can only request once, obtain the token value, copy the returned token, and add it to the request parameters of the next interface to complete the interface test. This is inconvenient, resulting in low efficiency. To this end, spend some time to learn to use Postman interface testing, only to have to solve the following technical points, of course, also inevitable Baidu some time.

  • Tool introduction: users need some methods to track web requests when developers debug network programs or web B/S mode programs. Users can use some network monitoring tools such as Firebug and other web debugging tools. This web page debugging tool can not only debug simple CSS, HTML, script and other simple web page basic information, it can also send almost all types of HTTP requests!

1. Postman is one of the best Chrome plug-ins in the world when it comes to sending HTTP requests to the web. Chromecj.com/web-develop… The official address of the download page is www.getpostman.com/

2. How to test the postman interface? The format and filling method are shown in the figure below:

3, interface automation test, how to do? Postman provides a Collections collection, which allows you to string multiple interface scripts into a business scenario and place them in a specific folder. You can run the entire interface at a time, that is, a business scenario.

4. As mentioned above, there is a problem. In the same environment, some operations need to obtain the token before the next operation? This is where the correlation technology is used, which is commonly called correlation, as Loadrunner has correlation functions (web_reg_save_param_ex), JMeter has post-processor (regular expression, JSON extractor, xpath), and so on.

5. Postman provides environment variables, including automatically defined environment variables and global variables. User-defined environment Variable Name: URL, Variable Name: Variable Name, and Variable Value: Variable Value

Global variables, such as the header information of the interface request, can be set:

The variable is referenced in double curly braces: {{}}. The url address can be written as {{URL}}/login

6. Tests above can be written into scripts.

var jsonData = JSON.parse(responseBody); // Obtain the response packet in JSON format

postman.setEnvironmentVariable("token", jsonData.data.result.token); / / set the environment variable token, value of jsonData. Data. The result. The token

tests\["token"\]=jsonData.data.result.token; // Return the token parameter in the response packet

tests\["Body matches string"\] = responseBody.has("Bi Caiwu"); // assert test Whether the result of the response packet is included
Copy the code

Tips: jsonData var to define a variable, the token variable, jsonData. Data. The result. The token, this value is the json data level 1 level go down,

7. For example, in the scenario where the user logs in, obtains the token token, and then the purchase interface uses the token token returned by the login, the two interfaces are placed in the same Collections folder.

  • The first login interface, set tests– environment variable to set the token value of the response,
  • In the second purchasing interface, the {{token}} parameter refers to the environment variable and performs the purchasing operation.

The right side of the figure shows the results of tests. Only tests that pass the validation are displayed. To know whether the validation assertion is correct, you can only look at the background log.

8. In this way, the associated action of the two interfaces is completed. There is no need to run a login interface to obtain the token and then add the purchase interface to input the token.

Tips: Delay is measured in milliseconds.

9. Postman can complete the API automation interface test with the powerful function of postman.

// Check whether 'user\_id' exists
tests\["Body contains user\_id"\] = responseBody.has("user\_id");
if(tests\["Body contains user\_id"\]) {// Parse the returned information into objects
var responseData = JSON.parse(responseBody); 
tests\["value\_user\_id"\]=responseData.token.user\_id / / set the global variable postman. SetGlobalVariable (" user \ _id ", tests \ [" value \ _user \ _id "\]);
}
else{ 
Globals \["test\_user\_id"\] is a constant value predefined by me in \ 'pre-request Script\'
postman.setGlobalVariable("user\_id",globals\["test\_user\_id"\]);
}
Copy the code

10. Install The Postman command line to run the tool Newman on Linux. Command line to run the interface collection: first download the collection just created, click export, and save to the specified path;

11. Popularize a Postman pre-Request Script function to create environment and global variables.

As shown below, tests can detect whether the value of a variable is referenced; Strings in double quotes:

Click the eye in the upper right corner of Postman and you can see that the script for the preset request has written in global and environment variables.

12. Multiple API requests need to be associated with the value returned by the previous API request response. Set environment variables after the request is initiated using the same method as setting environment variables before the request is initiated:

postman.setEnvironmentVariable("key"."value");
postman.setGlobalVariable("key"."value");
// The former is an environment variable and the latter is a global variable, which can be set to API variables before and after the request
Copy the code

The random number

PostMan provides three random numbers in addition to environment and global variables.

{{$guid}}

: Add a V4 style GUID

{{$timestamp}}

: Sets the current timestamp to seconds

{{$randomInt}}

: Adds a random integer between 0 and 1000

Built-in script description:

  1. Clear a global variable

The corresponding script: postman. ClearGlobalVariable (" variable \ _key ");

Parameter: Key of the variable to be cleared

2. Clear an environment variable

The corresponding script: postman. ClearEnvironmentVariable (" variable \ _key ");

Parameter: Key of the environment variable to be cleared

Response body:Contains string

Tests \[“Body matches string”\] = responsebody. has(“string\_you\_want\_to\_search”); Parameter: Expected content

4. Convert response in XML format to SON format Response Body :Convert XML body to a JSON Object

Var jsonObject \= xml2Json(responseBody);

Parameters :(default no parameters need to be set, for the interface response) the XML to be transformed

Response body:Is equal to a string

Tests \["Body is correct"\] = responseBody === "response\_body\_string";

Parameter: expected Response

6. Json parses the key value for verification Response Body :JSON value check

["Args key contains argument passed as URL parameter"\] = 'test' in responsejson.args

Parameters: test replaces the value under test, args replaces the key under test

7. Check whether response headers: Content-type header check contains the tested field

The corresponding script: tests \ [" the content-type is the present "\] = postman. GetResponseHeader (" the content-type");

Parameter: expected header

8. Response time Response time is less than 200ms

Test \["Response time is less than 200ms"\] = responseTime < 200;

Parameter: Response time

9. Set an global variable

The corresponding script: postman. SetGlobalVariable (" variable \ _key ", "variable \ _value");

Parameter: the key value of the global variable

10. Set an environment variable

The corresponding script: postman. The setEnvironmentVariable (" variable \ _key ", "variable \ _value");

Parameter: The key value of the environment variable

11. Determine the Status code:Code is 200

Test \["Status code is 200"\] = responsecode.code! = 400;

Parameter: status code

12. Check whether code name contains any content. Status code:Code name has string

Tests \["Status code name has string"\] = responsecode.name.has ("Created");

Parameter: Code name is expected to contain a string

13. Status code:Successful POST request is obtained

The corresponding script: tests \ [" Successful POST request "\] = responseCode. Code = = = 201 | | responseCode. Code = = = 202;

Use Tiny Validator 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); ‘parameters: You can modify the key-value pair in items to match the parameters of the validation JSON