Django APIClient测试用例返回400,但邮递员可以工作

时间:2019-10-11 06:31:12

标签: django python-3.x django-rest-framework

我的tests.py中有这些测试用例

"""Unit tests for client application."""

from django.test import TestCase
from rest_framework.test import APIClient
# Create your tests here.

class ClientTestCase(TestCase):
    api_client = APIClient()
    def test_get_clients(self):
        response = self.api_client.get('http://127.0.0.1:8000/client/clients/')
        self.assertEqual(int(response.status_code), 200)

    def test_add_client(self):
        response = self.api_client.post(
            path='http://127.0.0.1:8000/client/clients/',
            data={
                'name': 'Jon Snow',
                'age': 18,
                'gender': 'M',
                'address': 'night watch wall',
                'phone_number': '+9290078601',
                'email': 'jon@nightwatch.com',
            },
            content_type='application/json'
        )
        self.assertEqual(response.status_code, 201)

当我通过命令运行这些测试时

python manage.py test --debug-mode client/ -v 3

test_get_clients成功,而test_add_client失败,因为API返回了400
当我使用test_add_clientpostman的相同API时,它将返回预期的结果。
postman API的主体是

{
    "name": "Bruce Wayne",
    "age" : 23,
    "gender" : "M",
    "address" : "abc asdasd asdasd asdada",
    "phone_number" : "+92 3242225259",
    "email" : "abc@xyz.com"
}

,并且在标头中有Conent-Type:'application/json,正如我在测试用例中已经指定的那样。
我在这里可能会缺少什么?运行测试用例的输出根本无法提供任何见识。

1 个答案:

答案 0 :(得分:0)

我认为您需要json.dump您的数据:

import json

def test_add_client(self):
    response = self.api_client.post(
        path='http://127.0.0.1:8000/client/clients/',
        data=json.dumps({
            'name': 'Jon Snow',
            'age': 18,
            'gender': 'M',
            'address': 'night watch wall',
            'phone_number': '+9290078601',
            'email': 'jon@nightwatch.com',
        }),
        content_type='application/json'
    )
    self.assertEqual(response.status_code, 201)