Custom Search

Monday, December 8, 2014

OpenStack Python UnitTest with Mock Patching Library

* Mock is based on the 'action -> assertion' pattern instead of 'record -> replay'.


mock.patch('').start().side_effect = FAKE_SERVER.request


import requests
import mock

pobj = mock.patch('') #Returns object of "mock._patch" class
help(pobj)##check the definition of "mock._patch" class
dir(pobj)##Here, you can find 'start()' method

help(pobj.start)##Activate a patch, returning any created mock.
help(pobj.stop)##Stop an active patch.

mobj = pobj.start()##Returns object of "MagicMock" class
help(mobj)##check the definition of "MagicMock" class
dir(mobj)##Here, you can find 'side_effect' attribute


* Find the doc string of "side_effect"
"side_effect": A function to be called whenever the Mock is called. See
the `side_effect` attribute. Useful for raising exceptions or
dynamically changing return values. The function is called with the same
arguments as the mock, and unless it returns `DEFAULT`, the return
value of this function is used as the return value.

Alternatively `side_effect` can be an exception class or instance. In
this case the exception will be raised when the mock is called.

If `side_effect` is an iterable then each call to the mock will return
the next value from the iterable. If any of the members of the iterable
are exceptions they will be raised instead of returned.


>>> def test():
    return "Hello"

>>> mock.patch('').start().side_effect = test

>>> Hello

* "return_value": The value returned when the mock is called. By default
this is a new Mock (created on first access). See the
`return_value` attribute.

* Auto-speccing creates mock objects that have the same attributes and methods as the objects they are replacing, and any functions and methods (including constructors) have the same call signature as the real object.Auto-speccing can be done through the autospec argument to patch.

No comments:

Post a Comment