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

标签 python django rest testing django-rest-framework

我正在测试 CreateAPIViewAPITestCase类(class)。作为匿名用户,事情按预期工作,但是当我作为用户 login() 时,我得到 405 HttpResponseNotAllowed异常(exception)。我能够成功创建一个对象,同时通过 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}

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

最佳答案

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

关于python - 测试经过身份验证的 django-rest-framework 路由时出现 405 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60895576/

相关文章:

python - Django:动态模型字段和迁移

node.js - Mongoose - REST API - 查询不同模型的模式

python - Matlab 的 fminimax 是否适用帕累托最优?

python - 保存抓取的项目和文件时,Scrapy 在输出 csv 文件中插入空行

python - manjaro linux 上 opencv 中的 ImportError

Python - 检查字典中是否存在列表项

python - 内置登录 User.objects.all() 上的 Django 模板标签

python - 类型错误 : __call__() missing 1 required positional argument: 'send' Django

rest - Bugzilla rest api 激活

java - 使用多个 namespace 解码