4

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?

Lii
  • 11,553
  • 8
  • 64
  • 88
Nathan Buesgens
  • 1,415
  • 1
  • 15
  • 29

1 Answers1

2

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.

Nathan Buesgens
  • 1,415
  • 1
  • 15
  • 29