I have two classes in separate packages, one of them inherit from the other. I would like to test the child class.
So how can I mock the external objects used in the parent class? I am confused in which namespace they reside at this point.
I have two classes in separate packages, one of them inherit from the other. I would like to test the child class.
So how can I mock the external objects used in the parent class? I am confused in which namespace they reside at this point.
class A:
def foo(self):
# Make some network call or something
class B(A):
def bar(self):
self.foo()
...
class BTestCase(TestCase):
def setUp(self):
self.unit = B()
def test_bar(self):
with mock.patch.object(self.unit, 'foo') as mock_foo:
mock_foo.return_value = ...
result = self.unit.bar()
self.assertTrue(mock_foo.called)
...
To mock anything imported and used in the parent module, you need to mock it in the parent module.
a/a.py
import subprocess
class A(object):
def __init__(self):
print(subprocess.call(['uname']))
b/b.py
from a.a import A
class B(A):
def __init__(self):
super(B, self).__init__()
In your unittest
from b.b import B
from unittest.mock import patch
with patch('a.a.subprocess.call', return_value='ABC'):
B()
ABC