twill Python下的轻量级网站测试工具

之所以说轻量的原因是他是拿命令行测试的,还有DSL,还有Python。

Twill 网站测试

twill was initially designed for testing Web sites, although since then people have also figured out that it's good for browsing unsuspecting Web sites.

除此之外,还可以拿它做压力测试,这种压力测试和一般的不一样。可以模拟整个过程,比如同时有多少人登陆你的网站。

不过,它有一个限制是没有JavaScript。

看了一下源码,大概原理就是用requests下载html,接着用lxml解析html,比较有意思的是内嵌了一个DSL

Twill 安装

这是一个Python的库。

 pip install twill

Twill 登陆测试

1.启动我们的应用。

2.进入twill shell

twill-sh
 -= Welcome to twill! =-
current page:  *empty page*

3.打开网页

>> go http://127.0.0.1:5000/login
==> at http://127.0.0.1:5000/login
current page: http://127.0.0.1:5000/login

4.显示表单

    >> showforms

Form #1
## ## __Name__________________ __Type___ __ID________ __Value__________________
1     csrf_token               hidden    csrf_token   1423387196##5005bdf3496e09b8e2fbf450 ...
2     email                    email     email        None
3     password                 password  password     None
4     login                    submit    (None)       登入

current page: http://127.0.0.1:5000/login

5.填充表单

formclear 1
fv 1 email test@tes.com
fv 1 password test

6.修改action

formaction 1 http://127.0.0.1:5000/login

7.提交表单

>> submit
Note: submit is using submit button: name="login", value="登入"
current page: http://127.0.0.1:5000/

发现重定向到首页了。

Twill 测试脚本

当然我们也可以用脚本直接来测试login.twill:

go http://127.0.0.1:5000/login

showforms
formclear 1
fv 1 email test@tes.com
fv 1 password test
formaction 1 http://127.0.0.1:5000/login
submit

go http://127.0.0.1:5000/logout

运行

 twill-sh login.twill

结果

>> EXECUTING FILE login.twill
AT LINE: login.twill:0
==> at http://127.0.0.1:5000/login
AT LINE: login.twill:2

Form #1
## ## __Name__________________ __Type___ __ID________ __Value__________________
1     csrf_token               hidden    csrf_token   1423387345##7a000b612fef39aceab5ca54 ...
2     email                    email     email        None
3     password                 password  password     None
4     login                    submit    (None)       登入

AT LINE: login.twill:3
AT LINE: login.twill:4
AT LINE: login.twill:5
AT LINE: login.twill:6
Setting action for form  (<Element form at 0x10e7cbb50>,) to  ('http://127.0.0.1:5000/login',)
AT LINE: login.twill:7
Note: submit is using submit button: name="login", value="登入"

AT LINE: login.twill:9
==> at http://127.0.0.1:5000/login
--
1 of 1 files SUCCEEDED.

一个成功的测试诞生了。

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806