繁体   English   中英

在Python中模拟sqlite3 fetchone()

[英]Mocking sqlite3 fetchone() in python

我在这里进行了一些先前的问题,有关在进行单元测试时在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()的收益?

谢谢!

进一步修改后,我发现以下方法可行:

@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)

其他所有代码均与原始帖子相同。 希望这对其他人有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM