Tuesday, 3 May 2022

django mock test used to change behaviour of function for unit test

 https://docs.python.org/3/library/unittest.mock.html



Patch can take a function as argument  like

    with patch('django.db.utils.ConnectionHandler.__getitem__') as getItem:

getItem.return_value = True changes django.db.utils.ConnectionHandler.__getitem__') return value to true


# Patch as a decorator will also change return  value of time.sleep function to True, and pass into the next function 

 @patch('time.sleep', return_value=True)

    def test_wait_for_db_conn(self, timesleep):

means   django.db.utils.ConnectionHandler.__getitem__')  return OperationError 5 times and True 1 times a total of 6 times

getItem.side_effect=[OperationalError]*5 + [True]

No comments:

Post a Comment