Django Testing: determine which view was executed
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 开发者_JAVA百科advance.
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
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.
精彩评论