django和zc.testbrowser集成
homophon的Python项目详细描述
关于
homophony为django提供zc.testbrowserintegration; zc.testbrowser比默认的功能测试健壮得多 Django的客户。
请参阅introduction到zc.testbrowser以获得更好的理解 它有多强大。
使用谐音
首先,为了方便起见,您需要安装homophony, 最近的版本应该可以从pypi获得。
假设您正在处理一个名为foobar;的应用程序 此应用程序位于foobar/tests.py。
单元测试
以此作为foobar/tests.py:
的起点from homophony import BrowserTestCase, Browser class FoobarTestCase(BrowserTestCase): def testHome(self): browser = Browser() browser.open('http://testserver') browser.getControl(name='first_name').value = 'Jim' browser.getForm().submit() self.assertEquals(browser.url, 'http://testserver/hello') self.assertEquals(browser.title, 'Hello Jim')
记住实现自定义的setUp和tearDown方法 应该包括调用在BrowserTestCase中定义的那些。
博士
如果你更喜欢博士学位而不是单元测试(就像我们一样!),使用以下作为基础 对于foobar/tests.py:
from homophony import DocFileSuite def suite(): return DocFileSuite('tests.txt')
下面是一个例子foobar/tests.txt文件:
The website welcomes its visitors with a form: >>> browser = Browser() >>> browser.open('http://testserver') >>> browser.getControl(name='first_name').value = 'Jim' >>> browser.getForm().submit() When a name is given, it echoes back with an informal greeting: >>> browser.title 'Hello Jim' >>> print browser.contents <!DOCTYPE html> ... <h1>Hello Jim</h1> ... And there is a link to go back: >>> browser.getLink('Go back').click() >>> browser.title 'Home'
助手
浏览器类中有一些有用的帮助程序。您可以运行xpath查询 在使用queryHTML的HTML文档上,如下所示:
>>> browser.queryHTML('//h1') <h1>Hello Jim</h1>
在调试测试时,有时在特定的 测试中的点。通过调用serve:
>>> browser.serve()
此命令将启动一个http服务器并使用live access打开一个web浏览器 你的申请。使用ctrl-c停止服务器并继续运行测试。
有一个已知的问题是mini-webserver不提供静态文件,因此 您的浏览器可能无法访问应用程序使用的javascript或css。
浏览器将保存cookies accross请求,因此类似于用户会话 应该有用。
示例应用程序
源发行版中有一个示例django应用程序。让我们 运行测试:
wormhole:example admp$ ./manage.py test -v 2 website Creating test database... Creating table auth_permission Creating table auth_group Creating table auth_user Creating table auth_message Creating table django_content_type Creating table django_session Creating table django_site Installing index for auth.Permission model Installing index for auth.Message model ... testHome (example.website.tests.FoobarTestCase) ... ok Doctest: tests.txt ... ok ---------------------------------------------------------------------- Ran 2 tests in 0.102s OK Destroying test database...
参数-v 2用于打印测试列表,否则 没必要。
为了学习的目的,试着打破测试并在 测试运行程序的输出。
它是如何工作的?
为urllib安装自定义挂钩,以传递 http://testserver到WSGIHandler的子类 通过WSGI公开django应用程序。真正的重担是 由wsgi_intercept执行。