Basic use of Postman
1. Introduction to common functions
1.1 Postman page overview
The version used in the picture below is Postman v9.31.27. The Postman pages of different versions may be slightly different, but the basic usage remains the same. Take this version as an example to summarize the commonly used functions.
1.2 Editing of interface requests
Enter the selected workspace (if it does not exist, you need to create it), and then add a collection to the current workspace. The concept of collections in Postman is similar to the project in Eclipse. You can add folders under the collection. Folders at different levels can create subfolders, and folders are used to manage different functional modules or interface use cases in the project.
(1) Functions and functions of the interface editing area
(2) Script editing
It is mainly used for pre-request scripts (Pre-request Script, equivalent to setUp() in automation) and post-response assertions (Test Script, equivalent to teardown() and assertions in automation), written in JavaScript. It should be noted that Pre-request Script and Test script are available in Collection, Folder, and API, as shown below:
Script execution order
The execution sequence of scripts at different levels is as follows:
variable scope
If there is a data-driven file, pay attention to the scope of the variables:
Global variables: Global variables enable testers to access data between collections, requests, test scripts, and environments. Global variables are available throughout the workspace. Since global variables have the widest scope in Postman, they are ideal for testing and prototyping. In later stages of development, use more specific scopes.
Collection variables: Collection variables are available in all requests in the collection and are independent of the environment. Collection variables do not change based on the selected environment. Collection variables are appropriate if the tester is working with a single environment, such as for authentication or URL details.
Environment variables: Environment variables enable testers to extend their work scope to different environments, such as local development and testing or production. One environment can be active at a time. If the tester has a separate environment, it might be more efficient to use a collection variable, but the environment allows the tester to specify role-based access levels.
Data variables: Data variables come from external CSV and JSON files and are used to define when using Newman
or < a i=3>A data set that can be used when running the collection. Data variables have current values that do not persist after the request or collection runs. Collection Runner
Local variables: Local variables are temporary variables accessed in the request script. Local variable values are scoped to a single request or collection run and are no longer available after the run completes. Local variables are appropriate if the tester needs a value that covers all other variable scopes but does not want the value to persist after execution ends.
Pre-request script example:
Background: In the vue_shop project, all interface operations need to log in to the administrator account admin first, and obtain token authentication before the operation can be successful. At this time, it can be usedInterface association. That is:
Add a Pre-request script to obtain the administrator token in the Collection, and set the obtained token as a Collection-level variable. After that, all interfaces in this Collection can directly obtain this value from the Collection-level token variable.
code show as below:
// 获取token, 避免后续需在请求头中身份认证的接口重复填充Authorization
const LoginRequest = {
url: 'http://127.0.0.1:8888/api/private/v1/login',
method: 'POST',
header: 'Content-Type:application/json',
body: {
mode: 'raw',
raw: JSON.stringify({
"username": 'admin',"password":"123456" })
}
};
pm.sendRequest(LoginRequest, function (err, res) {
console.log(err ? err : res.json());
// slice(7)是因为响应的token的值是 Bearer eyJhbGciOiJI...,
// Postman在设置Authorization时会自动填充Bearer,截取token[7:]
var token = res.json().data.token.slice(7);
pm.collectionVariables.set("token", token);
});
Then follow the steps below to achieve interface association:
Test script example:
// 用于响应后断言
pm.test("校验登录成功", function () {
var jsonData = pm.response.json();
var msg = jsonData.meta.msg;
pm.expect(msg).to.eql("登录成功");
});
pm.test("校验登录名为admin", function () {
var jsonData = pm.response.json();
var username = jsonData.data.username;
// var expection = data.username;
pm.expect(username).to.eql("admin");
});
pm.test("校验登录账号的电话号码为12345678", function () {
var jsonData = pm.response.json();
var mobile = jsonData.data.mobile;
pm.expect(mobile).to.eql("12345678");
});
pm.test("校验登录账号的邮箱地址为[email protected]", function () {
var jsonData = pm.response.json();
var email = jsonData.data.email;
pm.expect(email).to.eql("[email protected]");
});
All four set checkpoints passed, and the running results are as follows:
Script help
In Postman, use the shortcut method on the right when writing a script. Click to automatically generate:
Or on the Postman official website, learn about examples of common assertion methods and use them after becoming familiar with them. The official document link is:
https://learning.postman.com/docs/writing-scripts/script-references/test-examples/, if this link fails, you can enter as follows
Examples of using dynamic variables are as follows:
(3) API test encryption and decryption functions
hash function
// 导入加密包 crypto-js
var CryptoJS = require("crypto-js");
// 散列函数
CryptoJS.MD5('待加密的字符串') //返回WordArray对象
Encryption and decryption functions
The reference here is from the link: https://www.cnblogs.com/huiguo/p/16601076.html.
The encryption function parameters are: (plain text string, key string, optional parameter object), and returns the cipher text string.
Consolidated function existsCryptojs.AES.encrypt
, Cryptojs.DES.encryp
, Cryptojs.Rabbit.encrypt
, Cryptojs.RC4.encrypt
, Cryptojs.TripleDES.encrypt
,
The most commonly used isCryptojs.AES.encrypt
.
The parameters of the decryption function are: (ciphertext string, key string, optional parameter object), and the returned result must be .toString(CryptoJS.enc.Utf8)
Convert to plaintext, because the ciphertext obtained after encryption is not a string, it is an CipherParams
object.
The decryption function is: CryptoJS.AES.decrypt
, CryptoJS.DES.decrypt
, CryptoJS.Rabbit.decrypt
, CryptoJS.RC4.decrypt
,CryptoJS.TripleDES.decrypt
,
The most commonly used is CryptoJS.AES.decrypt
.
Among them, the common properties of optional parameter objects are:
mode
: Encryption mode [CBC ECB CFB OFB CTRGladman (CTR)], the default is CBCpaddig
:Padding method [NoPadding ZeroPadding Pkcs7(Pkcs5) Iso10126 Iso97971 AnsiX923], the default is Pkcs7(Pkcs5)vi
: Offset vectorformatter
: Custom format
// 导入加密包 crypto-js
var CryptoJS = require("crypto-js");
// 设置密钥
var key = CryptoJS.enc.Hex.parse("000102030405060708090a0b0c0d0e0f");
// 设置偏移量
var iv = CryptoJS.enc.Hex.parse("101112131415161718191a1b1c1d1e1f");
// 加密
var encrypted = CryptoJS.AES.encrypt("Message",
key,
{
mode: CryptoJS.mode.CFB,
padding: CryptoJS.pad.AnsiX923,
iv: iv });
// 解密, 返回的是 CipherParams 对象
var decrypted = CryptoJS.AES.decrypt(encrypted,
key,
{
mode: CryptoJS.mode.CFB,
padding: CryptoJS.pad.AnsiX923,
iv: iv });
// 获取解密字符串
var decryptString = decrypted.toString(CryptoJS.enc.Utf8);
The running effect is as follows:
(4) Interface association
Use global variables, environment variables or collection variables to store variables of different levels of scope. Through this variable, the values that need to be passed (such as token, sessionid, user/product id, etc. that make the interface variable dependent) are stored between different interfaces. Transitive dependencies between interfaces to achieve the purpose of interface association.
1.3 Run the test set
After the interface is debugged, you can use the Runner to choose to run multiple interfaces under the same Collection/Folder. You can run the Collection/Folder multiple times, but the operation is a serial iteration, not a concurrent test. The steps are as follows:
Run results/test report
In the picture above, clickView summary
to view the report summary to view the passing status of each interface in each iteration and to know the success rate and stability of the interface:
(1) Use newman to generate test reports
-
Install the npm environment. For the nods installation package, see the official website: http://nodejs.cn/download/;
-
Anso
newman
,cnpm install -g newman
, Common use command:newman run [collection.json/分享的链接] [-g 全局变量文件.json] [-e 环境变量文件.json] [-r 报告格式] [--reporter-html-export 生成的报告保存路径] [-n num] []中的值表示可选 -r 报告格式:能指定的报告格式有cli、html -n num:运行集合num次
-
Export the automated script debugged in Postman. The exported file type is a json file:
- If there are environment variables and global variables, they also need to be exported separately. The exported file type is also a json file:
- The results of running in CMD are as follows:
When the output is in cli format, the test details of each interface will be output first, and then the collection running overview and failed interface assertion details will be displayed:
When the output is HTML, there will be no output on the CMD page. Just go directly to the corresponding specified path to find the report:
The content is as follows:
(2) Use newman-reporter-htmlextra to generate test reports
The generated reports are more user-friendly and easier to view, as follows:
1.4 Generation of interface documents
Postman can generate interface documentation for APIs in the collection.
(1) Generation of a single interface document
(2) Collection interface document
After all interfaces in the collection have been supplemented with documentation, you can view or edit the documentation for all interfaces.
1.5 Postman proxy
Postman proxy is used to capture APIs for debugging, testing interfaces or cookies.
A. Capture HTTP requests
The steps for setting up the proxy are as follows:
(1) Click on the lower right corner of PostmanCapture requests
(2) Configure proxy
(3) Set the proxy listening port (default is 5555) and confirm the settings again
After confirmation, the agent has been turned on, as shown below. Although the Postman agent is effective, the network agent Postman of the client system must be configured to capture the session, which is the fourth step:
(4) Configure system agent (take WIN 10 as an example)
(5) Capture session
When the client browser accesses the server, the request during the access process will be captured by Postman. The specific page and operation are as shown in the figure below:
Click StopStop
, you will enter the capture overview page, which is the fifth step.
(6) View agent capture results
At the same time, you can view the details of each session in the storage Collection when configuring the proxy:
In addition, you can also view or edit the capture details of past agents inHistory
in the left tab bar of Postman:
(7) Close the agent
B, Capture HTTP S
Request
The most important thing to capture https is to import the certificate. The capture steps after the certificate is successfully imported are the same as capturing http.
(1) DownloadOpen_SSL Certificate Generator and install it according to your system type:
Just go to the next step for installation, but you must check the second item in the following steps during installationOpenSSL 二进制文件 (/bin) 目录
:
(2) Configure environment variables and verify
The following screenshot shows that the installation was successful:
(3) Install certificate
(4) Restart Postman
(5) Capture https according to the process of capturing http packets (omitted)
1.6 Monitor, monitor
Monitor is a collection-based monitor used to continuously check the health of APIs, run test suites, or verify critical workflows. There you can set up a collection that contains the requests to run, and set a schedule for how often Postman will run the collection. Monitor also supports data drive.
After successful creation, click Run
If there is a non-PASS interface, there will also be an email warning:
It is particularly important to note that the non-paid version of Postman’s Monitor cannot monitor本地项目
(URL contains localhost/127.0.0.1) and 内部网址项目
(URL address starting with 10.), otherwise:
1.7 Mock server, interface simulation
(1) Two entrances created by Moke
(2) Configure Mock
(3) Run mock
(4) Points to note when running mock
The interface being mocked must haveExample
to return the Mock response set in Example
, and the interface being mocked is createdExample
The steps are as follows: