Postman digital signature, Session dependent, dependent interfaces, asynchronous interfaces to poll results

Script (JS) as Postman gives endless possibilities

Postman 6.1.4 Mac Native Edition is based on
presentations combine user_api_demo achieve

PS
recently received a mandate to take several basic single interface for startup and continuous integration it, to be a conventional functional verification, the study found, the different way the next single, and some need to log in (Session dependent), and some need to test sign (micro-services using digital signatures), interfaces rely on a lot of dynamic data, such as user id, address id, ticket id, current time, etc., and most importantly, the interface is asynchronous orders, returns only event stream event_key, especially on the test environment, order processing slower, the results need to poll a longer period of time, in the selection time, I began to feel the most, an asynchronous interface poll results can only be achieved with Jmeter timer, but personal it is not used Jmeter organizational logic elements (split over crushed). then try to achieve using JS + Postman.

Feasibility of
new Postman adds Pre-request Script and Test, using Javascript, and supports Collection (test set) / Folder (sub test set) level (see below), similar to the function test setUp and tearDown other frame, having equivalent the Fixtures function, for different scope (range) to prepare and clean up and assertions.
Collection (test set) provided

Folder (subtest set) set, a less than the Variables Collection (variable) provided

Postman support JS script libraries

  • Lodash: a practical approach JS library encapsulates many String, Array, Object processing method or the like, less common personal
  • cheerio: Jquery a core library, data acquisition / assertion Html / XML can be a convenient way to use Jquery
  • tv4 JSON Schema validator: 简称tv4, 先定义一个Schema(格式模板), 再验证你的JSON是否满足这种格式, 可用于断言JSON类型响应的整体格式是否正确.
  • CryptoJS: 加密库, 支持AES, DES, HMAC, MD5, SHA1等常用加密方式, 可用于生成加密数据或实现生成签名数据
  • xml2json/json2xml: xml与json格式互转

    [Postman Sandbox Api参考] (https://www.getpostman.com/docs/v6/postman/scripts/postman_sandbox_api_reference)

同时, Postman的脚本中可以读取, 设置变量, 环境变量, 全局变量, 可以读取request对象(只读)和response对象(只读)的信息, 另外, 重要的是Postman的脚本中也可以组装发送接口请求(可以实现接口依赖/接口结果验证问题)

数字签名的实现

实现原理: 请求中埋好参数{{sign}}->Pre-request Script生成sign, 并设置环境变量-> 发送请求
一般的延签接口都是开发给打好jar包扔给你, 自己使用Java或Jmeter调用就行, 但是, 有代码素养的测试可以自己实现签名, 这样可以更灵活.

首先, 做一下参数化, 埋一下变量, 环境中设置了appsercret的环境变量共加密脚本使用
Parametric signature sign

用js实现签名算法

签名算法请参考user_api_demo中delUser接口文档

Pre-request Script

// 连接参数
function con_params(params){
    if(typeof(params) == "string")
        return params;
    else {
        var sort_keys = Object.keys(params).sort();
        var s = '';
        for(var i in sort_keys) {
            var k = sort_keys[i];
            s += k + "=" + con_params(params[k]) + "&";
        }
        return s;
    }
}

// 生成签名
function cal_sign(appsecret,params){
    var s = con_params(params);
    console.log(s + "appsecret=" + appsecret);
    return CryptoJS.MD5(s+"appsecret="+appsecret).toString();
    
}

var appsecret= pm.environment.get("appsecret");  // 从环境变量中获取appsecret
params = JSON.parse(request.data);  // 获取请求数据
delete params.sign;                 // 去掉sign, 得到元素请求参数
sign = cal_sign(appsecret, params); // 计算签名

pm.environment.set("sign", sign);   // 添加为环境变量sign

Signature algorithm used to achieve js

Session依赖/ 接口依赖(关联)

The principle:
Session dependent: the Pre-request Script requests a login interface will keep the Session when retransmission request
interface dependence: In Pre-request Script request dependent interfaces, to get the required parameters from the corresponding interfaces -> set as an environment variable - > dynamic parameters used in the request

Session dependent (login required)
adding and sending the login request script Pre-request Script interface need to log in:

base_url = pm.environment.get("base_url");

// 登录请求, Postman脚本发送表单类(urlencoded)请求方法(Baidu不到的, 官网也没有哦!)
const loginRequest = {
    url: base_url + '/api/user/login/',
    method: "POST",
    body: {
        mode: 'urlencoded',
        urlencoded: 'name=张三&password=123456'
    }
};
pm.sendRequest(loginRequest, function (err, res) {
    console.log(err ? err : res.text());
});

Login Script

Interface dependence
interface dependence token, to set the dynamic parameter in the token request, the request interface getToken Pre-request Script, the token acquisition and set the environment variables
Parameterized token
Pre-request Script

appid = pm.environment.get("appid");
base_url = pm.environment.get("base_url");

pm.sendRequest(base_url+'/api/user/getToken/?appid='+appid, function (err, res) {
    if (err) {
        console.log(err);
    } else {
        token = res.text().split("=")[1];
        pm.environment.set("token", token);
    }
});

GetToken advance request token to the interface and taken

Asynchronous interface poll results

Verify asynchronous interface is one of the difficulties in testing the interface, one is the status of the interface with the acquisition result, realization of the principle here is that, after the transmission interface to achieve the result of polling used in the JS Test setInterval

Tests

event_key = pm.response.json().data.event_key; // 从响应中获取event_key
base_url = pm.environment.get("admin");

// getOrderResult接口
const getOrderResult = {
  url: base_url + '/customer/COrder/getOrderResult',
  method: 'POST',
  body: {
    mode: 'urlencoded',
    urlencoded: 'event_key='+event_key
  }
};

var i = 0; // 计数

// 封装一个发送请求方法,用于计数器调用
function getResult(){
    pm.sendRequest(getOrderResult, function (err, res) {
        i += 1;
        if(err){
            console.log(err);
        }
        else{
            msg = res.json().data.msg;
            if(msg == 'finish' || i > 10){   // 直到msg字段由working变为finish, 设置最多轮询20次, 最多轮询一分钟
               clearInterval(timer); 
            }
        }
    });
}

timer = setInterval(getResult, 3000);  // 每s秒请求一次接口获取结果状态

Polling results single

For more information, please add add learning of micro letter: lockingfree get

Guess you like

Origin www.cnblogs.com/superhin/p/11454838.html