繁体   English   中英

测试经过身份验证的 django-rest-framework 路由时出现 405 错误

[英]405 error when testing an authed django-rest-framework route

我测试CreateAPIViewAPITestCase类。 作为匿名用户,事情按预期工作,但是当我作为用户 login() 时,我收到 405 HttpResponseNotAllowed异常。 我能够成功创建一个对象,同时通过 django-rest-framework Web 前端以用户身份进行身份验证。 我正在使用 djangorestframework 版本 3.9.4 和 Django 1.11.29。

以下是代码的主要部分,以大致了解我在做什么:

class SherdNoteCreate(CreateAPIView):                                                                                                                                                        
    serializer_class = SherdNoteSerializer

    def post(self, request, *args, **kwargs):
        data = request.data.copy()
        data['asset'] = kwargs.get('asset_id')
        serializer = SherdNoteSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
​

class SherdNoteTests(APITestCase):
    def test_create_sherdnote_on_own_asset(self):

        # Removing this auth block allows the test to pass
        self.u = UserFactory(username='test_user')
        self.u.set_password('test')
        self.u.save()
        login = self.client.login(username='test_user', password='test')
        assert(login is True)

        asset = AssetFactory(primary_source='image', author=self.u)
        url = reverse('sherdnote-create', kwargs={'asset_id': asset.pk})
        data = {
            'title': 'note title',
            'body': 'note body'
        }
        response = self.client.post(url, data, format='json')

        # This fails with a 405!                                                                                                                                                                     
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

urls.py 中的路由:

     url(r'^(?P<asset_id>\d+)/sherdnote/create/$',
         SherdNoteCreate.as_view(),
         name='sherdnote-create'),

这是上面测试中打印出的responseresponse.__dict__

<HttpResponseNotAllowed [GET, HEAD, OPTIONS] status_code=405, "text/html; charset=utf-8">
{'_headers': {'content-type': ('Content-Type', 'text/html; charset=utf-8'), 'allow': ('Allow', 'GET, HEAD, OPTIONS'), 'vary': ('Va
ry', 'Origin, Cookie'), 'x-frame-options': ('X-Frame-Options', 'SAMEORIGIN'), 'content-length': ('Content-Length', '0')}, '_closab
le_objects': [<WSGIRequest: POST '/asset/1/sherdnote/create/'>], '_handler_class': None, 'cookies': <SimpleCookie: >, 'closed': Tr
ue, '_reason_phrase': None, '_charset': None, '_container': [b''], 'wsgi_request': <WSGIRequest: POST '/asset/1/sherdnote/create/'
>, 'client': <rest_framework.test.APIClient object at 0x7f9880902f10>, 'request': {'PATH_INFO': '/asset/1/sherdnote/create/', 'REQ
UEST_METHOD': 'POST', 'SERVER_PORT': '80', 'wsgi.url_scheme': 'http', 'CONTENT_LENGTH': 41, 'CONTENT_TYPE': 'application/json; cha
rset=None', 'wsgi.input': <django.test.client.FakePayload object at 0x7f987e834790>, 'QUERY_STRING': ''}, 'templates': [], 'contex
t': None, 'json': <function curry.<locals>._curried at 0x7f988018e440>, 'resolver_match': <SimpleLazyObject: <function Client.requ
est.<locals>.<lambda> at 0x7f988018eef0>>, '_dont_enforce_csrf_checks': True}

我一直无法追踪为什么会发生这种情况。 有没有人有任何想法?

好的,我的应用程序中有一些课程中间件干扰了我的 API 请求。 解决方案是制作一个示例课程,并在提出请求之前让我的测试用户成为该课程的学生。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM