Search code examples
pythonunit-testingmockingpython-mock

Mocking a module imported inside of a function


Is it possible to mock a module that's imported inside of a function?

for instance

def my_func(input):
    import something_else
    something_else.do_something(input)

I have an import inside of the function because of a circular dependency. Based on my googling I think I am SOL, but was wondering if anyone knew of way to make this possible.

I just want to verify that do_something gets called.


Solution

  • You can use the same technique that's described in this answer. In short you can patch sys.modules dict. So your test can be:

    from unittest.mock import patch, MagicMock
    
    ...
    
    def test_call_do_something(self):
        m = MagicMock()
        with patch.dict("sys.modules", something_else=m):
            input_mock = MagicMock()
            my_func(input_mock)
            m.do_something.assert_called_with(input_mock)
    

    You can rewrite it by patch decorator, but m should be a static instance.