【问题标题】:DRF test for APIView returns 400APIView 的 DRF 测试返回 400
【发布时间】:2021-05-07 14:32:46
【问题描述】:

我知道这已经有很多相同的问题,但它对我没有帮助,所以我需要任何关于错误所在的想法。 我有一个超级简单的 DRF APIView(所有导入都很好):

class MyView(APIView):
  permission_classes = (AllowAny,)

  def post(self, request: Request) -> Response:
    return Response({'status': 'success'}, status=status.HTTP_200_OK)

这是我的测试(忽略有效载荷,它只是为了这个问题而简化):

    import json
    from django.urls import reverse
    from rest_framework.test import APITestCase
    from web.models import User

    class MyViewViewTestCase(APITestCase):

      def setUp(self):
        self.username = 'test@example.com'
        self.pwd = '1234'
        self.user = User.objects.create_user(self.username, self.pwd)

      def request(self, data):
        self.client.login(username=self.username, password=self.pwd)
        return self.client.post(reverse('my-view-url-name'), data=data, format='json')

      def test_my_view(self):
        response = self.request(json.dumps({
            'some-data': 'some-data',
        }))
        print(response.content)

        self.assertEqual(response.status_code, 200)

所以,我得到的是 400 而不是 200。响应类型是

而 response.content 是:

b'\n<!doctype html>\n<html lang="en">\n<head>\n  <title>Bad Request (400 </title>\n</head>\n<body>\n  <h1>Bad Request (400)</h1><p></p>\n</body>\n</html>\n'

因此,考虑到 api 视图预计将返回 200 没有任何其他操作,我猜我在测试中做错了什么,但无法得到究竟是什么。有什么想法我可能错了吗? View 本身可以正常工作。 谢谢!

【问题讨论】:

  • 当 format="json" 你不必 json.dumps 数据。它在内部进行。还在开发环境的 Django 设置中设置 DEBUG=True 以获得更多信息。
  • 谢谢!我绝对确定 DEBUG 已经设置,但是你的评论让我对此表示怀疑,我发现如果你在 settings.py 中设置 DEBUG 它将不起作用,所以你必须明确地使用 @override_settings(DEBUG=True) 或通过使用--debug-mode

标签: python django django-rest-framework


【解决方案1】:

找到了解决办法!感谢 Igor Moraru 的建议。所以我的第一个问题是我绝对确定测试已经在调试模式下运行(设置为 DEBUG=True)。我发现它实际上不是真的,所以你必须通过使用 --debug-mode 选项运行测试来明确地做到这一点:

./manage.py test --debug-mode

或者使用@override_settings(DEBUG=True):

      from django.test.utils import override_settings      

      @override_settings(DEBUG=True)
      def test_my_view(self):
        response = self.request({
            'some-data': 'some-data',
        })
        print(response.content)

        self.assertEqual(response.status_code, 200)

在那之后我得到了更多的错误信息:

DisallowedHost at /api/v1/my_view/
Invalid HTTP_HOST header: 'testserver'. You may need to add 'testserver' to ALLOWED_HOSTS.

只需将testserver 添加到ALLOWED_HOSTS 即可轻松解决:

ALLOWED_HOSTS = ['testserver'] # here may be other allowed hosts, you need just to add one more

【讨论】:

    猜你喜欢
    • 2018-06-12
    • 2015-04-08
    • 2015-04-27
    • 2021-04-20
    • 1970-01-01
    • 2015-12-01
    • 2017-08-26
    • 1970-01-01
    • 2023-01-18
    相关资源
    最近更新 更多