Use Postman preprocessing, variables, and test to improve test interface test efficiency

Under the current trend of separate front-end and back-end development, interface writing and testing has become an inevitable job for Internet developers. In the actual development process, POSTMAN is a frequently used interface document development and testing tool. Making good use of some functions and skills of postman can effectively improve our work efficiency.
The following are some functions I used in my own development, I hope it will be useful to everyone!


My postman version number: 9.30.4

1: Use of environment variables

In my understanding, environment variables are common variables in our local environment during development, test environment, and formal environment. These variables are used in each environment, but the corresponding values ​​are different. Switching environments will switch to each environment the desired value.
The environment variable is for the entire workspace, it is a global variable, generally it can be used to set the global api request path, you can set different environment variables according to your actual situation, such as my project, I set A collection of local environment variables: localhost, a remote test environment: remotehost, and a formal environment: yl
insert image description here

1.1 The use of environment variables in interface requests

insert image description here
The way to use environment variables is to put the variable name in double curly braces, such as: { {energy-url}}, in the interface request, it can be used in the request url, or in the request parameters, or in the form parameters, and the corresponding values.
When requesting an interface, we often test interface requests in different environments, and we need to switch between different environments. In postman, you only need to select the corresponding environment in the environment drop-down selection box in the upper right corner, and you can easily switch environments, such as In the picture above, you only need to select localhost to send the request to the local server, select remotehost to send the request to my test server, and select yl to send the request to my production server, which is very convenient.

1.2 The use of environment variables in preprocessing scripts and tests

In pre-request script and test, we can also call environment variables to facilitate our processing logic. In pre-processing scripts and tests, we use pm.environment.get (variable name) to call environment variables, such as: pm.environment.get("energy-url")
insert image description here
can of course update and modify the value of environment variables, use pm.environment.set("Authorization", pm.collectionVariables.get("Authorization")) to assign and Revise.

2: Use of collection variables

In postman, different workspaces can be created. In each section, we can place all the interfaces of a project. A project may distinguish different subprojects, so the interfaces of different subprojects can be placed in different collections. ; Everyone's understanding and actual situation may be different, and you can make adjustments according to your actual situation.
The collection variable is the same as its name, and its scope of action is that all places under the collection can be called directly, including parameters, header header information, body, preprocessing and test. I usually use more, including signature, timestamp, authorization tokeninsert image description here

Instructions

1: In each request parameter, use double curly braces to place the variable name, such as: { {sign}} 2: Get the collection variable value
insert image description here
in the preprocessing script and test : pm.collectionVariables.get(“sign”) Set the combined variable value: pm.collectionVariables.set("time",Date.parse(new Date()))




insert image description here

3: Use of preprocessing scripts

pre-request sript is a script program that postman will execute before sending a request, so that we can process some logic and data. Generally, it may be used to process some data or calculations that need to be processed, such as calculating signatures, and can also perform some necessary prefix actions. Such as login; below are the signatures and assignment request timestamps that I often use.

let param = request.data;
try {
  let json = JSON.parse(param); //序列化JSON BODY
  param = json;
}catch(err){
//BODY不是JSON格式
}
const keysSorted = Object.keys(param).sort()
let requestStr = ''
for (let i = 0; i < keysSorted.length; i++) {
    let prv = pm.collectionVariables.get(param[keysSorted[i]].replace(/\{|\}/g,""))
    if(typeof(prv)!="undefined" && prv!=null && prv!="") {
        console.log(prv)
        param[keysSorted[i]] = prv
    }
    if(keysSorted[i]!="sign") requestStr += keysSorted[i] + '=' + (param[keysSorted[i]]!=null?param[keysSorted[i]]:'')
    if(keysSorted[i]=="Authorization") pm.environment.set("Authorization",param[keysSorted[i]])
}

let sign = CryptoJS.MD5(requestStr).toString().toUpperCase();
pm.collectionVariables.set("sign", sign);
pm.collectionVariables.set("Authorization",pm.collectionVariables.get("Authorization"))
//pm.environment.set("sign", sign);

insert image description here

4: The use of test

test is a script program that postman will execute after the request is completed. Generally, testers will use more; usually I use the most to judge whether to log in or log in based on the result returned by the interface. Go to the trouble of manually logging in; the following is the script I usually re-request after judging the login error

// 定义发送登录接口请求方法
function sendLoginRequest() {    
    // 构造一个 POST raw 格式请求。这里需要改成你们实际登录接口的请求参数。
    const loginRequest = {
        url: pm.environment.get("energy-url")+"/login/index",
        method: 'POST',
        body: {
            mode: 'urlencoded',
            urlencoded: 'name=super&password=123456&sign=844207CEF06934C143E6F719D91F346E'
        }
    };
    // 发送请求。 
    // pm.sendrequest 参考文档: https://www.apifox.cn/help/app/scripts/api-references/pm-reference/#pm-sendrequest
    pm.sendRequest(loginRequest, function (err, res) {
        if (err) {
            console.log(err);
        } else {
            // 读取接口返回的 json 数据。
            // 如果你的 token 信息是存放在 cookie 的,可以使用 pm.cookies.get('token') 方式获取。 
            // pm.cookies 参考文档:https://www.apifox.cn/help/app/scripts/api-references/pm-reference/#pm-cookies
            const jsonData = res.json();
            // 将 accessToken 写入环境变量 Authorization
            pm.collectionVariables.set('Authorization', jsonData.data.token);   
        }
    });
}
 
var jsonData = pm.response.json();
//登录错误,重新登录
if(jsonData.code==401 || jsonData.code==403){
    sendLoginRequest()
}

insert image description here
When sending a request, there are different request methods, different request methods, and data formats are also different, so you need to pay attention to this, otherwise the data may not be sent successfully!
1: form format
body: { mode: 'urlencoded', urlencoded: 'name=super&password=123456&sign=844207CEF06934C143E6F719D91F346E' } 2: raw format body: { mode: 'raw', raw: JSON.stringify({ key: 'this is json' }) }



insert image description here





insert image description here

Guess you like

Origin blog.csdn.net/xiaoyukongyi/article/details/127557889