Pytest和Pytest -django以assert错误结束



我在过去的30分钟里一直在处理这个问题,我只是想继续前进。基本上,测试返回断言错误:

E       AssertionError: assert {} == {'rant': 'Kulugo', 'slug': 'apostrophe'}
E         Right contains 2 more items:
E         {'rant': 'Kulugo', 'slug': 'apostrophe'}
E         Full diff:
E         - {'rant': 'Kulugo', 'slug': 'apostrophe'}
E         + {}
tests/rants/test_serializers.py:26: AssertionError

现在跟踪第26行中的错误:assert serializer.data == invalid_serializer_data

我希望一切都能通过,因为这个编写的代码是基于testdriven.io

的教程。完整代码:

from main.serializers import RantSerializer, CategorySerializer

def test_valid_rant_serializer():
valid_serializer_data = {
'id': 1,
'title': "First Rant",
'slug': "first-rant",
}
serializer = RantSerializer(data=valid_serializer_data)
assert serializer.is_valid()
assert serializer.validated_data == valid_serializer_data
assert serializer.data == valid_serializer_data
assert serializer.errors == {}

def test_invalid_rant_serializer():
invalid_serializer_data = {
'rant': 'Kulugo',
'slug': 'apostrophe'
}
serializer = RantSerializer(data=invalid_serializer_data)
assert not serializer.is_valid()
assert serializer.validated_data == {}
assert serializer.data == invalid_serializer_data
assert serializer.errors == {"id": ["This field is required"]}

错误:

FAILED tests/rants/test_serializers.py::test_valid_rant_serializer - AssertionError: assert False
FAILED tests/rants/test_serializers.py::test_invalid_rant_serializer - AssertionError: assert {'title': [ErrorDetail(string='This field is required.', code='required')], 'categories': [ErrorDetail(st...

您的问题是在测试用例test_invalid_rant_serializer的期望中,在这种情况下,您期望serializer.data等于invalid_serializer_data,但它不会用输入数据填充.data属性。

为了解决这个问题,我们可以删除检查serializer.datainvalid_serializer_data之间是否相等的行,如下所示:

def test_invalid_rant_serializer():
invalid_serializer_data = {
'rant': 'Kulugo',
'slug': 'apostrophe'
}
serializer = RantSerializer(data=invalid_serializer_data)
assert not serializer.is_valid()
assert serializer.validated_data == {}
# Remove the following line
# assert serializer.data == invalid_serializer_data
assert serializer.errors == {"id": ["This field is required"]}

相关内容

  • 没有找到相关文章

最新更新