MagicMock instances that are normally used as replacement values are meant to mimic callables and instances. They record information about usage and allow to make assertions as shown in the code given below –
from unittest.mock import MagicMock m = MagicMock(return_value = 10 ) print (m( 1 , 2 , debug = True ), "\n" ) m.assert_called_with( 1 , 2 , debug = True ) m.assert_called_with( 1 , 2 ) |
Output :
10 Traceback (most recent call last): File "", line 1, in File ".../unittest/mock.py", line 726, in assert_called_with raise AssertionError(msg) AssertionError: Expected call: mock(1, 2) Actual call: mock(1, 2, debug=True)
Code #7 : Replacing the value by supplying it as a second argument to patch()
print ( "x : " , x) with patch( '__main__.x' , 'patched_value' ): print (x) patched_value print ( "x : " , x) |
Output :
x : 42 x : 42
MagicMock instances that are normally used as replacement values are meant to mimic callables and instances. They record information about usage and can make assertions.
from unittest.mock import MagicMock m = MagicMock(return_value = 10 ) print (m( 1 , 2 , debug = True ), "\n" ) m.assert_called_with( 1 , 2 , debug = True ) m.assert_called_with( 1 , 2 ) |
Output :
10 Traceback (most recent call last): File "", line 1, in File ".../unittest/mock.py", line 726, in assert_called_with raise AssertionError(msg) AssertionError: Expected call: mock(1, 2) Actual call: mock(1, 2, debug=True)
Code #8 : Working on the example
m.upper.return_value = 'HELLO' print (m.upper( 'hello' )) assert m.upper.called m.split.return_value = [ 'hello' , 'world' ] print (m.split( 'hello world' )) m.split.assert_called_with( 'hello world' ) print (m[ 'blah' ]) print (m.__getitem__.called) |
Output :
'HELLO' ['hello', 'world'] <MagicMock name='mock.__getitem__()' id='4314412048'> True
Typically, these kinds of operations are carried out in a unit test. It is explained with an example taking a function in the code given below –
Code #9 :
from urllib.request import urlopen import csv def dowprices(): lines = (line.decode( 'utf-8' ) for line in u) rows = (row for row in csv.reader(lines) if len (row) = = 2 ) prices = { name: float (price) for name, price in rows } return prices |
Normally, this function uses urlopen()
to go fetch data off the Web and parse it. To unit test it, a more predictable dataset can be used.