【问题标题】:Mocking sqlite3 fetchone() in python在 python 中模拟 sqlite3 fetchone()
【发布时间】:2018-08-10 09:20:00
【问题描述】:

在进行单元测试时,我已经在这里解决了一些关于在 python 中模拟 sqlite3 的问题,不幸的是,这些问题都没有帮助我成功地模拟 fetchone() 的结果。

以下是我整理的一个快速测试示例,以尝试使其正常工作:

TETS.PY

import unittest
import sqlite3
from unittest import TestCase, mock
from unittest.mock import patch, MagicMock

class Foo: 

    def checkActive(self):
        conn = sqlite3.connect('lll.db')
        cur = conn.execute("SELECT * FROM SQLITE_MASTER")
        value = cur.fetchone()
        return value


class test_Foo(TestCase):

    @patch('tets.sqlite3')
    def test_shortTest(self, mock_sql):
        mock_sql.connect().cursor().fetchall.return_value = ('Test',)

        test_class = Foo()
        return_mock = test_class.checkActive()
        print(return_mock)

if __name__ == '__main__':  # pragma: no cover -> local unittest main call
    unittest.main()

我已经尝试了上述的变体,以及修补 tets.sqlite3.connect 并从那里开始,但我总是以下任何一种结果:

[Running] python -u "c:\Users\z003uwfm\Desktop\tets.py"
<MagicMock name='connect().execute().fetchone()' id='45622576'>
.
----------------------------------------------------------------------
Ran 1 test in 0.016s

OK

[Running] python -u "c:\Users\z003uwfm\Desktop\tets.py"
None
.
----------------------------------------------------------------------
Ran 1 test in 0.021s

OK

有没有人能够模拟从 fetchone() 或 fetchall() 返回的真实工作示例?

谢谢!

【问题讨论】:

    标签: python unit-testing sqlite mocking


    【解决方案1】:

    经过进一步的修改,我发现以下方法可以正常工作:

    @patch('sqlite3.connect')
    def test_shortTest(self, mock_sql):
        mock_sql.return_value.execute.return_value.fetchone.return_value = ('Test',)
        test_class = Foo()
        return_mock = test_class.checkActive()
        print(return_mock)
    

    所有其他代码与原始帖子相同。希望这可以帮助其他人,如果他们不得不遇到这个!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-01
      相关资源
      最近更新 更多