Django 测试 - 是否硬编码 URL
这是一个最佳实践问题。
在 Django 中编写测试时,最好在tests.py中硬编码url,还是使用调度的reverse()函数来检索正确的url?
仅使用硬编码url进行测试<强>感觉是正确的方法,但同时我想不出一个足够好的论据来不使用reverse()。
选项 A.reverse()
# Data has already been loaded through a fixture
def test_view_blog(self):
url = reverse('blog', kwargs={'blog_slug':'test-blog'})
response = self.client.get(url)
self.failUnlessEqual(response.status_code, 200)
选项 B.硬编码
# Data has already been loaded through a fixture
def test_view_blog(self):
url = '/blog/test-blog/'
response = self.client.get(url)
self.failUnlessEqual(response.status_code, 200)
This is a best-practices question.
When writing tests in Django, is it better to hard code urls in your tests.py, or to use the dispatch's reverse() function to retrieve the correct url?
Using hard-coded urls for testing only feels like the right way, but at the same time I can't think of a good enough argument for not using reverse().
Option A. reverse()
# Data has already been loaded through a fixture
def test_view_blog(self):
url = reverse('blog', kwargs={'blog_slug':'test-blog'})
response = self.client.get(url)
self.failUnlessEqual(response.status_code, 200)
Option B. hard-coded
# Data has already been loaded through a fixture
def test_view_blog(self):
url = '/blog/test-blog/'
response = self.client.get(url)
self.failUnlessEqual(response.status_code, 200)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议使用“Option A.reverse()”,因为它使您能够将测试与视图安装的位置分离。
例如,如果“/blog/test-blog/”变为“/blog/test-better-url-blog/”,则测试仍然是相关的。
I would recommend to use "Option A. reverse()" because it enables you to decouple your test from the location at which the view is mounted.
for example if '/blog/test-blog/' becomes '/blog/test-better-url-blog/' for test will still be pertinent.
我最近开始通过 django-test-utils 对我的一些 Django 工作进行单元测试。
我没有使用硬编码 URL 和/或使用反向,而是使用诸如 twill.follow('Blog') 之类的东西(跟踪页面上的“博客”链接)。
这可以让您真正测试网站的行为,就像网络浏览器看到它一样,并且可以捕获其他方法无法捕获的内容。例如,如果您不小心从导航链接中删除了“博客”链接,则会失败。
I've recently started using Twill via django-test-utils to unit test some of my Django work.
Instead of hardcoding URLs and/or using reverse I use things like
twill.follow('Blog')
(to follow a "Blog" link on the page).This lets you really test the behavior of your website, just like a web browser would see it, and can catch things the other methods can't. For example, it would fail if you accidentally removed the "Blog" link from your navigation links.
最好使用反向函数通过视图名称获取 url。这不仅可以测试您的视图,还可以确保您的视图名称保持相同。
将其视为内部 API 测试。如果您的某些网址已损坏,您将会意识到,并会收到提醒以更新模板中的 {% url %} 标记。
It is better to use the reverse function to get the urls by view names. This will not only test your views but also ensures that your view names keep the same.
See it as internal API testing. You would recognize if some of your URLs are broken and get reminded to update your {% url %} tags in the templates.
为什么不同时执行
twill.follow('Blog')
& 呢?反向()
?Why not do both
twill.follow('Blog')
&reverse()
?