我如何模拟sqlite3.Cursor [英] How can I mock sqlite3.Cursor

查看:95
本文介绍了我如何模拟sqlite3.Cursor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been pulling my hair out trying to figure out how to mock the sqlite3.Cursor class specifically the fetchall method.

请考虑以下代码示例

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不会导致有趣的错误

Running nosetests results in no fun error

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方法,还是我做错了什么?

Should I not be able to mock the fetchall method or am I doing something horribly wrong?

推荐答案

我会修补在模块中导入的sqlite3,然后从那里开始工作.

I would take the approach of patching out sqlite3 imported in your module and then work from there.

让我们假设您的模块名为what.py.

Let's assume your module is named what.py.

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

I would patch out what.sqlite3 and then mock the return value of .connect().cursor().fetchall.

这是一个更完整的示例:

Here is a more complete example:

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

这篇关于我如何模拟sqlite3.Cursor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆