Skip to main content
 首页 » 编程设计

Python 模拟单元测试和数据库

2024年11月01日10grandyang

我想在测试代码中的方法时停止数据库调用。我只想让它返回值,但我似乎做不到那么远。

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']