我无法确定如何测试基于Django类的视图是否从URL模式接收到预期的kwargs
。
如果我有urls.py
:
from django.conf.urls import url
from myapp import views
urlpatterns = [
# ...
url(
regex=r"^people/(?P<pk>\d+)/$",
view=views.PersonDetailView.as_view(),
name='person_detail'
),
]
我的views.py
:
from django.views.generic import DetailView
from myapp.models import Person
class PersonDetailView(DetailView):
model = Person
我可以测试对URL的请求是否调用了正确的视图:
from django.test import TestCase
from django.urls import resolve
from myapp import views
from myapp.factories import PersonFactory
class UrlsTestCase(TestCase):
def test_person_detail_view(self):
PersonFactory(pk=3)
self.assertEqual(resolve('/people/3/').func.__name__,
views.PersonDetailView.__name__)
但我也想测试/people/3/
的请求会导致{'pk': '3'}
传递给PersonDetailView
,而我无法确定基于类的视图接收kwargs
以便测试它(通过修补接收方法,我猜)。
答案 0 :(得分:1)
以下是我在视图中检查id或pk的方式(我正在使用Django1.11):
from menus.models import Item
from menus.views import ItemListView
from django.test import RequestFactory
from django.contrib.auth.models import User
person = User.objects.get(username='ryan')
factory = RequestFactory()
request = factory.get('/items/')
request.user = person
response = ItemListView.as_view()(request)
#prints the id or pk of the requesting user
response._request.user.pk
response._request.user.id