I have 2 modules. The first one say A
:
Inside module A
I have:
from my_lib import SomeClass
def my_function:
my_var = SomeClass()
do something with my_var...
The package my_lib
is a package I created and i pip-installed it locally into my site-packages (by running pip install .
in the root directory of my package. I have __init__.py
__main__.py
and all the needed files for a correct package)
The other module is say test_A
. Inside test_A
I use mock pytest in the following way:
import A
import pytest
def test_my_function(mocker):
mocker.patch(target='my_lib.SomeClass', return_value='some_mock_value')
A.my_function()
The problem is that mocking with my_lib.SomeClass
doesn't apply the mock to the direct invocation of SomeClass
within module A
when the tests enter my_function
within that module (a real SomeClass instance is returned). The only way it does work is when in module A i use SomeClass invocation like this:
import my_lib
.....
.....
my_var = my_lib.SomeClass()
That means I have to change the real module just so that the mock test will be able to mock the invoked class, which sounds wrong.
Patching without the full path like this:
mocker.patch(target='SomeClass', return_value='some_mock_value')
will NOT work since mock-pytest will not be able to import SomeClass (since SomeClass
does not exist in site-packages, only my_lib.SomeClass
does).
Is there an elegant solution to this situation ?
How to tell mock-pytest that SomeClass
that is invoked in module A
and my_lib.SomeClass
from the mock path relate to the same library in site-packages ?
I've run out of ideas. Help ?