【发布时间】: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