Reputation: 153
I have following code:
pkg1/mock_class.py:
class A:
def ma(self):
print(' class_A')
class B:
def __init__(self):
self.var = 'vvv'
def mb(self):
a = A()
print('class_B')
a.ma()
and test code:
from unittest import mock
import pytest
from pkg1.mock_class import B
@pytest.fixture(scope='class')
def mockA():
with mock.patch('pkg1.mock_class.A'):
yield
class TestB:
def test_b(self, mockA):
b = B()
b.mb()
I want to mock whole class A () using fixture and i would like to be able to configure some return values probably using parametrization in future.
Basic - just mocking/patching as implemented above is not working class B is mocked and i don't understand why.
Thanks for advice.
Jano
Upvotes: 5
Views: 8024
Reputation: 153
The code above is working correctly, i thought it is not working because in real scenario it wasnt - i was patching incorrect place.
from official documentation (link):
patch() works by (temporarily) changing the object that a name points to with another one. There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.
The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined. A couple of examples will help to clarify this.
Upvotes: 2