Postman common summary

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.

image-20230306112728690

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.

image-20230306113640390

(1) Functions and functions of the interface editing area

image-20230306120949304

(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:

image-20230306125127566

Script execution order

The execution sequence of scripts at different levels is as follows:

image-20230306141209586

variable scope

If there is a data-driven file, pay attention to the scope of the variables:

image-20230307163545143

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:

image-20230306143656434

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:

image-20230306144231933

Script help

In Postman, use the shortcut method on the right when writing a script. Click to automatically generate:

image-20230306144903391

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

image-20230306150812067

Examples of using dynamic variables are as follows:

image-20230306151306307

(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 CBC
  • paddig:Padding method [NoPadding ZeroPadding Pkcs7(Pkcs5) Iso10126 Iso97971 AnsiX923], the default is Pkcs7(Pkcs5)
  • vi: Offset vector
  • formatter: 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:

image-20230306165530802

(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:

image-20230306172457622

image-20230306172949837

Run results/test report

image-20230306173656111

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:

image-20230306173823937

(1) Use newman to generate test reports
  • Install the npm environment. For the nods installation package, see the official website: http://nodejs.cn/download/;

  • Ansonewman, 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:

    image-20230307142255829

    • If there are environment variables and global variables, they also need to be exported separately. The exported file type is also a json file:

    image-20230307142905118

    • 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:

    image-20230307144225926

    image-20230307144451207

    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:

image-20230307145210447

The content is as follows:

image-20230307145625363

(2) Use newman-reporter-htmlextra to generate test reports

image-20230307151807558

The generated reports are more user-friendly and easier to view, as follows:

image-20230307152054348

1.4 Generation of interface documents

Postman can generate interface documentation for APIs in the collection.

(1) Generation of a single interface document

image-20230307165929897

image-20230307170315802

(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.

image-20230307170932005

image-20230307170958207

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

image-20230307211044176

(2) Configure proxy

image-20230307230027485

(3) Set the proxy listening port (default is 5555) and confirm the settings again

image-20230307213424219

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:

image-20230307213745063

(4) Configure system agent (take WIN 10 as an example)

image-20230307214301756

(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:

image-20230307223633915

Click StopStop, you will enter the capture overview page, which is the fifth step.

(6) View agent capture results

image-20230307223836799

At the same time, you can view the details of each session in the storage Collection when configuring the proxy:

image-20230307224232094

In addition, you can also view or edit the capture details of past agents inHistory in the left tab bar of Postman:

image-20230307224706381

(7) Close the agent

image-20230307224839483

B, Capture HTTP SRequest

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:

image-20230308142220573

Just go to the next step for installation, but you must check the second item in the following steps during installationOpenSSL 二进制文件 (/bin) 目录:

image-20230308142350080

(2) Configure environment variables and verify

image-20230308142813648

The following screenshot shows that the installation was successful:

image-20230308142948884

(3) Install certificate

image-20230308143230660

image-20230308143258932

image-20230308143406582

image-20230308143506096

(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.

image-20230308151922792

image-20230308152057553

After successful creation, click Run

image-20230308163621101

If there is a non-PASS interface, there will also be an email warning:

image-20230308163811678

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:

image-20230308163853260

1.7 Mock server, interface simulation

(1) Two entrances created by Moke

image-20230311180200215

image-20230311180257842

(2) Configure Mock

image-20230311180317134

image-20230311181015215

(3) Run mock

image-20230311181629431

(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 createdExampleThe steps are as follows:

image-20230311182026057

Guess you like

Origin blog.csdn.net/weixin_43162616/article/details/129466929