基类的模拟方法

2024-05-23 13:58:47 发布

您现在位置:Python中文网/ 问答频道 /正文

如何模拟基类来测试派生类的rest行为?在

# 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()

Tags: frompyimportselfhostsqlportrepository
1条回答
网友
1楼 · 发布于 2024-05-23 13:58:47

你不能这样模仿Class。你应该模仿其中的一个函数。尝试:

with patch.object(PostgresStore, 'connect', return_value=None) as connect_mock:
  # do something here
  assert connect_mock.called

相关问题 更多 >