Last active
March 25, 2017 01:31
-
-
Save kstrauser/ad8e4125460b02de9b5514934f56f0f6 to your computer and use it in GitHub Desktop.
Use assert functions instead of methods to avoid insidious test problems
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> import mock | |
>>> m = mock.Mock() | |
>>> m.assert_called_once() # Old version of Mock? This may not be what you expect. | |
<Mock name='mock.assert_called_once()' id='4558624144'> | |
>>> assert_called_once = mock.Mock.assert_called_once # Doesn't exist. Now you know! | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
AttributeError: type object 'Mock' has no attribute 'assert_called_once' | |
>>> assert_called_once_with = mock.Mock.assert_called_once_with # There it is. | |
>>> assert_called_once_with(m) # This does the right thing. | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
File ".../mock.py", line 845, in assert_called_once_with | |
raise AssertionError(msg) | |
AssertionError: Expected to be called once. Called 0 times. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
mock
is a beautiful and incredibly useful module, but it's easy to misspell its.assert_*
methods. Starting in Python 3.5, misspelling a method starting with.assert
or.assret
will raise an AttributeError. But even with that help,my_mock.ssert_called_once_with()
(missing the "a" in "assert") will cheerfully succeed. If your mock assertions are critical - and why would you be testing them if they're not? - consider writing them as function calls instead of method invocation.Remember that given
obj = Cls()
, thatobj.method()
is exactly the same asCls.method(obj)
. You can define a list of assert functions that you'd like to use and call only those functions, not the methods they represent. Then your tests will fail with aNameError
if you ever misspell a function and good editors will alert you to the problem as you code.