Saturday, October 25, 2025
HomeLanguagesPython | Unit Test Objects Patching | Set-2

Python | Unit Test Objects Patching | Set-2

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:




    
  
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():
    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.

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS