How do I mock a function which is imported with an alias?

Viewed 1210

Below I have added some dummy code which exactly represent what I am trying to do.

I am importing a function from a class with an alias, I am doing this since the class is running the aliased version itself.

Things I have tried:

  • http://bhfsteve.blogspot.com/2012/06/patching-tip-using-mocks-in-python-unit.html This does not give a specific solution to the problem.
  • patched a.dummy.class.function.alias as a.dummy.class.function this allows execution but will not run the alias_function_mocker() as in the class the function is called as alias() and not function()
  • I tried running as a.dummy.class.function.alias but this results in an attribute error as alias isn't actually an attribute of class(because function() is)
from a.dummy.class import function as alias

def alias_function_mocker():
    return 0

@patch("a.dummy.class.function.alias", side_effect=alias_function_mocker):
def test_function(mocked_function):
    function_calling_alias()
    return 0

What I think the problem roots from is that the class file is calling function using alias and there doesn't seem to be a way to patch aliased function calls. The simple and most naive solution I can think of is just do not use an alias.

2 Answers

You need to mock the object where it is. If you imported the module/function to file.py, you need to mock the object of this file.

If you are using the test in the same file of the method, this could be the solution:

from os.path import isdir as is_it_a_dir
from unittest.mock import patch

def check(path):
    return is_it_a_dir(path)

with patch('__main__.is_it_a_dir') as mock_isitadir:
    mock_isitadir.return_value = True
    assert check('/any/invalid/path') == True

If your test is in another file, than your approch should work.

Just to complement Mauro Baraldi's answer, this is how to do it using decorators.

@patch("__main__.alias")
Related