Open In App

Python | Unit Test Objects Patching | Set-2

Last Updated : 12 Jun, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report
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 - Code #6: Python3 1==
  

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() Python3 1==
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. Python3 1==
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 Python3 1==
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 : Python3 1==
from urllib.request import urlopen
import csv

def dowprices():
    u = urlopen('http://finance.yahoo.com/d/quotes.csv?s =@^DJI&f = sl1')
    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.

Next Article
Article Tags :
Practice Tags :

Similar Reads