Mocking

Please open notebook rsepython-s2r4.ipynb

Definition

Mock: verb,

  1. to tease or laugh at in a scornful or contemptuous manner
  2. to make a replica or imitation of something

Mocking

Mocking frameworks

Recording calls with mock

Mock objects record the calls made to them:

from unittest.mock import Mock
function = Mock(name="myroutine", return_value=2)
function(1)

2

function(5, "hello", a=True)

2

function.mock_calls

[call(1), call(5, ‘hello’, a=True)]

The arguments of each call can be recovered

name, args, kwargs = function.mock_calls[1]
args, kwargs

((5, ‘hello’), {‘a’: True})

Mock objects can return different values for each call

function = Mock(name="myroutine", side_effect=[2, "xyz"])
function(1)

2

function(1, "hello", {'a': True})

‘xyz’

We expect an error if there are no return values left in the list:

function()

—————————————————————————

StopIteration Traceback (most recent call last)

in () </span>

—-> 1 function()

C:\ProgramData\Anaconda3\lib\unittest\mock.py in call(_mock_self, *args, **kwargs)

917 # in the signature

918 _mock_self._mock_check_sig(*args, **kwargs)

–> 919 return _mock_self._mock_call(*args, **kwargs) 920 921

C:\ProgramData\Anaconda3\lib\unittest\mock.py in _mock_call(_mock_self, *args, **kwargs)

976

977 if not _callable(effect):

–> 978 result = next(effect)

979 if _is_exception(result):

980 raise result

StopIteration:

Using mocks to model test resources

Often we want to write tests for code which interacts with remote resources. (E.g. databases, the internet, or data files.)

We don’t want to have our tests actually interact with the remote resource, as this would mean our tests failed due to lost internet connections, for example.

Instead, we can use mocks to assert that our code does the right thing in terms of the messages it sends: the parameters of the function calls it makes to the remote resource.

For example, consider the following code that downloads a map from the internet:

import requests

def map_at(lat,long, satellite=False, zoom=12,
           size=(400,400), sensor=False):

    base="http://maps.googleapis.com/maps/api/staticmap?"

    params=dict(
        sensor= str(sensor).lower(),
        zoom= zoom,
        size= "x".join(map(str,size)),
        center= ",".join(map(str,(lat,long))),
        style="feature:all|element:labels|visibility:off")

    if satellite:
        params["maptype"]="satellite"

    return requests.get(base,params=params)
london_map = map_at(51.5073509, -0.1277583)
from IPython.display import Image
%matplotlib inline
Image(london_map.content)

Mocks plot

We would like to test that it is building the parameters correctly. We can do this by mocking the requests object.

We need to temporarily replace a method in the library with a mock. We can use “patch” to do this:

from unittest.mock import patch
with patch.object(requests,'get') as mock_get:
    london_map=map_at(51.5073509, -0.1277583)
    print(mock_get.mock_calls)

[call(‘http://maps.googleapis.com/maps/api/staticmap?’, params={‘center’: ‘51.5073509,-0.1277583’, ‘sensor’: ‘false’, ‘style’: ‘feature:all|element:labels|visibility:off’, ‘size’: ‘400x400’, ‘zoom’: 12})]

Our tests then look like:

def test_build_default_params():
    with patch.object(requests,'get') as mock_get:
        default_map=map_at(51.0, 0.0)
        mock_get.assert_called_with(
        "http://maps.googleapis.com/maps/api/staticmap?",
        params={
            'sensor':'false',
            'zoom':12,
            'size':'400x400',
            'center':'51.0,0.0',
            'style':'feature:all|element:labels|visibility:off'
        }
    )
test_build_default_params()

That was quiet, so it passed. When I’m writing tests, I usually modify one of the expectations, to something ‘wrong’, just to check it’s not passing “by accident”, run the tests, then change it back!

Testing functions that call other functions

def partial_derivative(function, at, direction, delta=1.0):
    f_x=function(at)
    x_plus_delta=at[:]
    x_plus_delta[direction]+=delta
    f_x_plus_delta=function(x_plus_delta)
    return (f_x_plus_delta-f_x)/delta

We want to test that the above function does the right thing. It is supposed to compute the derivative of a function of a vector in a particular direction.

E.g.:

partial_derivative(sum, [0,0,0], 1)

1.0

How do we assert that it is doing the right thing? With tests like this:

from unittest.mock import MagicMock

def test_derivative_2d_y_direction():
    func=MagicMock()
    partial_derivative(func, [0,0], 1)
    func.assert_any_call([0, 1.0])
    func.assert_any_call([0, 0])


test_derivative_2d_y_direction()

We made our mock a “Magic Mock” because otherwise, the mock results f_x_plus_delta and f_x can’t be subtracted:

MagicMock()-MagicMock()

<MagicMock name=’mock.sub()’ id=’2295172443048’>

Mock()-Mock()

—————————————————————————

TypeError Traceback (most recent call last)

in () </span>

—-> 1 Mock()-Mock()

TypeError: unsupported operand type(s) for -: ‘Mock’ and ‘Mock’

Next: Reading - Debugger