Python模拟单元测试和数据库

2 投票
2 回答
12233 浏览
提问于 2025-04-18 02:01

我想在测试我代码中的一个方法时,模拟一个数据库调用。我只希望它能返回一些值,但我似乎无法做到这一点。

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

所以就像这个方法根本没有接收到参数一样,尽管在命令行中运行没有问题。

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

我该如何解决这个问题呢?

2 个回答

1

我想到的另一个解决方案是这个,不过它没有使用 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()
2

你的错误可能出现在这里:

 query.from_statment.return_value = ['test1', 'test2']

应该是:

 query.from_statement.return_value.all.return_value = ['test1', 'test2']

在命令行中对你来说是可以工作的,因为你没有使用相同的代码

>>> appModel.session.query('').from_statement('stmt')
['test1', 'test2']

如果你真的尝试的话,会失败的

>>> appModel.session.query('').from_statment('stmt').all()
['test1', 'test2']

撰写回答