52

I have achieved 100% test coverage in my application everywhere except my urls.py. Do you have any recommendations for how I could write meaningful unit tests for my URLs?

FWIW This question has arisen as I am experimenting with Test-Driven Development and want failing tests before I write code to fix them.

4

3 回答 3

76

一种方法是reverseURL 名称并验证

例子

urlpatterns = [
    url(r'^archive/(\d{4})/$', archive, name="archive"),
    url(r'^archive-summary/(\d{4})/$', archive, name="archive-summary"),
]

现在,在测试中

from django.urls import reverse

url = reverse('archive', args=[1988])
assertEqual(url, '/archive/1988/')

url = reverse('archive-summary', args=[1988])
assertEqual(url, '/archive-summary/1988/')

无论如何,您可能正在测试视图。

现在,要测试 URL 是否连接到正确的视图,您可以使用resolve

from django.urls import resolve

resolver = resolve('/summary/')
assertEqual(resolver.view_name, 'summary')

现在在变量resolverResolverMatch类实例)中,您有以下选项

 'app_name',
 'app_names',
 'args',
 'func',
 'kwargs',
 'namespace',
 'namespaces',
 'url_name',
 'view_name'
于 2013-09-24T16:34:38.133 回答
4

只是补充@karthikr 的答案(基于他的)

-> 你可以断言负责解决的视图是你期望使用的视图resolver.func.cls

例子

from unittest import TestCase
from django.urls import resolve

from foo.api.v1.views import FooView


class TestUrls(TestCase):
    def test_resolution_for_foo(self):
        resolver = resolve('/api/v1/foo')
        self.assertEqual(resolver.func.cls, FooView)

于 2019-09-20T08:29:38.200 回答
0

对不起,我是矿工,但我在关键词“django url testing”下首先发现了这个地方。

我相当同意我的前辈的观点,但我也确信有更好的方法来测试你的 URL。我们不应该使用“ resolver = resolve('url/path') ”的主要原因是当视图的名称更固定时,路径是某种流畅的。

简而言之,这更好:

class TestUrls(TestCase):

    def test_foo_url_resolves(self):
        url = reverse('bar:foo')
        self.assertEqual(resolve(url).func.view_class, FooBarView)

'bar:foo' - bar 是命名空间, foo 是视图名称

比这个

class TestUrls(TestCase):
    def test_resolution_for_foo(self):
        resolver = resolve('/api/v1/foo')
        self.assertEqual(resolver.func.cls, FooView)
于 2021-12-07T08:08:42.667 回答