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:
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()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.
Rather than hacking on top of Python's import machinery, you can simply add the mocked module into sys. path , and have Python prefer it over the original module. Now, when the test suite is run, the mocked-lib subdirectory is prepended into sys. path and import A uses B from mocked-lib .
To mock an imported function with Jest we use the jest. mock() function. jest. mock() is called with one required argument - the import path of the module we're mocking.
How do we mock in Python? Mocking in Python is done by using patch to hijack an API function or object creation call. When patch intercepts a call, it returns a MagicMock object by default. By setting properties on the MagicMock object, you can mock the API call to return any value you want or raise an Exception .
Spying on the function using jest. import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest. spyOn(moduleApi, 'functionToMock'). mockReturnValue({ someObjectProperty: 42 }); Usage wise it's basically the same as manually mocking it as described in the previous section.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With