使用Groovy构建自己的脚本环境
场景
在进行Web服务端开发的时候,发布前通常需要测试一遍。对于一个大一点的项目,最好的办法是写个自动化测试程序。
以Groovy为例,写测试代码之前通常的有如下几个操作
- 引用相关的类库
- import相关的类
- 对库不熟悉的时候你很可能得先把库的文档好好看一遍
对于你来说,你需要的可能仅仅是post,get等几个简单的操作而已,而上面的操作更是可能占用你整个开发过程的大部分时间。
Orz....项目进度没跟上,又要加班了。。。。
要是有一种语言,本身自带post,get这样的函数那该多好啊,测试程序哗啦哗啦就写完了!
解决方案
通过Groovy构建一个脚本环境,自带post,get这些常用的函数
效果
再也不用手动引用库了,再也不用手动import类了,再也不用复习好长好长的文档了,写测试脚本再也腰不疼、腿不麻了!
原理
groovy本身是一个强大的脚本引擎,同时也是高度可定制化的。
在groovy编译脚本的时候,可以为脚本指定一个基类,这个基类的所有方法和属性都可以直接在脚本引用。
实现
首先,先新建一个工程,这里用gradle作为构建工具,取工程名为httpbatch。
新建build.gradle
apply plugin: 'groovy'
apply plugin: 'eclipse'
apply plugin: 'application'
mainClassName = 'com.kasonyang.httpbatch.Application'
repositories {
mavenCentral()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.3.10'
compile 'org.apache.httpcomponents:httpclient:4.5'
}
工程引用了apache的httpclient组件,并指定主类为com.kasonyang.httpbatch.Application
生成Eclipse工程
$ gradle eclipse
然后我们就可以使用Eclipse导入工程了。
创建主类Application.groovy
package com.kasonyang.httpbatch
import com.kasonyang.httpbatch.test.TestException
import org.codehaus.groovy.control.CompilerConfiguration
class Application {
static void printUsage(){
println """
usage : httpbatch file #execute a file
or httpbatch -s #enter shell mode
"""
}
static void main(String[] args) {
if(args.length<1){
printUsage()
return
}
def reader,scriptStr = ''
switch(args[0]){
case '-s':
print ">"
reader = System.in
reader.eachLine {it->
scriptStr += it + '\n'
if(it == ''){
runScript(scriptStr)
scriptStr = ''
}//else{
print '>'
//}
}
break
default:
def file = new File(args[0])
runScript(file)
break
}
}
private static String getExceptionStack(Exception ex,String clsName){
String msg = ""
for(stack in ex.stackTrace){
if(stack.className == clsName){
def fileName = stack.fileName
def lineNumber = stack.lineNumber.toString()
msg += ("\tFile:${fileName}(${lineNumber})")
}
}
msg
}
private static runScript(def it){
def config = new CompilerConfiguration()
config.scriptBaseClass = 'com.kasonyang.httpbatch.HttpBatchScript'
def shell = new GroovyShell(config)
def scriptClass
try{
//shell.evaluate(file)
def script = shell.parse(it)
scriptClass = script.class.name
def stateReturn = script.run()
//System.out.println(stateReturn)
}catch(TestException ex){
println "test fail:"
println getExceptionStack(ex,scriptClass)
println "\texcepted:${ex.excepted}\n\tactual:${ex.actual}"
}catch(Exception ex){
println ex.message
println getExceptionStack(ex,scriptClass)
}catch(RuntimeException ex){
println ex.message
println getExceptionStack(ex,scriptClass)
}
}
}
Application指定了脚本的基类为com.kasonyang.httpbatch.HttpBatchScript,这个类就是主题的主体。
先上代码
package com.kasonyang.httpbatch
import com.kasonyang.httpbatch.test.TestException
import com.kasonyang.httprequest.HttpRequest
import com.kasonyang.httprequest.HttpResponse
import groovy.lang.Binding
import groovy.lang.Script;
abstract class HttpBatchScript extends Script {
private http = new HttpRequest();
HttpResponse $$
Closure beforeGo,beforePost,afterGo,afterPost
Closure testFail
private String base = ''
private String path = ''
private String trimPath(String path,boolean left=true,boolean right=true){
int start =(left && path.startsWith('/')) ? 1 : 0;
int end = (right && path.endsWith('/')) ? path.length()-1 : path.length();
path.substring(start,end)
}
private def getUri(uri){
base + (base?'/':'') + path + (path?'/':'') + trimPath(uri,true,false)
}
def base(){
this.base = ''
}
/**
* set the base path of request
* @param path the base path
* @return
*/
def base(String path){
this.base = trimPath(path)
}
def enter(){
this.path = ''
}
/**
* enter a directory in base
* @param path
* @return
*/
def enter(String path){
this.path = trimPath(path)
}
/**
* submit a get request
* @param uri the request uri
* @param params the query params
* @param callback call after request
* @return
*/
HttpResponse go(String uri,Map params,Closure callback){
def httpGet = http.createGet(getUri(uri),params)
this.beforeGo?.call(httpGet)
def response = http.execute(httpGet)
this.$$ = response
if(callback) callback.call()
this.afterGo?.call(response)
return this.$$
}
HttpResponse go(String uri,Closure callback){
return go(uri,[:],callback)
}
HttpResponse go(String uri,Map params){
return go(uri,params,null)
}
HttpResponse go(String uri){
return this.go(uri,null)
}
/**
* submit a post request
* @param uri the request uri
* @param params the post params
* @param callback call after request
* @return
*/
HttpResponse post(String uri,Map params,Closure callback){
def httpPost = http.createPost(getUri(uri),params)
this.beforePost?.call(httpPost)
def response = http.execute(httpPost)
this.$$ = response
if(callback) callback.call()
this.afterPost?.call(response)
return this.$$
}
HttpResponse post(String uri,Closure callback){
return post(uri,[:],callback)
}
HttpResponse post(String uri,Map params){
return post(uri,params,null)
}
HttpResponse post(String uri){
return this.post(uri,null)
}
/**
* set the beforeGo callback,which whill be call before every get request
* @param callback
*/
void beforeGo(Closure callback){
this.beforeGo = callback
}
/**
* set the beforePost callback,which whill be call before every post request
* @param callback
*/
void beforePost(Closure callback){
this.beforePost = callback
}
/**
* set the callback,which whill be call when test fail
* @param cb
*/
void testFail(Closure cb){
this.testFail = cb
}
/**
* set the callback,which whill be call after every get request
* @param callback
*/
void afterGo(Closure callback){
this.afterGo = callback
}
/**
* set the callback,which whill be call after every post request
* @param callback
*/
void afterPost(Closure callback){
this.afterPost = callback
}
/**
* test whether it is true
* @param value
*/
void testTrue(Object value){
testEquals(true,value)
}
/**
* test whether actual equals the excepted
* @param excepted
* @param actual
*/
void testEquals(Object excepted,Object actual){
if(excepted != actual){
def ex = new TestException(excepted,actual)
if(this.testFail){
testFail(ex)
}else{
throw ex
}
}
}
/**
* test whether it is null
* @param value
*/
void testNull(Object value){
testEquals(null,value)
}
}
这个类主要定义了一个public属性$$还有几个public方法,也就是post、go,和一些其它可能需要用到的函数。
因为get方法在groovy里有特殊意义,这里使用go方法名代替了get。
提示:这里使用了另外两个类,HttpRequest和HttpResponse,是自定义的两个Class,由于篇幅的原因,这里就不再贴代码了,具体实现可前往Github查看。
我已经把全部源码放到了Github,感兴趣的可以前往查看。
地址:https://github.com/kasonyang/httpbatch
构建项目
$ gradle installDist
程序被输出到build/install/httpbatch目录下,将bin目录添加到环境变量PATH中。
使用
- 创建脚本文件 "example.hb"
go "YOU_URL"//对你要测试的URL提交get请求
testEquals 200,$$.statusCode//状态码为 200?
def text = $$.text //get the response as text
def json = $$.json//get the response as json
println text //output the response
//这里添加你的测试逻辑代码
println "Test successfully!"
- 执行脚本文件
$ httpbatch example.hb
使用Groovy构建自己的脚本环境的更多相关文章
- Spark:利用Eclipse构建Spark集成开发环境
前一篇文章“Apache Spark学习:将Spark部署到Hadoop 2.2.0上”介绍了如何使用Maven编译生成可直接运行在Hadoop 2.2.0上的Spark jar包,而本文则在此基础上 ...
- 为 Python Server Pages 和 Oracle 构建快速 Web 开发环境。
为 Python Server Pages 和 Oracle 构建快速 Web 开发环境. - 在水一方 - 博客频道 - CSDN.NET 为 Python Server Pages 和 Oracl ...
- 使用Eclipse+Maven+Jetty构建Java Web开发环境(几个教程综合集成2014发行)
工作需要使用Jetty由于web集装箱,得知Eclipse+Maven+Jetty该组合是非常好的,因此,要在网上找了很多教程,但不写或多或少特定的或过时的内容而导致最终的配置失败,易于配置为未来的同 ...
- [phvia/dkc] Docker Compose 快速构建(LNMP+Node)运行环境
快速构建(LNMP+Node)运行环境. dkc 在此作为 docker-compose 的缩写,你可以理解为 alias dkc=docker-compose 准备 安装 docker 选择1) 从 ...
- [转]构建Python+Selenium2自动化测试环境(二)
构建Python+Selenium2自动化测试环境完成之后,就需要测试支持python的selenium的版本是否都支持在不同浏览器上运行,当前我们分别在三个最通用的浏览器上通过脚本来测试. 1.在I ...
- [.net 面向对象程序设计深入](5)MVC 6 —— 构建跨平台.NET开发环境(Windows/Mac OS X/Linux)
[.net 面向对象程序设计深入](5)MVC 6 —— 构建跨平台.NET开发环境(Windows/Mac OS X/Linux) 1.关于跨平台 上篇中介绍了MVC的发展历程,说到ASP.NET ...
- 快速构建springmvc+spring+swagger2环境
快速构建springmvc+spring+swagger2环境 开发工具:Intellij idea jdk: 1.8 开发步骤: 1.创建maven工程,如图建立工程结构 ...
- Linux计划任务 定时任务 Crond 配置详解 crond计划任务调试 sh -x 详解 JAVA脚本环境变量定义
一.Crond 是什么?(概述) crontab 是一款linux系统中的定时任务软件用于实现无人值守或后台定期执行及循环执行任务的脚本程序,在企业中使用的非常广泛. 现在开始学习linux计 ...
- Android NDK开发 Android Studio使用新的Gradle构建工具配置NDK环境(一)
本文主要讲述了如何如何在Android Studio使用新的Gradle构建工具配置NDK环境,现在把相关的步骤整理出来分享给Android程序员兄弟们,希望给他们在配置NDK环境时带来帮助. 从An ...
随机推荐
- Dede后台验证码不显示解决方法详解(dedecms 5.7)
今天朋友问我他本地与服务器上安装了dedecms5.7无法显示验证码,一般这种情况很少见,一般情况就是服务器设置问题,还有临时目录的权限问题 Dede后台验证码不显示或不正常分三种情况,下面来逐一分析 ...
- 【MVC】ASP.NET MVC 请求生命周期
当一个asp.net mvc应用程序提出请求,为了响应请求,包含一些请求执行流程步骤! 在asp.net mvc应用程序Http request和Http response 过程中,主要包含8个步骤: ...
- c programming language ___ 5_2.c
#include <stdio.h> #include <ctype.h> #define BUG printf("here!bug!\n"); int g ...
- 九度OJ 1544 数字序列区间最小值
题目地址:http://ac.jobdu.com/problem.php?pid=1544 题目描述: 给定一个数字序列,查询任意给定区间内数字的最小值. 输入: 输入包含多组测试用例,每组测试用例的 ...
- C puzzles详解
题目:http://www.gowrikumar.com/c/ 参考:http://wangcong.org/blog/archives/291 http://www.cppblog.com/smag ...
- 《Google 代码风格指南》
<Google 代码风格指南> https://github.com/google/styleguide
- nginx+php与apache+php性能对比
测试工具http_load相同的动态页面测试,相同的硬件资源,相同并发,相同请求数量的前提下,nginx+php比apache+php的性能要 差,而且如果请求的压力大于硬件资源的承受能力,nginx ...
- Windows7防火墙服务无法启用怎么办
点击windows 7控制面板中防火墙的“推荐配置”没有反应,打开“服务”,无法启动windows firewall,并报错. 问题: 1.点击windows 7控制面板中防火墙的“推荐配置”没有 ...
- 使用sqoop将mysql数据导入到hadoop
hadoop的安装配置这里就不讲了. Sqoop的安装也很简单. 完成sqoop的安装后,可以这样测试是否可以连接到mysql(注意:mysql的jar包要放到 SQOOP_HOME/lib 下): ...
- BT9034: 仅 IE 和 Opera 支持 HTMLFrameElement 和 HTMLIFrameElement 的 document 属性
标准参考 根据 DOM-2 中的描述,HTMLFrameElement 和 HTMLIFrameElement 都没有 'document' 属性. 关于 HTMLFrameElement 对象的详细 ...