Django assertEqual不显示实际值与期望值

时间:2012-11-03 17:13:38

标签: django tdd assertions

所以我正在学习如何在Django中练习TDD,而且我遇到了一些小麻烦。我创建了一个自定义用户对象,该对象以一对一的关系链接到经过身份验证的系统用户。我有以下测试,它练习我的自定义用户类的一部分:

def test_creating_a_user_with_attributes(self):
    myuser = Myuser.objects.create_user('Gary', email='me@email.com')
    current_time = now()
    myuser.birthday = current_time
    myuser.save()
    first_user = Myuser.objects.all()[0]
    self.assertEqual(first_user.birthday, current_time, 'first_user.birthday should be equal to the current_time')

问题是我的测试失败了,我无法立即看到原因。断言失败报告了我提供的消息,我感到困惑,因为我确定生日被设置为现在的值。我最终不得不重构我的断言以使失败的值清晰。

    self.assertEqual(first_user.birthday, current_time,
        'first_user.birthday ' + str(first_user.birthday) + ' should equal ' + str(current_time))

这表明生日是日期字段而不是日期时间字段。我的问题是,是否存在一些替代形式的断言,它将预期值和实际值转储为失败消息的一部分,或者我是否在某种程度上滥用或误解了API?

2 个答案:

答案 0 :(得分:5)

Django没有实现assertEqual,它只是使用Python的unittest模块。

您需要为您的测试用例类设置longMessage属性为True,如下所示:

class VerboseTestCase(TestCase):
    longMessage = True

    def test_creating_a_user_with_attributes(self):
        myuser = Myuser.objects.create_user('Gary', email='me@email.com')
        current_time = now()
        myuser.birthday = current_time
        myuser.save()
        first_user = Myuser.objects.all()[0]
        self.assertEqual(first_user.birthday, current_time, 'first_user.birthday should be equal to the current_time')

如果测试失败,将输出类似的内容:

AssertionError: <datetime 1> != <datetime 2> : first_user.birthday should be equal to the current_time

Python's unittest docs中解释了这一点。

答案 1 :(得分:2)

默认错误消息 显示失败的值。但是你通过向assertEqual提供第三个参数来覆盖它。如果你把它遗漏了,它会打印出值。

正如Gonzalo所说,你可以使用longMessage属性实现两全其美。