6

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.

Michele d'Amico
  • 22,111
  • 8
  • 69
  • 76
aamiri
  • 2,420
  • 4
  • 38
  • 58

1 Answers1

5

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.

Community
  • 1
  • 1
Michele d'Amico
  • 22,111
  • 8
  • 69
  • 76