Skip to content

Instantly share code, notes, and snippets.

@slacy
Created October 26, 2012 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slacy/3961881 to your computer and use it in GitHub Desktop.
Save slacy/3961881 to your computer and use it in GitHub Desktop.
Broken code for trying to test that __str__() is called on a MagicMock instance.
"""
Example code that illustrates how un-intuitive it is to assert that the __str__() method of a MagicMock
instance was called. I'm not even sure how to git this test code to work correctly.
"""
import mock
from mock import call
def main():
mocked_class = mock.MagicMock()
# Imagine that these method calls are made in our application code.
mocked_class.foo()
# We've overridden __str__ so it's important to test that too.
_a_str = str(mocked_class)
# Now our test is over and we want to validate that the mocks were called in the way we expect.
# Show all mocked methods that were called:
print mocked_class.mock_calls
# prints: [call.foo(), call.__str__()]
# Now, from the above output, try to construct an array that we can compare against.
expected = [call.foo(), call.__str__()]
print expected
# prints: [call.foo(), 'call'] XXX ???
# The line below fails with "too many values to unpack" because it's trying to compare the
# mock call.__str__() with the string 'call'.
assert(mocked_class.mock_calls == expected)
if __name__ == '__main__':
main()
@deedf
Copy link

deedf commented Oct 2, 2022

expected = [call.foo(), ('str',)]

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