[英]Python Mock UnitTest and Database
I want to stub out a database call when I test a method I have in my code.当我测试我的代码中的方法时,我想存根数据库调用。 All I want it to do is return me values but I cannot seem to get that far.
我想要它做的就是返回我的价值,但我似乎无法走那么远。
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)
I get the following error我收到以下错误
for row in appModel.session.query(*t.columnNames()).from_statement(stmt).all():
TypeError: 'Mock' object is not iterable
So its like its not getting passed into the method at all even though it works in the shell no problem.所以它就像它根本没有被传递到方法中,即使它在 shell 中工作也没有问题。
>>> appModel.session.query('').from_statment('stmt')
['test1', 'test2']
I then tried using mock.patch.object然后我尝试使用 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()
I get the following error我收到以下错误
2014-04-09 13:20:53,276 root ERROR Code failed with error:
<function loadSummary at 0x0D814AF0> does not have the attribute 'appModel'
How can I get around this problem?我怎样才能解决这个问题?
Your error appears to be here:您的错误似乎在这里:
query.from_statment.return_value = ['test1', 'test2']
Should be:应该:
query.from_statement.return_value.all.return_value = ['test1', 'test2']
It works in the shell for you because you aren't using the same code它在 shell 中为您工作,因为您没有使用相同的代码
>>> appModel.session.query('').from_statement('stmt')
['test1', 'test2']
Would fail if you actually tried如果你真的尝试过会失败
>>> appModel.session.query('').from_statment('stmt').all()
['test1', 'test2']
Another solution I came up with was this but its not as neat as using Mock我想出的另一个解决方案是这个,但它不像使用 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.