In my test code I have a lot of boilerplate expressions "Magic", "return_". I also have lengthy strings to identify the paths of the functions to mock. The strings are not automatically replaced during refactoring and I would prefer to directly use the imported functions.
Example code:
from mock import patch, MagicMock
from pytest import raises
@patch(
'foo.baa.qux.long_module_name.calculation.energy_intensity.intensity_table',
MagicMock(return_value='mocked_result_table'),
)
Instead I would prefer:
from better_test_module import patch, Mock, raises
from foo.baa.qux.long_module_name.calculation import energy_intensity
@patch(
energy_intensity.intensity_table,
Mock('mocked_result_table'),
)
or
@patch(
energy_intensity.intensity_table,
'mocked_result_table',
)
I post my corresponding custom implementation as an answer below.
If you have other suggestions, please let me know. I am wondering why the proposed solution is not the default. I do not want to reinvent the wheel. Therefore, if there is an already existing library I could use, please let me know.
Related:
Create a wrapper module allowing for shorter names and passing functions directly. (If something like this already exists as a pip package, please let me know; don't want to reinvent the wheel.)
Usage:
First draft for my wrapping code in
my_test_utils/mock.py: