Python - 单元测试:如果它们真的是同一个对象,则使用它们的属性来比较一些对象?

Python - unittests: compare some objects using their attributes instead if they are really the same object?

我有将数据设置到 class 属性的方法。

假设我 运行:

self._set_data(some_data)
print self._data

它向我打印了以下信息:

{'c2': {
    'column': 1, 
    'style': <xlwt.Style.XFStyle object at 0x7f4668a18dd0>, 
    'value': u'Argentina', 'row': 2}, 
'c1': {
    'column': 0, 
    'style': <xlwt.Style.XFStyle object at 0x7f4668a18dd0>, 
    'value': 'C is not Python', 'row': 0}}

所以除了 style 之外的每个键都有简单的数据,所以在 运行 单元测试时检查预期的内容没有问题。但是我用 style 键看到的问题是,它 returns 实例化了 xlwt 模块的样式对象。现在,即使我使用与 __init__ 相同的值创建 "same" 样式,unittest 仍然会失败,因为它会比较对象,所以它会是不同的对象。 python 标准单元测试套件有类似的东西吗?或者我需要扩展 unittests 套件,所以它会以某种方式不同地比较特定对象?

在您的测试中,您可以创建一个使用预期值初始化的模拟样式对象,然后将其 __dict__ 属性与测试样式对象的 __dict__ 属性进行比较。

if mock_style.__dict__ == tested_style.__dict__ :
    print('The styles are set correctly.')