【发布时间】:2017-07-21 06:50:53
【问题描述】:
我一直在努力弄清楚如何模拟 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 方法还是我做错了什么?
【问题讨论】:
-
@JanneKarila 我试过了,但现在我得到了一个 AssertionError gist.github.com/anonymous/7931550 :
-
我认为您的补丁级别错误。我个人会修补 sqlite3 本身并像这样模拟 fetch_all 方法:gist.github.com/alexcouper/eec0d38454ce4bc43c6b
-
Alex,你应该公开 GIST 作为答案,它对我有用,谢谢
-
@RogerVeciana 完成。 :)
标签: python unit-testing sqlite mocking nose