【发布时间】:2017-06-07 19:26:49
【问题描述】:
我正在为紧跟testing documentation 的 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.
我不明白为什么会发生这种情况以及如何解决这个问题。
-
pkkwargs 在 URL 中, - 根据文档,如果默认为
pk,则无需显式添加lookup-field值, - 视图正确打开,但此测试失败...
谁能解释一下为什么会出现这个错误?
以下是相关代码:
“主要”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,)
【问题讨论】:
-
当您在测试之外(例如通过 Postman)实际请求 API 时,它是否有效?或者如果您使用 APIClient?
-
确实如此。这是 RemcoGerlich 提到的缺失部分。感谢您的建议!
-
@user1544500 如果您从邮递员使用命名参数调用您的 API,那么 API 端点是什么?
标签: python django testing django-rest-framework django-generic-views