簡體   English   中英

如何模擬 python 中的后續 function 調用?

[英]How to mock subsequent function calls in python?

我是 python 中測試和測試的新手。 我有一個 python class 看起來像這樣:

文件名: 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)

I want to mock these functions: pyhive.hive.connect , pyhive.Connection.cursor (used by my class as hive.connect(hive_ip).cursor() ) and pyhive.Cursor.execute (used by my class as self.cursor.execute(command)在執行方法中)。

我能夠模擬 function 調用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)

但是我如何確保隨后的 function 調用,如.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.

您的問題是您已經模擬了connect ,因此對connect結果的后續調用將在模擬上進行,而不是在真正的 object 上進行。 要檢查該調用,您必須改為檢查返回的模擬 object:

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()

對模擬的每次調用都會產生另一個模擬 object。 mock_connect.return_value為您提供通過調用mock_connect返回的模擬,並且mock_connect.return_value.cursor包含另一個將實際調用的模擬。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM