我想在我的代码中测试一个方法时发出数据库调用。我想要它做的就是回报我的价值观,但我似乎无法做到那么远。
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'
如何解决这个问题?
答案 0 :(得分:2)
您的错误似乎在这里:
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']
答案 1 :(得分:0)
我想出的另一个解决方案是这个,但它不像使用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()