Search code examples
pythonmockingpython-unittestpython-mock

How to patch two function calls when they are called together in python


I have a function which uses below code.

def get_doc_hash(doc):
       return hashlib.md5(doc.encode(‘utf-8’)).hexdigest()

How can I mock both the calls of md5() and hexdigest() to write test cases for this function ?


Solution

  • As pointed out in comments, it would be better to test for expected behaviour, but purely for purpose of showing how to chain mocks, here is how it can be done:

    import hashlib
    import unittest
    from unittest.mock import patch
    
    
    def get_doc_hash(doc):
        return hashlib.md5(doc.encode("utf-8")).hexdigest()
    
    
    class TestHash(unittest.TestCase):
        @patch('hashlib.md5')
        def test_get_doc_hash_to_demonstrate_mock_chaining(self, mock_hashlib):
            mock_hashlib.return_value.hexdigest.return_value = "digested"
            hash_out = get_doc_hash("test doc")
            mock_hashlib.assert_called_once_with("test doc".encode("utf-8"))
            mock_hashlib.return_value.hexdigest.assert_called_once()
            self.assertEqual(hash_out, "digested")