[英]Response.status_code 400 for a simple view test
I'm passing a simple json body to my view but I'm getting a 400 instead of a 200. It should be a really straightforward test but I can't quite figure out what is wrong.我将一个简单的 json 正文传递到我的视图中,但我得到的是 400 而不是 200。这应该是一个非常简单的测试,但我不太清楚哪里出了问题。 Thanks.谢谢。
Url: Url:
"api/v2/ada/send",
views.sendView.as_view(),
name="ada-send",
),
View:看法:
class sendView(generics.GenericAPIView):
permission_classes = (permissions.IsAuthenticated,)
def post(self, request, *args, **kwargs):
body = request.data
return Response(body, status=status.HTTP_200_OK)
View Test:查看测试:
class AdaSendGet(APITestCase):
url = reverse("ada-send")
def test_choice_type_valid(
self,):
user = get_user_model().objects.create_user("test")
self.client.force_authenticate(user)
response = self.client.post(
self.url,
{
"contact_uuid": "49548747-48888043",
"choices": 3,
"message": (
"What is the issue?\n\nAbdominal pain"
"\nHeadache\nNone of these\n\n"
"Choose the option that matches your answer. "
"Eg, 1 for Abdominal pain\n\nEnter *back* to go to "
"the previous question or *abort* to "
"end the assessment"
),
"step": 6,
"value": 2,
"optionId": 0,
"path": "/assessments/assessment-id/dialog/next",
"cardType": "CHOICE",
"title": "SYMPTOM"
},
content_type="application/json",
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
Error:错误:
self.assertEqual(response.status_code, status.HTTP_200_OK)
AssertionError: 400 != 200
response.json() returns: response.json() 返回:
{'detail': 'JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)'}
Weird one here.这里很奇怪。 I solved it by removing我通过删除解决了
content_type="application/json",
from the payload.从有效载荷。
As they mentioned in the documentation here https://www.django-rest-framework.org/api-guide/testing/#api-test-cases正如他们在此处的文档中提到的那样https://www.django-rest-framework.org/api-guide/testing/#api-test-cases
When you want to specify the format you should use format argument.当你想指定格式时,你应该使用格式参数。
Methods which create a request body, such as post, put and patch, include a format argument, which make it easy to generate requests using a content type other than multipart form data.创建请求正文的方法,例如 post、put 和 patch,包括格式参数,这使得使用多部分表单数据以外的内容类型生成请求变得容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.