“This is the fifth day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.
Background: I joined an Internet company in p2p industry in 2017, and was introduced by the leader to use Postman for interface testing. I used to use JMeter for interface testing. Of course, I have heard of this tool, which is often used by developers to debug interfaces. However, most of my colleagues at that time used Postman for limited functions, such as not implementing Newman, not purchasing interface listeners for performance testing in its paid version, and only using the Collections function. However, there was a drawback that made it inconvenient to make interfaces, namely, the correlation between the two interfaces. For example, if the next interface requests the token from the previous interface, you can only request the token once to obtain the token value, copy the returned token, and add the token to the request parameters of the next interface to complete the interface test. This is inconvenient, resulting in low efficiency. To this end, I spent some time learning to use Postman to do interface testing, only to solve the following technical points, of course, also unavoidable Baidu some.
- Tool introduction: users in the developer debugging network program or web B/S mode of the program is the need for some methods to track web requests, users can use some network monitoring tools such as the famous Firebug and other web debugging tools. Today we introduce this web debugging tool can not only debug simple CSS, HTML, scripts and other simple basic information of the web page, it can also send almost all types of HTTP requests!
1. Postman is one of the representative products in the Chrome plugin class for sending WEB HTTP requests. Chromecj.com/web-develop… Download page official address: www.getpostman.com/
Postman interface test tool is not described here, how to do interface test? Its format and filling method are as shown in the figure:
3, interface automation test, how to do? Postman provides a Collections collection capability that can string multiple interface scripts together into a single business scenario, put them in a specified folder, and run the entire interface, i.e. one business scenario, at a time.
4, As mentioned above, there is a problem. In the same environment, some operations need to obtain token before the next operation. Associative techniques, commonly known as associative, are used here, as Loadrunner has associative functions (web_reg_SAVe_param_ex), Jmeter has post-processor (regular expressions, JSON extractors, xpath), etc.
Postman provides environment variables, including automatically defined environment variables and global variables. User-defined environment Variable Name: URL, Variable Name, Variable Value: Variable Value
Global variables, such as header information, can be set for interface requests:
Variable reference mode In double curly braces: {{}}, the URL address can be written as {{URL}}/login
6. The above tests can be written to scripts.
var jsonData = JSON.parse(responseBody); // Get 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; // Verify that the token parameter is returned in the response packet
tests\["Body matches string"\] = responseBody.has("Bi Caiwu"); // Assert whether test contains the result of the response packet
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, scenario: A user logs in to the system to obtain a token, and then purchases the interface using the token returned by login. In this case, the two interfaces are in the same Collections folder.
- For the first login interface, set tests– the environment variable that sets the token value for the response,
- The second purchase interface, pass the parameter {{token}} reference environment variables, purchase operation.
The tests validation results are shown on the right side of the image above. Only the tests that passed are validated. To see if the validation assertion is correct, you can only look at the background log.
8. In this way, the association of the two interfaces is completed. There is no need to run a login interface first, obtain the token, and then add the purchase interface input token.
Tips: Delay is in milliseconds.
9, the follow-up postman powerful function, can complete THE API automation interface test.
// Check whether the value '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 in \ 'pre-request Script\'
postman.setGlobalVariable("user\_id",globals\["test\_user\_id"\]);
}
Copy the code
10. Install Newman on the Postman command line for Linux. Command line run interface collection: first download the collection created just now, click Export, and save to the specified path;
Add a postman pre-request script to create environment variables and global variables.
As shown in the figure below, tests can check whether the values of variables are referenced. String in double quotes:
Click on the eye in the upper right corner of Postman to see that the script for the preset request has written global and environment variables into it.
12. Multiple API requests need to be associated with the value returned by the last API request response, setting environment variables after the request is initiated, and setting environment variables before the request is initiated using the same method:
postman.setEnvironmentVariable("key"."value");
postman.setGlobalVariable("key"."value");
// The former are environment variables and the latter are global variables that 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}}
: Adds a V4 style GUID
{{$timestamp}}
: Stamps the current time to seconds
{{$randomInt}}
: Adds a random integer between 0 and 1000
Built-in script description:
- 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
3. Response Contains content Response Body :Contains string
Tests [“Body matches String “\] = responsebody. has(“string\_you\_want\_to\_search”); Parameter: Expected content
4. Convert XML response to SON response body:Convert XML body to a JSON Object
Var jsonObject \= xml2Json(responseBody);
Parameter :(no parameter required by default, response of the interface) 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 to verify Response Body :JSON value check
Tests \["Args key contains argument passed as URL parameter"\] = 'test' in responsejson.args
Parameters: test replaces the measured value, and args replaces the measured key
7. Check whether the response headers: Content-type header check field exists
The corresponding script: tests \ [" the content-type is the present "\] = postman. GetResponseHeader (" the content-type");
Parameter: Expected header
8. The Response time is less than 200ms
Tests \["Response time is less than 200ms"\] = responseTime < 200;
Parameter: response time
9. Set a global variable
The corresponding script: postman. SetGlobalVariable (" variable \ _key ", "variable \ _value");
Parameter: the key value of a 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. Check the Status code Status code:Code is 200
Tests \["Status code is 200"\] = responsecode.code! = 400;
Parameter: Status code
12. Check whether the code name contains 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
Status code:Successful Post request
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 pairs in items to validate json parameters