我如何单元测试django urls? [英] How do I unit test django urls?
问题描述
我在我的应用中取得了100%的测试覆盖率无处不在,除了我的 urls.py
。你有没有建议我如何为我的URL编写有意义的单元测试?
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这个问题是因为我正在试验测试在编写代码以解决问题之前,需要进行开发并想要失败的测试。
FWIW This question has arisen as I am experimenting with Test-Driven Development and want failing tests before I write code to fix them.
推荐答案
一种方法是 reverse
URL名称和验证
One way would be to reverse
URL names and validate
示例
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/')
您可能反正测试的意见。
You are probably testing the views anyways.
现在,为了测试URL连接到正确的视图,您可以使用 resolve
Now, to test that the URL connect to the right view, you could use resolve
from django.urls import resolve
resolver = resolve('/summary/')
assertEqual(resolver.view_name, 'summary')
现在分解器
( ResolverMatch
类实例) ,您有以下选项
Now in the variable resolver
(ResolverMatch
class instance), you have the following options
'app_name',
'app_names',
'args',
'func',
'kwargs',
'namespace',
'namespaces',
'url_name',
'view_name'
这篇关于我如何单元测试django urls?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!