【问题标题】:test that an URL is matching the correct view测试 URL 是否匹配正确的视图
【发布时间】:2013-03-08 02:20:21
【问题描述】:

对于这两个 django url 模式

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

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

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

【问题讨论】:

    标签: django django-urls django-testing


    【解决方案1】:

    这不会让你匹配原始的正则表达式,但它会让你匹配一个模式的例子:

    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)
    

    【讨论】:

      【解决方案2】:

      你应该把特殊情况放在第一位:

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

      url 从上到下进行评估,从而呈现与 url 匹配的第一个视图。您可以在浏览器中使用它们来测试这些 url,也可以在 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...'
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 2015-11-14
      • 2015-06-09
      • 1970-01-01
      • 2021-06-21
      相关资源
      最近更新 更多