1

How can I mock out the base class to test the rest behaviour of derived class?

# themod/sql.py

class PostgresStore(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port

    def connect(self):
        self._conn = "%s:%s" % (self.host, self.port)
        return self._conn


# themod/repository.py
from .sql import PostgresStore


class Repository(PostgresStore):

    def freak_count(self):
        pass


# tests/test.py
from themod.repository import Repository
from mock import patch 

@patch('themod.repository.PostgresStore', autospec=True)
def patched(thepatch):
    # print(thepatch)
    x = Repository('a', 'b')

    #### how to mock the call to x.connect?
    print(x.connect())

patched()
Anuvrat Parashar
  • 2,960
  • 5
  • 28
  • 55
  • You can't, not without rebuilding the subclass. The subclass keeps a reference to the base class and you didn't patch *that reference*. – Martijn Pieters Aug 03 '15 at 19:09
  • Mock out the inherited methods directly on the subclass instead. – Martijn Pieters Aug 03 '15 at 19:10
  • @MartijnPieters if I intend to test the subclass too, it beats the purpose doesn't it? – Anuvrat Parashar Aug 03 '15 at 19:18
  • 1
    @AnuvratParashar So the first thing is that you should stub interaction points. So even if you could do that it would not be the ideal way to do things. http://stackoverflow.com/questions/1595166/why-is-it-so-bad-to-mock-classes – dusual Aug 04 '15 at 08:07

1 Answers1

3

You can't mock out a Class as such. You should mock out one of the functions inside it. Try:

with patch.object(PostgresStore, 'connect', return_value=None) as connect_mock:
  # do something here
  assert connect_mock.called
Saurabh Kumar
  • 5,576
  • 4
  • 21
  • 30