Django 测试:确定执行了哪个视图

发布于 2024-09-18 10:20:34 字数 412 浏览 6 评论 0原文

在 Django 测试文档中,他们承诺您可以“测试是否针对给定 URL 执行了正确的视图”。

但是我没有找到任何如何测试执行哪个视图的可能性。我希望在 Response< /code> class但执行视图没有任何内容。

提前致谢。

In the Django testing documentation they promise that you can "Test that the correct view is executed for a given URL."

However I didn't find any possibility how to test which view was executed. I would expect that in the Response class but there's nothing about the executed view.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暮色兮凉城 2024-09-25 10:20:34

您可以这样提取视图函数名称

from django.test.client import Client
c = Client()
response = c.get('/')
from django.core.urlresolvers import resolve
resolve(response.request["PATH_INFO"])[0].func_name

You can extract the view function name thusly

from django.test.client import Client
c = Client()
response = c.get('/')
from django.core.urlresolvers import resolve
resolve(response.request["PATH_INFO"])[0].func_name
伴梦长久 2024-09-25 10:20:34

Dave 的答案涉及每次测试 URL 时的 HTTP 请求,这可能会很慢。如果您只想知道网址解析为哪个视图,则无需使用 Client 即可:

>>> from django.core.urlresolvers import get_resolver
>>> from myapp.views import func_to_test
>>> resolver = get_resolver(None)
>>> match = resolver.resolve('/some/path/')
>>> if match.func is func_to_test:
>>>    print "correct function for resolution!"

Ryan Wilcox 关于路由测试的帖子 更详细地介绍了这些内容,并提供了使测试变得更加容易的技术。

Dave's answer involves a HTTP request each time you're testing a url, which can be slow. If you just want to know what view a url resolves to, you can do that without using Client:

>>> from django.core.urlresolvers import get_resolver
>>> from myapp.views import func_to_test
>>> resolver = get_resolver(None)
>>> match = resolver.resolve('/some/path/')
>>> if match.func is func_to_test:
>>>    print "correct function for resolution!"

Ryan Wilcox's post on route testing goes into more detail and provides techniques for making it even easier to test them.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文