AssertionError:400!= 201运行TestCase时

时间:2018-01-17 11:44:28

标签: python python-3.x django-rest-framework foreign-keys http-status-code-400

我是Django的新手。当我运行命令python manage.py test时,我一直收到以下错误;

Tact/tact_api/lines/test_views.py", line 103, in 
test_api_can_create_an_event
self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)
AssertionError: 400 != 201

----------------------------------------------------------------------
Ran 8 tests in 0.105s

我非常感谢您解决此问题的任何帮助!我自己的一些想法包括:

1)我的Event对象post请求中可能存在语法错误。请参阅下面的测试代码 2)问题可能与配置有关。

供参考,请参阅以下测试;

class EventViewTestCase(TestCase):
"""
Test suite for Event API views
"""
def setUp(self):
    """
    Define the event test client and other test variables.
    """
    user = User.objects.create(username="tactician")

    # initialize client and force authentication
    self.client = APIClient()
    self.client.force_authenticate(user=user)

    # create and post a new line using authorized user
    # since user model instance is not serializable, use its Id/PK
    self.line_data = {'owner': user.id, 'title': 'Title goes here'}
    self.res = self.client.post(reverse('line-list'), self.line_data, format='json')

    # create and post a new event linked to created line using authorized user
    line = Line.objects.get()
    self.event_data = {'owner': user.id, 'pk': line.id, 'title': 'Title goes here',
                       'desc': 'Desc. here', 'start': timezone.now(), 'end': timezone.now()}
    self.response = self.client.post(reverse('event-list'), self.event_data, format='json')

def test_api_can_create_an_event(self):
    """
    Test the api has event creation capability.
    """
    self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)

串行器;

class EventSerializer(serializers.HyperlinkedModelSerializer):
"""
Convert Event model instance into native Python datatypes to be rendered as JSON.
"""
owner = serializers.ReadOnlyField(source='owner.username')

class Meta:
    model = Event
    fields = ('url', 'id', 'owner', 'created', 'modified', 'title', 'desc', 'start',
              'end', 'line')

def get_fields(self, *args, **kwargs):
    """
    create and return a new Event object (linked to a user owned Line) with validated data.

    update and return an existing Event object with validated data.
    """
    fields = super(EventSerializer, self).get_fields(*args, **kwargs)
    view = self.context['view']
    owner = view.request.user
    fields['line'].queryset = fields['line'].queryset.filter(owner=owner)
    return fields

1 个答案:

答案 0 :(得分:1)

此问题现已解决。

首先,在我的测试套件中,我提供给post请求的事件有效负载数据中存在轻微的语法错误。

self.event_data = {'owner': user.id, 'pk': line.id...}

已更改为是我在事件模型中指定的外键字段名称。)

self.event_data = {'owner': user.id, 'line': line.id...}

其次,对于我的Event序列化程序,我使用了错误的基类;

class EventSerializer(serializers.HyperlinkedModelSerializer)

更改为

class EventSerializer(serializers.ModelSerializer)