Skip to content

Instantly share code, notes, and snippets.

@kstrauser
Last active March 25, 2017 01:31
Show Gist options
  • Save kstrauser/ad8e4125460b02de9b5514934f56f0f6 to your computer and use it in GitHub Desktop.
Save kstrauser/ad8e4125460b02de9b5514934f56f0f6 to your computer and use it in GitHub Desktop.
Use assert functions instead of methods to avoid insidious test problems
>>> 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.
@kstrauser
Copy link
Author

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(), that obj.method() is exactly the same as Cls.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 a NameError if you ever misspell a function and good editors will alert you to the problem as you code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment