簡體   English   中英

Python 單元測試:模擬外部庫 function 從 class ZA8CFDE6331BD1C49EB2AC96F8691 調用

[英]Python unittest: Mock an external library function called from a class object

您好,我有以下代碼;

我正在嘗試在 file_a 中測試負載 function; 在我導入的外部模塊中下載的是 function

file_a.py

from foo import download

class Bar()
    __init__(self, arg_1):
        self.var = arg_1

    def load(self):
        if self.var == "latest_lib":
            download("latest_lib")

我寫了這樣的測試

test.py

@patch(file_a.download)
def test_download():
    import file_a
    bar = file_a.Bar("latest_lib")
    bar.load()
    file_a.download.assert_called() 

但似乎酒吧 object 沒有調用模擬下載,而是調用了導入的下載。 我怎樣才能解決這個問題並使我的測試通過?

我試着用你自己的代碼來看看哪里出了問題。 有一些語法錯誤並不重要,但主要問題是您應該將字符串傳遞給patch以使其工作。

這是我對您的代碼的修改,這一切都發生了:

# file_a.py

from pprint import pprint as pp

class Bar():
    def __init__(self, arg_1):
        self.var = arg_1

    def load(self):
        if self.var == "latest_lib":
            pp("latest_lib")

和:

# test_file_a.py

import unittest
from unittest.mock import patch


class TestStringMethods(unittest.TestCase):
    @patch("file_a.pp")
    def test_download(self, pp):
        import file_a
        bar = file_a.Bar("latest_lib")
        bar.load()
        pp.assert_called()


if __name__ == "__main__":
    unittest.main()

筆記:

  1. 您需要將字符串傳遞給patch以使其在運行時模擬 object。
  2. 您必須在測試 function 中收到模擬的 object。
  3. 我在這里使用了基於類的測試,因為我想使用unittest標准庫,但是如果您使用的是pytest ,則不必這樣做。

還有來自官方文檔的最后一條說明:

基本原則是在查找 object 的地方打補丁,這不一定與定義的地方相同。

我認為您缺少模擬設置:

@patch("foo.download")
def test_download(mock_download):
    from file_a import Bar

    Bar("latest_lib").load()
    mock_download.assert_called()

暫無
暫無

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

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