平时测试过程中,针对接口及消息测试,经常遇到需要mock一些接口或服务的场景,怎么快速mock一个基于http的轻量级服务呢,对比了多个工具之后,选择了bottle这个框架(基于python),简单易用可快速搭建需要的服务。
下面附个简单例子来看一下怎么使用(bottle的官方地址),比如我们mock一个简单的登录服务:
- 通过post请求向mock的服务端发送登录请求;
- 当用户名密码正确则返回“welcome”;
- 当用户名密码错误则返回“88”;
bottle的服务端的源码如下,用python实现:
from bottle import route, run ,post,request
@route('/login', method='POST')
def do_login():
username = request.forms.get('name')
password = request.forms.get('password')
if username == 'www' and password == '123456':
return "hello"
else:
return "88"
run(host='0.0.0.0', port=8080, debug=True)
代码简单易懂,执行后我们可以看到服务已经启动
Bottle v0.11.6 server starting up (using WSGIRefServer())...
Listening on http://0.0.0.0:8080/
`
然后我们发送一个post请求,查看mock的登录服务是否能正常工作,同样用python实现:
import urllib2, urllib
data = {'name' : 'www', 'password' : '123456'}
f = urllib2.urlopen(
url = 'http://localhost:8080/login',
data = urllib.urlencode(data)
)
print f.read()
请求发出后,服务端返回如下,我们看到服务端已经收到了客户端发来的的请求:
Bottle v0.11.6 server starting up (using WSGIRefServer())...
Listening on http://0.0.0.0:8080/
SHIFENG-L2.corp.qihoo.net - - [27/Mar/2014 20:53:49] "POST /login HTTP/1.1" 200 5
客户端也接收到了正确的返回结果:
>>>
hello
>>>
Comments