如何在 Python 中编写自定义的 `.assertFoo()` 方法? [英] How to write a custom `.assertFoo()` method in Python?
问题描述
我正在使用 Python 的 unittest
为我的应用程序编写一些测试用例.现在我需要将一个对象列表与另一个对象列表进行比较,以检查第一个列表中的对象是否符合我的预期.
I'm writing some test cases for my application using Python's unittest
. Now I need to compare a list of objects with a list of another objects to check if the objects from the first list are what I'm expecting.
如何编写自定义 .assertFoo()
方法?它应该怎么做?它应该在失败时引发异常吗?如果是,哪个例外?以及如何传递错误信息?错误信息应该是 unicode 字符串还是字节字符串?
How can I write a custom .assertFoo()
method? What should it do? Should it raise an exception on failure? If yes, which exception? And how to pass the error message? Should the error message be a unicode string or a bytestring?
遗憾的是,官方文档 没有解释如何编写自定义断言方法.
Unfortunately, the official documentation doesn't explain how to write custom assertion methods.
如果您需要一个真实的例子,请继续阅读.
If you need a real-world example for this, continue reading.
我写的代码有点像这样:
The code I'm writing is somewhat like this:
def assert_object_list(self, objs, expected):
for index, (item, values) in enumerate(zip(objs, expected)):
self.assertEqual(
item.foo, values[0],
'Item {0}: {1} != {2}'.format(index, item.foo, values[0])
)
self.assertEqual(
item.bar, values[1],
'Item {0}: {1} != {2}'.format(index, item.bar, values[1])
)
def test_foobar(self):
objs = [...] # Some processing here
expected = [
# Expected values for ".foo" and ".bar" for each object
(1, 'something'),
(2, 'nothing'),
]
self.assert_object_list(objs, expected)
这种方法可以非常轻松地以非常紧凑的方式描述每个对象的预期值,而无需实际创建完整的对象.
This approach makes it extremely easy to describe the expected values of each object in a very compact way, and without needing to actually create full objects.
然而……当一个对象断言失败时,不再比较其他对象,这使得调试更加困难.我想编写一个自定义方法,它可以无条件地比较所有对象,然后显示所有失败的对象,而不仅仅是第一个.
However... When one object fails the assertion, no further objects are compared, and this makes debugging a bit more difficult. I would like to write a custom method that would unconditionally compare all objects, and then would display all objects that failed, instead of just the first one.
推荐答案
我在这些情况下使用多重继承.例如:
I use the multiple inheritance in these cases. For example:
首先.我定义了一个包含将合并的方法的类.
First. I define a class with methods that will incorporate.
import os
class CustomAssertions:
def assertFileExists(self, path):
if not os.path.lexists(path):
raise AssertionError('File not exists in path "' + path + '".')
现在我定义了一个继承自 unittest.TestCase 和 CustomAssertion 的类
Now I define a class that inherits from unittest.TestCase and CustomAssertion
import unittest
class MyTest(unittest.TestCase, CustomAssertions):
def test_file_exists(self):
self.assertFileExists('any/file/path')
if __name__ == '__main__':
unittest.main()
这篇关于如何在 Python 中编写自定义的 `.assertFoo()` 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!