我正在编写Django Rest Framework视图的测试,紧密遵循测试文档。
这是我的简单测试:
def test_patient_detail_api_opens(self):
factory = APIRequestFactory()
view =PatientDetailApi.as_view()
request = factory.get(reverse('api_pacjent', kwargs={'pk' :1}))
force_authenticate(request, user=self.user)
response = view(request)
self.assertEqual(response.status_code, 200)
这个测试失败并显示以下信息:
AssertionError: Expected view PatientDetailApi to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.
我不明白为什么会发生这种情况以及如何修复它。
- URL中存在
pk
kwargs, - 根据文档,如果
lookup-field
默认为pk
,则无需显式添加其值, - 视图正确打开,但是此测试失败...
请问有人能解释一下为什么会出现这个错误吗?
以下是相关代码:
'main' url.py
:
urlpatterns = [
url(r'^pacjent/', include('pacjent.urls')),
]
pacjent.urls
看起来是这样的:
url(r'^api/szczegoly/(?P<pk>\d+)/$', PatientDetailApi.as_view(), name="api_pacjent"),
而 PatientDetailApi
就是这个:
class PatientDetailApi(generics.RetrieveUpdateAPIView):
model = Patient
serializer_class = PatientDetailsSerializer
queryset = Patient.objects.all()
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)