Python SQLAlchemy 模拟

标签 python unit-testing sqlalchemy python-unittest python-unittest.mock

这是我进行链式数据库查询调用的方法。

import math
def get_all_keys():
    db_session = DBSession()
    keys = db_session.query(SomeClass).all()

我应该模拟 DBSession().query(SomeClass).all()。我尝试了一些但没有任何效果。这是我的试验。

@patch('app.modules.somemodule.DBSession')
def test_asd(self, DBSession):
    DBSession.execute.query.execute.all.return_value = [1, 2, 3]
    self.assertListEqual(DBSession.query('qwe').all(), [1, 2, 3])

在这次尝试中,如果我尝试打印 DBSession(),我会得到一个看起来不错的 MagicMock 对象。但是当我运行 pytest 时出现以下错误。

    self = <test_some_module.SomeModuleTests testMethod=test_asd>, DBSession = <MagicMock name='DBSession' id='140028663111976'>

    @patch('app.modules.somemodule.DBSession')
    def test_asd(self, DBSession):
        DBSession.execute.query.execute.all.return_value = [1, 2, 3]
        print(DBSession().query('qwe').all())
>       self.assertListEqual(DBSession.query('qwe').all(), [1, 2, 3])
E       AssertionError: First sequence is not a list: <MagicMock name='DBSession.query().all()' id='140028662649184'>

tests/test_some_module.py:21: AssertionError

好像我在 mock 时做错了什么。我的错误是什么?我检查了文档。

最佳答案

您只是在模拟错误的东西,并断言调用链应该返回包含给定项目的实际列表,而不是神奇的模拟对象。您应该使用 return_value,而不是简单地模拟对同名属性的访问的 execute。 ,正如您在最后一步中所做的那样。给定链

DBSession().query(...).all()

你应该是在 mock

DBSession.return_value.query.return_value.all.return_value = [1, 2, 3]

另一方面,在 test_asd() 中你正在做的断言

DBSession.query(...).all()

所以

DBSession.query.return_value.all.return_value = [1, 2, 3]

关于Python SQLAlchemy 模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50621689/

相关文章:

python - 获取一小时过去的微秒

unit-testing - 如何在ionic2中使用Karma测试this.nav.push和this.menu.enable

python - 使用sqlalchemy创建一个mysql数据库

java - 如何正确 stub 外部方法?模拟语句上的 NullPointer

Angular 6 ngrx 商店测试 : cannot read ids of undefined

python - NoForeignKey 关系错误,即使 SQLAlchemy 模型指定了外键

mysql - 使用 version_id 列更新实体(乐观离线锁)

python - 当 PyQt5 应用程序退出时,我得到 "Release of profile requested but WebEnginePage still not deleted. Expect troubles !"

python - 如何使用 Python 将光标移动到 MySQL 中的最后一条记录?

python - IBM Watson nl-c 训练时间