[Fixed]-How to mock chained function calls in python?

24👍

Each mock object holds onto the mock object that it returned when it is called. You can get a hold of it using your mock object’s return_value property.

For your example,

self.assertTrue(query_mock.distinct.called)

distinct wasn’t called on your mock, it was called on the return value of the filter method of your mock, so you can assert that distinct was called by doing this:

self.assertTrue(query_mock.filter.return_value.distinct.called)

Leave a comment