断言已设置*任意*属性
我有一个Python的mock对象,我想检查一下这个对象的任何属性是否被设置过。
我觉得PropertyMock不适合我,因为我需要知道是否有任何属性被设置,而不是某个特定的属性。
而且,看起来我也不能模拟一个mock对象的__setattr__
方法。
那么,我该如何测试一个mock对象的任意属性是否被设置过呢?
1 个回答
2
虽然这个方法不是最好的,但你可以在初始化模拟对象后,保存它的属性,然后在测试时和之前的属性进行比较。
>>> myobj = Mock()
>>> attrsbefore = set(dir(myobj))
>>> attrsbefore
set(['reset_mock', 'method_calls', 'assert_called_with', 'call_args_list', 'mock_calls', 'side_effect', 'assert_called_once_with', 'assert_has_calls', 'configure_mock', 'attach_mock', 'return_value', 'call_args', 'assert_any_call', 'mock_add_spec', 'called', 'call_count'])
>>> myobj.foo = 'bar'
>>> set(dir(myobj)) - attrsbefore
set(['foo'])
这个方法需要你额外保存一些状态,而且并不能严格测试某个属性是否被设置,只是比较了两个时间点的属性差异。