Patch over a function imported inside another function

You should mock out helpers.do_it_helper:

class Test_do_it(unittest.TestCase):
    def test_do_it(self):
        with patch('helpers.do_it_helper') as helper_mock:
            helper_mock.return_value = 12
            # test things

Here’s an example using mock on os.getcwd():

import unittest
from mock import patch


def get_cwd():
    from os import getcwd
    return getcwd()


class MyTestCase(unittest.TestCase):
    @patch('os.getcwd')
    def test_mocked(self, mock_function):
        mock_function.return_value="test"
        self.assertEqual(get_cwd(), 'test')

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)