简体   繁体   English

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

[英]test that an URL is matching the correct view

for these two django url patterns 对于这两个Django URL模式

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

the special_case_2003 view will never be called because of the wider pattern above it special_case_2003视图将永远不会被调用,因为它上方的模式更大

how can i test (in tests.py) what view have been matched via an URL pattern to be sure my urls are matching the desired views 我如何测试(在tests.py中)通过URL模式匹配了哪些视图,以确保我的网址与所需的视图匹配

This won't let you match the raw regular expression, but it'll let you match an example of a pattern: 这不会让您匹配原始正则表达式,但是会让您匹配模式示例:

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)

You should put the special case first: 您应该将特殊情况放在首位:

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

The urls are evaluated from top to bottom thus rendering the first view for which an url matches. 从顶部到底部对URL进行评估,从而呈现与URL匹配的第一个视图。 You can just test these urls by using them in your browser or you could write a specific test for them in tests.py. 您可以通过在浏览器中使用它们来测试这些URL,也可以在tests.py中为它们编写特定的测试。

For more information on how to test urls.py read https://docs.djangoproject.com/en/1.4/topics/testing/#testing-tools which explains both how you can check whether you get a 200 response and how you can test whether certain content is present. 有关如何测试urls.py的更多信息,请阅读https://docs.djangoproject.com/en/1.4/topics/testing/#testing-tools ,其中说明了如何检查是否收到200响应以及如何进行响应测试是否存在某些内容。

Here is the canonical example: 这是规范的示例:

>>> 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...'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM