0

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.

silentnights
  • 813
  • 3
  • 11
  • 21

2 Answers2

1
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)
             ...
Dan
  • 1,874
  • 1
  • 16
  • 21
  • I gave +1 for your answer, because it hinted about the usage of mock.patch.object, which I did not previously know, but the problem with that solution is that if you need to mock something that is used in __init__() it will not work. I have added the solution down below – silentnights May 05 '18 at 12:20
1

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
silentnights
  • 813
  • 3
  • 11
  • 21