[英]Python: can unittest display expected and actual values?
If I have an assert in a unittest.TestCase as shown below: 如果我在unittest.TestCase中有一个断言,如下所示:
self.assertTrue( person.age == 42, "age incorrect")
When it fails, it gives the "age incorrect" message. 当它失败时,它会给出“年龄不正确”的消息。 What I would also like to see is the expected and actual values. 我还希望看到的是预期值和实际值。 What's the best way to go about doing this? 这样做的最佳方法是什么? Is it something unittest can do? 是单位测试可以做的吗?
EDIT I would like to see something like: 编辑我想看到类似的东西:
"age incorrect: expected value 42 actual value 39" “年龄不正确:预期值42实际值39”
you can set the longMessage
attribute to True
您可以将longMessage
属性设置为True
expected_age = 42
actual_age = person.age # 39
self.longMessage = True
self.assertEqual(expected_age, actual_age, 'age incorrect')
you would get something like: 你会得到类似的东西:
AssertionError: 42 != 39 : age incorrect
reference: https://docs.python.org/2/library/unittest.html#unittest.TestCase.longMessage 参考: https : //docs.python.org/2/library/unittest.html#unittest.TestCase.longMessage
You should use a workaround to this problem, like this: 您应该使用解决此问题的方法,如下所示:
self.assertEqual(person.age, 42, 'age incorrect: expected value {0} actual value {1}'.format(42, person.age))
But i think not providing the "msg" parameter is the best option, since it generates the text: 但我认为不提供“msg”参数是最好的选择,因为它生成文本:
first != equal
Most(*) tools for running tests also shows directly which line failed, thus you should be able to understand which test failed and why without using an extra message. 用于运行测试的大多数(*)工具也直接显示哪个行失败,因此您应该能够了解哪个测试失败以及为什么不使用额外的消息。
(*) read "all". (*)读“全部”。
see: assertEqual 见: assertEqual
self.assertEqual(person.age, 42, 'age incorrect')
or with the default message (to answer the comment): 或者使用默认消息(回答评论):
self.assertEqual(person.age, 42)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.