两个问题:
我正在尝试模拟PasswordClient()。password_db,以便可以在TableQuery中使用它。我在嘲笑PasswordClient.__init__()
时遇到了麻烦。
import os
class PasswordClient:
def __init__(self):
self.password_db = os.environ['DOES_NOT_EXIST']
class DBClient:
def __init__(self):
password_client = PasswordClient()
class TableQuery():
def add_person(self):
self.db_client=DBClient()
@patch.object(PasswordClient, 'PasswordClient.__init__')
def fn():
return 'hello'
a = TableQuery()
a.add_person()
我尝试了以下方法:
@patch.object(PasswordClient, 'PasswordClient.__init__')
@patch.object(PasswordClient, 'PasswordClient.password_db')
@patch.object(PasswordClient, 'password_db')
所有操作都以KeyError结尾,因为DOES_NOT_EXIST很好...您知道。
答案 0 :(得分:0)
更好的设计是将必要的客户端作为参数传递,而不是让每个类负责了解如何实例化此类客户端。
import os
class PasswordClient:
def __init__(self, value):
self.password_db = value
class DBClient:
def __init__(self, pc):
self.password_client = pc
class TableQuery:
def __init__(self, dbc):
self.db_client = dbc
def add_person(self):
...
a = TableQuery(DBClient(PasswordClient(...)))
a.add_person()