Reputation: 393
In the following code, is there a way to assert that the query
attribute has been set if search is a mock object? Or if query
was the mock object, is there a way to do it?
search.query = Q('bool', must=must)
So far I've found out that Python unittest.mock only supports asserting that mocks have been called as functions. Also the setattr magic method can not be mocked so search.__setattr__
can not be used to assert the above.
Upvotes: 6
Views: 4056
Reputation: 5939
Maybe I misunderstood your point, but why not simply run the code under test and afterwards check that search
has got that expected attribute query
and that search.query
holds the expected value? For example (I assigned search
a MagicMock
object because according to your description it probably has to be. For the sake of the following example it would not be necessary that search
is a MagicMock
or any kind of mock):
# setup
search = MagicMock()
# when exercised, your code under test would do:
search.query = 42
# afterwards you validate that search.query holds the value you expect:
self.assertTrue(hasattr(search, 'query'))
self.assertEqual(search.query, 42)
Upvotes: 4