如何在python中模拟后续函数调用?

如何在python中模拟后续函数调用?,python,python-3.x,testing,python-unittest,python-mock,Python,Python 3.x,Testing,Python Unittest,Python Mock,我不熟悉python中的测试和测试。我有一个python类,如下所示: import unittest import mock from hive_schema_processor import HiveSchemaProcessor class TestHive(unittest.TestCase): @mock.patch('pyhive.hive.connect') @mock.patch('pyhive.hive.Connection.cursor') def

我不熟悉python中的测试和测试。我有一个python类,如下所示:

import unittest
import mock

from hive_schema_processor import HiveSchemaProcessor

class TestHive(unittest.TestCase):
    @mock.patch('pyhive.hive.connect')
    @mock.patch('pyhive.hive.Connection.cursor')
    def test_workflow(self, mock_connect, mock_cursor):
        hive_ip = "localhost"
        processor = Hive(hive_ip)

        mock_connect.assert_called_with(hive_ip)
        mock_cursor.assert_called()

文件名:
my\u hive.py

从pyhive导入配置单元
类蜂巢:
定义初始化(自身、蜂巢ip):
self.cursor=hive.connect(hive\u ip).cursor()
def执行(自我,命令):
self.cursor.execute(命令)
我想模拟这些函数:
pyhive.hive.connect
pyhive.Connection.cursor
(由我的类用作
hive.connect(hive\u ip.cursor()
)和
pyhive.cursor.execute
(由我的类用作执行方法中的
self.cursor.execute(command)

我能够模拟函数调用
hive.connect
,并且我能够断言它是用我给出的hive\u ip调用的,如下所示

导入单元测试
导入模拟
从我的蜂箱导入蜂箱
类TestHive(unittest.TestCase):
@mock.patch('pyhive.hive.connect')
def测试工作流程(自我、模拟连接):
配置单元ip=“本地主机”
处理器=配置单元(配置单元ip)
mock_connect.assert_调用_with(配置单元ip)
但是如何确保后续的函数调用,如
.cursor()
self.cursor.execute()
也被调用
hive.connect(hive\u ip)
返回
pyhive.hive.Connection
的实例,该实例的方法名为
cursor

我尝试添加如下模拟:

import unittest
import mock

from hive_schema_processor import HiveSchemaProcessor

class TestHive(unittest.TestCase):
    @mock.patch('pyhive.hive.connect')
    @mock.patch('pyhive.hive.Connection.cursor')
    def test_workflow(self, mock_connect, mock_cursor):
        hive_ip = "localhost"
        processor = Hive(hive_ip)

        mock_connect.assert_called_with(hive_ip)
        mock_cursor.assert_called()

但测试失败,原因是:

AssertionError: expected call not found.
Expected: cursor('localhost')
Actual: not called.

您的问题是您已经模拟了
connect
,因此对
connect
结果的后续调用将在模拟上进行,而不是在真实对象上。 要检查该调用,必须检查返回的模拟对象:

类TestHive(unittest.TestCase): @mock.patch('pyhive.hive.connect') def测试工作流程(自我、模拟连接): 配置单元ip=“本地主机” 处理器=配置单元(配置单元ip) mock_connect.assert_调用_with(配置单元ip) mock\u cursor=mock\u connect.return\u value.cursor mock_cursor.assert_调用() 对mock的每次调用都会生成另一个mock对象。
mock\u connect.return\u value
提供通过调用
mock\u connect
返回的mock,以及
mock\u connect.return\u value.cursor
包含另一个实际调用的mock。

非常感谢您的回答。这有帮助。