如何模拟基类来测试派生类的其余行为?
# 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()
答案 0 :(得分:2)
你不能嘲笑Class
。你应该嘲笑其中的一个功能。尝试:
with patch.object(PostgresStore, 'connect', return_value=None) as connect_mock:
# do something here
assert connect_mock.called