簡體   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