gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 06:26:04 26 4
gpt4 key购买 nike

我一直在努力想弄清楚如何模拟 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com