[英]Python Mock UnitTest and Database
當我測試我的代碼中的方法時,我想存根數據庫調用。 我想要它做的就是返回我的價值,但我似乎無法走那么遠。
def loadSummary(appModel):
stmt = 'Select * from Table'
for row in appModel.session.query(*t.columnNames()).from_statement(stmt).all():
t.append(row)
return t
def test_loadSummary(self):
appModel = Mock()
query = appModel.session.query.return_value
query.from_statment.return_value = ['test1', 'test2']
expected = loadSummary(appModel)
我收到以下錯誤
for row in appModel.session.query(*t.columnNames()).from_statement(stmt).all():
TypeError: 'Mock' object is not iterable
所以它就像它根本沒有被傳遞到方法中,即使它在 shell 中工作也沒有問題。
>>> appModel.session.query('').from_statment('stmt')
['test1', 'test2']
然后我嘗試使用 mock.patch.object
class MockAppContoller(object):
def from_from_statement(self, stmt):
return ['test1', 'test2']
def test_loadSummary(self):
with mock.patch.object(loadSummary, 'appModel') as mock_appModel:
mock_appModel.return_value = MockAppContoller()
我收到以下錯誤
2014-04-09 13:20:53,276 root ERROR Code failed with error:
<function loadSummary at 0x0D814AF0> does not have the attribute 'appModel'
我怎樣才能解決這個問題?
您的錯誤似乎在這里:
query.from_statment.return_value = ['test1', 'test2']
應該:
query.from_statement.return_value.all.return_value = ['test1', 'test2']
它在 shell 中為您工作,因為您沒有使用相同的代碼
>>> appModel.session.query('').from_statement('stmt')
['test1', 'test2']
如果你真的嘗試過會失敗
>>> appModel.session.query('').from_statment('stmt').all()
['test1', 'test2']
我想出的另一個解決方案是這個,但它不像使用 Mock 那樣整潔
class mockAppModel(object):
def from_from_statement(self, stmt):
t = []
t.appendRow('row1', 'row2')
return t
class mockFromStmt(object): #This is the ONE parameter constructor
def __init__(self):
self._all = mockAppModel()
def all(self): #This is the needed all method
return self._all.from_from_statement('')
class mockQuery(object): #This is the ONE parameter constructor
def __init__(self):
self._from_statement = mockFromStmt()
def from_statement(self, placeHolder): #This is used to mimic the query.from_statement() call
return self._from_statement
class mockSession(object):
def __init__(self):
self._query = mockQuery()
def query(self, *args): #This is used to mimic the session.query call
return self._query
class mockAppModel(object):
def __init__(self):
self.session = mockSession()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.