[issue43371] Mock.assert_has_calls works strange

Mardoxx report at bugs.python.org
Thu Jul 8 19:29:43 EDT 2021


Mardoxx <mardoxx at gmail.com> added the comment:

This is surprising behaviour, Python 3.8.9:

factory = unittest.mock.Mock()

### test example
foo_obj = factory.create("foo"),do_thing()

# !! MUST BE CALLED AFTER .create("foo") !!
bar_obj = factory.create("bar").do_thing()
###

# I set any_order to false because these should be called in order.
factory.create.assert_has_calls([
    unittest.mock.call("foo"),
    unittest.mock.call("bar")
], any_order = False)

# OOPS!! this fails
# mock_calls == [call('foo'), call().do_thing(), call('bar'), call().do_thing()]
# I can however check this with...
# assert factory.create.call_args_list == [
#     unittest.mock.call("foo"),
#     unittest.mock.call("bar")
# ]

Am I fundamentally misunderstanding something here?

This appears to be different behaviour from assert_has_awaits, which adds to the confusion. assert_has_calls checks mock_calls, I'd have thought it should check call_args_list. Another method assert_mock_calls should check mock_calls for consistency? Or have I missed something here?

Perhaps an additional flag of in_sequence would be nice, defaulted to False to keep the existing unusual behaviour.
When False, calls must be in exactly the order they are described.
When True, calls must be in sequence (with anything in-between each call).
any_order=True overrides this and allows them to be in any order anywhere in the mock_calls list.

----------
nosy: +mardoxx
versions: +Python 3.8

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


More information about the Python-bugs-list mailing list