Skip to content

常用工具类

ReneJiang edited this page Dec 4, 2019 · 3 revisions

1. 基础知识

1.1 Groovy插值字符串简介

// 变量定义
username = 'AnyMock'

// 单行插值字符串
str1 = "username = $username, length = ${username.length()}"

// 多行插值字符串
str2 = """{
    "username": $username,
    "length": ${username.length()}
}"""

assert str1 == 'username = AnyMock, length = 7'
assert str2 == '''{
    "username": AnyMock,
    "length": 7
}'''

1.2 如何调试

推荐使用断言进行调试

def username = request.getParameter('username');
assert username == 'AnyMock';

若不符合断言条件,请求将返回报错信息与http请求报文

[310005-Groovy script exec exception]
##############################################################################
Assertion failed: 

assert username == 'AnyMock'
       |        |
       |        false
       'WrongParam'

##############################################################################
GET /example/06?username=WrongParam
cache-control:no-cache
postman-token:7bd37c0e-12a6-47e4-a81e-02e3179b0f7e
user-agent:PostmanRuntime/7.6.0
accept:*/*
host:127.0.0.1:8330
accept-encoding:gzip, deflate
connection:keep-alive

1.3 如何打印日志

print 'Service starting...'

anymock-core的后端日志中将会出现如下内容

2019-03-11 22:08:43.854  INFO 116401 --- [http-nio-8330-exec-3] c.d.a.core.biz.impl.GroovyServiceImpl    : You can log here

2. 如何获取请求参数

2.1 如何获取GET请求参数

username = request.getParameter('username');

2.2 如何获取POST(x-www-form-urlencoded)请求参数

username = request.getParameter('username');

body = request.getAttribute('body');

2.3 如何获取请求体

body = request.getAttribute('body');

2.4 如何获取请求头

username = request.getHeader('username');

3. 如何设置响应参数

3.1 如何设置响应头

response.setHeader('username', 'AnyMock');

3.2 如何设置响应体

如果脚本中存在return语句,则响应体的内容为return对象的字符串形式

return "This is response body.";

否则将取最后一行表达式作为返回结果

"This is response body.";

3.3 如何设置异步响应头

httpURLConnection.setRequestProperty('key', 'value')

3.4 如何设置异步响应体

同3.2 如何设置响应体

4. 常用工具使用

4.1 如何解析JSON

result = new JsonSlurper().parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')

assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"

4.2 如何解析XML

rootNode = new XmlSlurper().parseText('<root><one a1="uno!"/><two>Some text!</two></root>')

assert rootNode.name() == 'root'
assert rootNode.one[0].@a1 == 'uno!'
assert rootNode.two.text() == 'Some text!'
rootNode.children().each { assert it.name() in ['one','two'] }

4.3 如何进行URL编码解码

result = URLEncoder.encode('bookname=Mysql从删库到跑路', "UTF-8" )
assert result == 'bookname%3DMysql%E6%B5%A0%E5%BA%A1%E5%9E%B9%E6%90%B4%E6%92%B3%E5%9F%8C%E7%92%BA%E6%88%A3%E7%9F%BE'

result = URLDecoder.decode(result, "UTF-8" )
assert result == 'bookname=Mysql从删库到跑路'

4.4 如何生成随机数

使用java.util.Randomjava.Security.SecureRandom等随机数工具

4.5 如何操作数组

兼容java语法,可使用[]运算符直接操作

4.6 如何进行base64编码解码

def s = 'Argh, Groovy you say, mate?'

String encoded = s.bytes.encodeBase64().toString()
assert 'QXJnaCwgR3Jvb3Z5IHlvdSBzYXksIG1hdGU/' == encoded

byte[] decoded = encoded.decodeBase64()
assert s == new String(decoded)

4.7 如何操作日期

同Java语法

4.8 安全

同Java语法 md5 sha1 sha256 rsa aes(cbc ebc)

4.9 如何操作二进制

同Java语法

4.10 如何访问数据库(以Mysql为例)

import groovy.sql.Sql

sql = Sql.newInstance("jdbc:mysql://localhost:8306/database?serverTimezone=UTC",
                      "root", 
                      "root",
                      "com.mysql.jdbc.Driver");
result = '';
sql.eachRow("select * from am_space"){ result += (it.id +  " ${it.label}\n")}

4.11 如何配置protobuf协议mock