class CanonDatabase:
def __init__(self, clean_up_db=False):
self.db = "tmg_canon_april_tokens"
self.conn = create_connection(self.db)
self.cur = self.conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
我正在尝试mock.patch MySQLdb以传递构造函数。如何mock.patch MySQLdb.cursors?
@mock.patch.object(MySQLdb, '__init__')
class TestDatabase(unittest.TestCase):
def setUp(self):
super(TestDatabase, self).setUp()
patch = mock.patch('atone_canon.Database.create_connection')
mock_baz = patch.start()
mock_baz.cursor.return_value = mock.MagicMock()
def tearDown(self):
super(TestDatabase, self).tearDown()
mock.patch.stopall()
def test_clean_table(self, mysql_mock):
db = CanonDatabase()
self.assertEqual(True, False)
但是这个失败,出现以下错误信息:
File "atone_canon/Database.py", line 20, in __init__ self.cur = self.conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
AttributeError: 'module' object has no attribute 'cursors'
我找到了一种方法:(!)
如果我在单元测试中插入此进口,甚至不需要使用它:
from MySQLdb.cursors import DictCursor
然后我不再出现错误,我赢了甚至不得不mock.patch MySQLdb包装:
# @mock.patch.object(MySQLdb, '__init__')
class TestDatabase(unittest.TestCase):
...
不太满意的解决方案。一般来说,我嘲笑生活在我的项目之外的课程(例如住在virtualenv)。我保持开放,所以希望有人能告诉我如何嘲笑这些类。
您是否尝试模拟MySQLdb.cursors.DictCursor与您在自定义类的setUp中使用的方式类似?因为它看起来像你模拟MySQLdb .__ init__,然后期望找到正确不存在的MySQLdb.cursors – user3012759 2015-02-05 15:10:48
不知道该怎么做。 'patch_dict_cursor = mock.patch.object(DictCursor,'__init __')'这是否行得通? – Houman 2015-02-05 15:49:23
认为你需要更类似于此的东西:patch_dict_cursor = mock.patch(MySQLdb.cursors.DictCursor,spec = True) – user3012759 2015-02-05 15:56:48