Postman Script用法

介绍

Postman提供了一定的脚本编写功能,用户可以通过编写脚本添加一些动态行为,官方介绍如下:

Postman contains a powerful runtime based on Node.js that allows you to add dynamic behavior to requests and collections. This allows you to write test suites, build requests that can contain dynamic parameters, pass data between requests, and a lot more.

req-resp.png

Pre-request Script

在请求前执行,用于添加一些动态的请求参数。

Tests

在获取到服务端返回结果后执行,用于编写测试用例,判断返回结果是否符合期望。

使用示例

示例简述

有一个服务,服务调用方式如下:

  • 每次请求都需要添加当前时间戳参数timestamp至请求头;
  • 每次请求都需要对timestamp进行加密生成数据签名参数signature,并把signature添加到请求头,signature参数生成算法:signature=MD5(salt+timestamp)。

模拟接口参考

以下是基于Spring Boot的接口模拟参考代码:

package cn.centychen.demo.springboot.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Cent
 * @createAt 2020/10/21
 */
@RestController
@RequestMapping("/postman")
@Slf4j
public class PostmanDemoController {

    private static final String SALT = "yJhjBoiGN8or";
    private static final char[] HEX_CHARS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};


    @GetMapping("/demo")
    public String demo(@RequestHeader("timestamp") String timestamp, @RequestHeader("signature") String signature, String name) {
        if (!accessSignature(timestamp, signature)) {
            return "Sorry,signature is wrong!";
        }

        return String.format("%s,you do it!", name);
    }

    /**
     * 校验签名
     *
     * @param timestamp
     * @param signature
     * @return
     */
    private boolean accessSignature(String timestamp, String signature) {
        return StringUtils.hasText(timestamp)
                && StringUtils.hasText(signature)
                && generateSignature(timestamp).equals(signature);
    }

    /**
     * 生成签名
     *
     * @param string
     * @return
     */
    private String generateSignature(String string) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("MD5").digest(
                    (SALT + string).getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("签名失败!");
        }
        String signature = new String(encodeHex(secretBytes));
        log.info("signature=====>{}", signature);
        return signature;
    }

    /**
     * Encode
     *
     * @param bytes
     * @return
     */
    private char[] encodeHex(byte[] bytes) {
        char[] chars = new char[32];

        for (int i = 0; i < chars.length; i += 2) {
            byte b = bytes[i / 2];
            chars[i] = HEX_CHARS[b >>> 4 & 15];
            chars[i + 1] = HEX_CHARS[b & 15];
        }

        return chars;
    }
}

Postman调用

接口配置

image.png

Header配置

image-2.png

编写pre-request script

//盐值
var salt = 'yJhjBoiGN8or'

//请求参数name
var name='Cent';
pm.environment.set('name',name);

//获取当前时间戳
var timestamp = new Date().getTime();
//添加timestamp到环境变量
pm.environment.set('timestamp',timestamp);

//生成数据签名,CryptoJS是Node的基础包,可直接使用
var signatrue = CryptoJS.MD5(salt + timestamp).toString();
//添加signatrue到环境变量
pm.environment.set('signatrue',signatrue);

编写tests script

pm.test("调用测试",function(){
    var name = pm.environment.get('name');
    pm.expect(pm.response.text()).eql(name+',you do it!');
});

调用测试

执行调用返回结果如下文,验证通过。

请求头

image-3.png

返回信息

image-4.png

Tests

image-5.png

参考资料

  • Scripting in Postman
  • Postman JavaScript reference

你可能感兴趣的:(Postman Script用法)