[issue43371] Mock.assert_has_calls works strange

Roy Smith report at bugs.python.org
Sat Jan 15 22:21:02 EST 2022


Roy Smith <roy at panix.com> added the comment:

I agree that this is confusing and that what we need is an assertion for the top-level mock having specific calls in a specific order, and ignores any intervening extra calls to mocked functions.  In other words, a version of assert_has_calls() which looks at call_args_list instead of mock_calls.

I just finished up a session of head-banging with some tests that were failing (Python 3.7), and eventually ended up with the

self.assertEqual(my_mock.call_args_list, [call(...), call(...)])

idiom as noted in msg397172 (but without first banging a few new dents into the top of my desk).  This exact same experience is related in a recent stackoverflow thread (https://stackoverflow.com/questions/69360318/python-unittest-mock-assert-has-calls-returning-calls-to-other-mocks) so this seems to be a common source of confusion.

I am neutral on whether this is implemented as a new flag to assert_has_calls() or as a new assertion method.

As an aside, what I was trying to do was test if my code constructed its several instances of a class in the correct way.  At one point I hit upon the idea of:

MyMockedClass().__init__.assert_has_calls(....)

which expressed my desired logic exactly and simply, but couldn't get that to work.  It's unclear if I just never found the proper incantation, or if that's fundamentally unworkable.

----------
nosy: +roysmith

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43371>
_______________________________________


More information about the Python-bugs-list mailing list