当前位置:   article > 正文

Postman前置脚本(二)_postman前后置

postman前后置

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("====================");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/631859
推荐阅读
相关标签
  

闽ICP备14008679号