How to patch dynamic imports in python unittests?

Viewed 226

I have the below file structure in my project. The magic basically contains wrappers around the third-party libraries.

.
├── magic
│   └── __init__.py
│   └── mock.py
│   └── real.py

So based on environment variables, we import methods from either mock.py entirely or real.py. Now I want to write unit tests for some methods which use these magic methods from magic. The contents of __init__.py are listed below.

if SOME_ENV:
    from .mock import (
        magic_method
    )
else:
    from .real import (
        magic_method
    )

__all__ = [
    "magic_method"
]

In unit tests, when I want to patch them and see whether magic_method was called, I am always getting it like magic_method was never called, but it is called every time if I run the script. Below is the sample test_case()

def test_magic(db):
    with patch("magic.mock.magic_method") as magic_method:
        # something
    assert magic_method.called

The above test is failing every time. Any suggestions?

0 Answers
Related