python - 我怎样才能模拟 sqlite3.Cursor

标签 python unit-testing sqlite mocking nose

我一直在努力想弄清楚如何模拟 sqlite3.Cursor 类,特别是 fetchall 方法。

考虑以下代码示例

import sqlite3

from mock import Mock, patch
from nose.tools import assert_false


class Foo:
    def check_name(name):
        conn = sqlite3.connect('temp.db')
        c = conn.cursor()
        c.execute('SELECT * FROM foo where name = ?', name)
        if len(c.fetchall()) > 0:
            return True
        return False


@patch('sqlite3.Cursor.fetchall', Mock(return_value=['John', 'Bob']))
def test_foo():
    foo = Foo()
    assert_false(foo.check_name('Cane'))

运行 nosetests 导致没有有趣的错误

E
======================================================================
ERROR: temp.test_foo
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/koddsson/.virtualenvs/temp/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/home/koddsson/.virtualenvs/temp/lib/python2.7/site-packages/mock.py", line 1214, in patched
    patching.__exit__(*exc_info)
  File "/home/koddsson/.virtualenvs/temp/lib/python2.7/site-packages/mock.py", line 1379, in __exit__
    setattr(self.target, self.attribute, self.temp_original)
TypeError: can't set attributes of built-in/extension type 'sqlite3.Cursor'

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (errors=1)

我不应该模拟 fetchall 方法还是我做错了什么?

最佳答案

我会采用修补模块中导入的 sqlite3 的方法,然后从那里开始工作。

假设您的模块名为 what.py

我会修补 what.sqlite3 然后模拟 .connect().cursor().fetchall 的返回值。

这是一个更完整的例子:

from mock import patch
from nose.tools import assert_true, assert_false

from what import Foo

def test_existing_name():
    with patch('what.sqlite3') as mocksql:
        mocksql.connect().cursor().fetchall.return_value = ['John', 'Bob']
        foo = Foo()
        assert_true(foo.check_name('John'))

关于python - 我怎样才能模拟 sqlite3.Cursor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20536594/

相关文章:

delphi - 如何使用 DUnit 测试 Singleton 类?

python - 自定义类排序 : no error thrown, 什么是 Python 测试?

python - PyMongo - 查询嵌入文档列表

python - 在 Python unittest 框架中修改全局变量

java - com.sun.istack.internal.SAXException2 : unable to marshal type as an element

SQLite、Golang 和联结表

sqlite - 在 xamarin 项目中使用 MobileServiceClient 和 MobileServiceSQLiteStore '数据库被锁定'

python - Flask SQLAlchemy 获取所有 json

python - 剔除一个选定值后选取最大值

ios - 使用 Realm 数据库进行 XCTest 单元测试中的 RLMException