我刚开始在python中进行测试和测试。我有一个python类,如下所示:
文件名:my_hive.py
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.connect、pyhive.Connection.cursor(我的类用作hive.connect(hive_ip).cursor())和pyhive.Cursor.execute (类在执行方法中用作self.cursor.execute(command) )。
我能够模拟函数调用hive.connect,也能够断言它是用我给出的hive_ip调用的,如下所示。
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的方法。
我尝试过添加类似这样的模拟:
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.发布于 2021-04-27 06:02:15
您的问题是您已经模拟了connect,因此对connect结果的后续调用将在模拟上进行,而不是在真正的对象上进行。要检查该调用,必须对返回的模拟对象进行检查:
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包含另一个将被实际调用的模拟。
https://stackoverflow.com/questions/67277495
复制相似问题