欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Postman前置脚本(二)

程序员文章站 2022-07-12 11:47:22
...

Postman前置脚本第二版


1. 前置脚本请求中参数处理

postman请求中使用的{{}}格式参数,在前置脚本中默认没有进行替换,可以使用pm.variables.replaceIn(),比如pm.variables.replaceIn("{{$timestamp}}")

2. body不可变

postman中body不可变,在前置脚本中无法修改body,目前暂时只适用于get请求

3. 实现功能

  • 环境变量中default_prefix变量默认请求参数的前缀,所有环境变量中以此前缀开头的变量,会自动添加到请求中

  • 参数值处理

  • 添加sign签名

  • 设置环境

  • 判断是否有access_token变量,如果没有调用登陆接口自动获取access_token,并保存到环境变量中

    //pm.environment.set("timestamp", timestamp);
    
    //设置测试环境与正式环境host和app key
    var isTest = pm.collectionVariables.get("isTest");
    var app_key = pm.collectionVariables.get("app_key_release");
    var app_secret = pm.collectionVariables.get("app_secret_release");
    var baseURL = pm.collectionVariables.get("baseURL_release");
    if(isTest == "true"){
        app_key = pm.collectionVariables.get("app_key_debug");
        app_secret = pm.collectionVariables.get("app_secret_debug");
        baseURL = pm.collectionVariables.get("baseURL_debug");
    }
    if(baseURL != pm.collectionVariables.get("baseURL")){
        pm.collectionVariables.set("baseURL", baseURL);
    }
    pm.environment.set("default-app_key", app_key);
    
    //替换请求中参数为实际值
    /*
    var query_params = pm.request.url.query;
    query_params.map((item)=>{
        item.value = pm.variables.replaceIn(item.value);
        });
    */
    
    //log_info(pm.request.url.query.toString(), "query parmas");
    
    //password参数替换为mad5加密后
    if(pm.request.url.path.includes("login")){
        params = pm.request.url.query;
        if(params.has("password")){
            var password = pm.variables.replaceIn(params.get('password'));
            /*
            var rlt = /^\{\{(\w+)\}\}$/.exec(password);
            if(rlt){
                password = pm.variables.get(rlt[1]);
            }
            */
            password_hash = CryptoJS.MD5(password).toString();
            pm.request.url.query.upsert({key: "password", value: password_hash});
        }
    }
    
    
    //判断是否已已经有token,如果没有,调用登陆接口获取token
    if(!pm.variables.has("access_token") && !pm.request.url.path.includes("login")){
        log_info("request token");
        getToken(process_request);
    }else{
        process_request();
    }
    
    
    //添加请求默认参数
    function process_request(){
        //log_info(pm.variables.get("access_token"), "access token");
        var default_params = getDefaultVar(pm.variables.get("default_prefix"));
        if(pm.request.method == "GET"){
            for(k in default_params){
                pm.request.addQueryParams(k + "=" + default_params[k]);
            }
            //pm.request.addQueryParams("app_key=" + app_key);
            //pm.request.addQueryParams("company_id=" + commpany_id);
            //pm.request.addQueryParams("imei=" + imei);
            //pm.request.addQueryParams("timestamp=" + timestamp);
            //pm.request.addQueryParams("language=" + language);
            if(pm.variables.has("access_token") && !pm.request.url.path.includes("login")){
                pm.request.addQueryParams("token=" + pm.variables.get("access_token"));
            }
        }
        if(pm.request.method == "POST"){
            b = pm.request.body;
            //console.log(b);
            if(b != undefined && b.mode == "urlencoded"){
                //body.urlencoded.add({key: "app_key", value: app_key});
                //body.urlencoded.add({key: "commpany_id", value: commpany_id});
                //body.urlencoded.add({key: "imei", value: imei});
                //body.urlencoded.add({key: "timestamp", value: timestamp});
                //body.urlencoded.add({key: "language", value: language});
                //console.log(b.urlencoded);
            }
        }
    
        //获取query params和body form数据,进行sign签名计算
        data = pm.request.url.query.toObject();
        if(pm.request.body){
            body_data = pm.request.body[pm.request.body.mode].toObject();
            Object.assign(data, body_data);
        }
        var sign = sn_sign(data, app_secret);
        //log_info(sign, "sn sign");
        //请求中添加sign参数
        pm.request.addQueryParams("sign=" + sign);
    }
    
    function sn_sign(data, secret){
        if (Object.prototype.toString.call(data) === '[object Object]'){
            var str = secret;
            //var reg = /a/;
            //reg = reg.compile(/^\{\{(\w+)\}\}$/);
            Object.keys(data).sort().map((key)=>{
                var val = pm.variables.replaceIn(data[key]);
                //to do
                //拼接请求参数,对请求进行签名
            });
            //log_info(str, "origin string");
            return CryptoJS.MD5(str).toString().toUpperCase();
        }
        return "";
    }
    
    /******************** 
     * function:获取变量中设置的请求中默认参数
     * parameter:prefix --- 默认参数前缀
    ********************/
    
    function getDefaultVar(prefix){
        var timestamp = Math.round(new Date().getTime() / 1000);
        var def_params = {};
        if(prefix){
            var vars = pm.variables.toObject();
            for(v in vars){
                if(v.startsWith(prefix)){
                  def_params[v.substr(prefix.length)] = vars[v];
                }
            }
        }
        if(!("timestamp" in def_params)){
            def_params["timestamp"] = timestamp.toString();
        }
        return def_params;
    }
    
    function getToken(callback){
        PropertyList = require("postman-collection").PropertyList;
        QueryParam = require("postman-collection").QueryParam;
        var query_params = new PropertyList(QueryParam, this, []);
        var default_params = getDefaultVar(pm.variables.get("default_prefix"));
        default_params["account"] = pm.variables.get("account");
        default_params["password"] = CryptoJS.MD5(pm.variables.get("password")).toString();
        default_params["area_code"] = "86";
        default_params["sign"] = sn_sign(default_params, app_secret);
    
        for(k in default_params){
            query_params.add({key: k, value: default_params[k]});
        }
        //log_info(query_params.toString());
    
        const login_request = {
            url: pm.variables.replaceIn("{{baseURL}}") + "/user/login",
            method: "POST",
            header:["Content-Type: application/x-www-form-urlencoded"],
            body:{
                mode: "raw",
                raw:query_params.toString()
            }
        }
        pm.sendRequest(login_request, function (err, response) {
            if(!err){
                resp_data = response.json();
                if(resp_data.result_code == "0"){
                    pm.environment.set("access_token", resp_data.result_data.access_token);
                }
            }
            if(typeof callback == "function"){
                callback();
            }
        });
    }
    
    
    function log_info(any, tag){
        if(tag == undefined){
            tag = any.toString();
        }
        console.log("=====" + tag + "======");
        console.log(any);
        console.log("====================");
    }
    
相关标签: postman js 接口