Sunday, September 22, 2013

python mock: Diffference between Mock and MagicMock

note: why use mock/fake/stub object for unit test:

Using mock objects allows developers to:
  1. write and unit-test functionality in one area without actually calling complex underlying or collaborating classes
  2. focus their tests on the behavior of the system under test (SUT) without worrying about its dependencies
When mock objects are replaced by real ones then the end-to-end functionality will need further testing. These will be integration tests rather than unit tests.

Mock and MagicMock objects create all attributes and methods as you access them and store details of how they have been used.

Mock allows you to assign functions (or other Mock instances) to magic methods and they will be called appropriately. The MagicMock class is just a Mock variant that has all of the magic methods pre-created for you (well, all the useful ones anyway) - (per http://www.voidspace.org.uk/python/mock/#quick-guide)

example:

>>> import mock
>>> mock1 = mock.Mock()
>>> mock2 = mock.MagicMock()

>>> mock2.__str__.return_value = 'foobarbaz'
>>> str(mock2)
'foobarbaz'
>>> mock2.__str__.assert_called_with()

>>> mock1.__str__.return_value = 'foobarbaz'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'method-wrapper' object has only read-only attributes (assign to .return_value)

# ah, there it is, i have to configure __str___ behavior

>>> mock1.__str__ = mock.Mock(return_value='wheeeeee')
>>> str(mock1)
'wheeeeee'

1 comment: