首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中模拟后续函数调用?

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

Stack Overflow用户
提问于 2021-04-27 05:38:02
回答 1查看 779关注 0票数 0

我刚开始在python中进行测试和测试。我有一个python类,如下所示:

文件名:my_hive.py

代码语言:javascript
复制
from pyhive import hive

class Hive:
    def __init__(self, hive_ip):
        self.cursor = hive.connect(hive_ip).cursor()

    def execute(self, command):
        self.cursor.execute(command)

我想模拟这些函数:pyhive.hive.connectpyhive.Connection.cursor(我的类用作hive.connect(hive_ip).cursor())和pyhive.Cursor.execute (类在执行方法中用作self.cursor.execute(command) )。

我能够模拟函数调用hive.connect,也能够断言它是用我给出的hive_ip调用的,如下所示。

代码语言:javascript
复制
import unittest
import mock

from my_hive import Hive

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

        mock_connect.assert_called_with(hive_ip)

但是,如何确保后续函数调用(如.cursor()self.cursor.execute() )也已被调用?hive.connect(hive_ip)返回pyhive.hive.Connection的一个实例,该实例具有名为cursor的方法。

我尝试过添加类似这样的模拟:

代码语言:javascript
复制
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()

但是测试失败了,抱怨道:

代码语言:javascript
复制
AssertionError: expected call not found.
Expected: cursor('localhost')
Actual: not called.
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-27 06:02:15

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

代码语言:javascript
复制
class TestHive(unittest.TestCase):
    @mock.patch('pyhive.hive.connect')
    def test_workflow(self, mock_connect):
        hive_ip = "localhost"
        processor = Hive(hive_ip)

        mock_connect.assert_called_with(hive_ip)
        mock_cursor = mock_connect.return_value.cursor
        mock_cursor.assert_called()

对模拟的每次调用都会产生另一个模拟对象。mock_connect.return_value为您提供了调用mock_connect返回的模拟,mock_connect.return_value.cursor包含另一个将被实际调用的模拟。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67277495

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档