测试URL是否与正确的视图匹配

时间:2013-03-19 12:02:32

标签: django django-urls django-testing

这两个django网址模式

(r'^articles/(\d{4})/$', 'news.views.year_archive'),
(r'^articles/2003/$', 'news.views.special_case_2003'),

special_case_2003视图永远不会被调用,因为它上面有更广泛的模式

我如何测试(在tests.py中)通过URL模式匹配的视图,以确保我的网址与所需的视图匹配

2 个答案:

答案 0 :(得分:2)

这不会让您匹配原始正则表达式,但它会让您匹配模式的示例:

from django.core.urlresolvers import resolve

def test_foo(self):
    func = resolve('/foo/').func
    func_name = '{}.{}'.format(func.__module__, func.__name__)
    self.assertEquals('your.module.view_name' func_name)

答案 1 :(得分:0)

你应该把特例放在第一位:

(r'^articles/2003/$', 'news.views.special_case_2003'),
(r'^articles/(\d{4})/$', 'news.views.year_archive'),

从顶部到底部评估网址,从而呈现网址匹配的第一个视图。您可以在浏览器中使用它们来测试这些网址,也可以在tests.py中为它们编写特定的测试。

有关如何测试urls.py的详细信息,请阅读https://docs.djangoproject.com/en/1.4/topics/testing/#testing-tools,其中介绍了如何检查是否获得200响应以及如何测试是否存在某些内容。

以下是规范示例:

>>> from django.test.client import Client
>>> c = Client()
>>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
>>> response.status_code
200
>>> response = c.get('/customer/details/')
>>> response.content
'<!DOCTYPE html...'