gpt4 book ai didi

python - 模拟基类的方法

转载 作者:行者123 更新时间:2023-11-28 21:10:26 27 4
gpt4 key购买 nike

如何模拟基类来测试派生类的其余行为?

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

最佳答案

你不能像这样模拟一个Class。您应该模拟其中的一个功能。尝试:

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

关于python - 模拟基类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31794925/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com