How to mock a function inside a function python test?

  mocking, python, unit-testing

I have these files:

utils.py

def generateCode():
    while(True):
        # https://tools.ietf.org/html/rfc4122.html
        uuid_code = str(uuid.uuid4().int)[:6]
        return uuid_code

generate.py

from utils import generateCode

def create_auth_challenge():
   code = generateCode()
   return code

test.py

from unittest.mock import patch
from generate import create_auth_challenge

@patch('utils.generateCode', return_value='123456')
def test_create_auth_challenge(self, mock_generateCode):
   answer = create_auth_challenge()
   self.assertEqual(answer,'123456')

but the problem is the result of the test is failed because of

answer!=’123456′

so, I think it is because the mocking process is wrong because the answer value is always a random number. What makes it wrong? Does it because of the uuid4? How to do the right mocking?

Source: Python Questions

LEAVE A COMMENT