【问题标题】:Expected view to be called with a URL keyword argument named "pk"使用名为“pk”的 URL 关键字参数调用预期视图
【发布时间】: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.

我不明白为什么会发生这种情况以及如何解决这个问题。

  • pk kwargs 在 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


【解决方案1】:

当我在 perform_create 中错误使用 get_object 方法时遇到了类似的错误。从documentation阅读为什么这个错误

perform_create(self,instance):
      instance = self.get_object()

【讨论】:

    【解决方案2】:

    使用请求和来自 URL 的参数调用视图函数。所以通过它们:

    response = view(request, pk=1)
    

    【讨论】:

    • 天啊,我尝试将其添加到as_view,然后是factory.get,然后尝试处理请求本身...
    猜你喜欢
    • 2018-08-17
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    相关资源
    最近更新 更多