classification
Title: Provide assertion functions in unittest.mock
Type: Stage:
Components: Tests Versions: Python 3.7
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: odd_bloke, ppperry, tribaal
Priority: normal Keywords:

Created on 2017-07-17 14:36 by odd_bloke, last changed 2017-07-17 20:29 by ppperry.

Messages (2)
msg298533 - (view) Author: Daniel Watkins (odd_bloke) * Date: 2017-07-17 14:36
The convenience assertion methods on mock objects can be easily mistyped and if they are mistyped, they will silently pass.  This can be quite user-hostile.  Consider the following:

>>> example = Mock()
>>> example.assert_called_once()
>>> example.assert_caled_once_with(...)

This will not raise any exceptions, though the first feels natural and the latter is misspelt.  To avoid using the methods, one can type:

>>> example = Mock()
>>> assert example.call_count == 1
>>> assert example.call_args_list == [call(...)]

but the meaning of that latter statement is particularly non-obvious.  Instead, it would be great if I could import the assertions from mock as functions, and call them with mock as the first argument:

>>> from unittest.mock import assert_called_once  # This will be an ImportError
>>> example = Mock()
>>> assert_caled_once_with(example, ...)  # A NameError
>>> assert_called_once_with(example, ...)  # Great success!
msg298553 - (view) Author: (ppperry) Date: 2017-07-17 20:29
You can already do this, although it it somewhat of a hack:

>>> assert_called_once=Mock.assert_called_once # This will be an AttributeError
>>> assert_called_once_with=Mock.assert_called_once_with
>>> example = Mock()
>>> assert_caled_once_with(example, ...)  # A NameError
>>> assert_called_once_with(example, ...)  # Great success!
History
Date User Action Args
2017-07-17 20:29:52ppperrysetnosy: + ppperry
messages: + msg298553
2017-07-17 14:40:49tribaalsetnosy: + tribaal
2017-07-17 14:36:43odd_blokecreate