Django和zc.testbrowser集成
项目描述
关于
homophony 为Django提供了 zc.testbrowser 集成;zc.testbrowser 比Django附带的功能测试客户端更健壮。
请参阅 zc.testbrowser介绍,以更好地了解它的强大之处。
使用homophony
首先,您需要安装 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 中定义的。
Doctests
如果您喜欢 doctests 而不是单元测试(就像我们一样!),请使用以下内容作为 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'
辅助工具
浏览器类有一些有用的辅助工具。您可以使用 queryHTML 在 HTML 文档上运行 XPath 查询,如下所示
>>> browser.queryHTML('//h1') <h1>Hello Jim</h1>
在调试测试时,有时打开浏览器测试的特定点很有用。您可以通过调用 serve 来实现这一点
>>> browser.serve()
此命令将启动一个 HTTP 服务器并打开一个可以实时访问您的应用程序的网络浏览器。使用 Ctrl-C 停止服务器并继续运行测试。
已知问题是微型 Web 服务器不提供静态文件,因此您的浏览器可能无法访问应用程序使用的 JavaScript 或 CSS。
浏览器将在请求之间持久化 cookies,因此像用户会话这样的东西应该可以工作。
示例应用程序
源分发中有一个示例 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 执行的。
反馈
有一个主页,其中包含有关如何访问代码存储库的说明。
请将反馈和建议发送至 team@shrubberysoft.com。
项目详细信息
homophony-0.1.7.1.tar.gz 的散列
算法 | 散列摘要 | |
---|---|---|
SHA256 | d38ce91a193224f6a2ebe8c7a3a7779bf781a60624ace1a4207aa5b059238db9 |
|
MD5 | fcb61c712a8f002fe8ec277e1759e6bb |
|
BLAKE2b-256 | c4b9b5fda6afc606d3f498eb22a8022d8e6c68da784e8f980393b6948767505a |