Kintarō
Kintarō

Reputation: 3187

How to unset mock.MagicMock in module level?

Suppose someone set the module as MagicMock in the head of the python file:

sys.modules['moduleABC'] = mock.MagicMock()

This cause trouble as moduleABC will be a mock when I try to run a whole list of unit test.

How can I unset this to an actual moduleABC in the rest of the files?

Upvotes: 1

Views: 601

Answers (1)

Uri Shalit
Uri Shalit

Reputation: 2318

I think a better approach would be to change that unit test to use patch in a setUp function and then it will apply for all tests in that module, but will be reverted in the end, this is also better as each test will have it's own and not one single mock for all of them (If for instance, you test the number of time a method is called in the module you will have to accumulate all calls in the test...)

Another option is to use the tearDown function and change a bit the way you assign the mock to:

import moduleABC

orig_abc = sys.modules['moduleABC']
sys.modules['moduleABC'] = mock.MagicMock()

def tearDown():
    sys.modules['moduleABC'] = orig_abc

But I strongly recommend the first option, as it is the better approach.

Upvotes: 1

Related Questions