简体   繁体   中英

Assert that *any* attribute was set

I have a Python mock object and I would like to assert whether any attribute of that object was set.

I do not believe the PropertyMock will work for my purposes, because I must know if any attribute was set, not a particular property.

It also does not appear like I can mock the __setattr__ method of a mock object.

How can I test if any arbitrary attribute of a mock object has been set?

While this solution is not ideal, you can store the attributes of the mock object after initialization and compare them to the attributes at the time of test.

>>> 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'])

This solution requires maintaining additional state and does not strictly test whether an attribute is set, only the difference in attributes at two points in time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM