[英]How to create builtin function mock used by object in tested function
我想從我的Python應用程序測試一個功能。 代碼如下:
import unittest
from unittest.mock import patch
from mock import MagicMock
import configparser
def read_config_sections(filename):
cp = configparser.ConfigParser()
cp.read(filename)
sections = list()
for section in cp.sections():
sections.append(section)
return sections
class TestReadConfigSection(unittest.TestCase):
@patch("__main__.open", MagicMock(return_value="[SECTION1]"))
def test_read_config_sections(self):
sections = read_config_sections("somename.ini")
self.assertEqual(["SECTION1"], sections)
if "__main__" == __name__:
unittest.main()
我想模擬ConfigParser
方法使用的open
函數來讀取配置。 有人可以告訴我效果如何嗎? 當我運行上面的代碼時,變量sections
是一個空列表。
或者,也許您對如何測試此功能有個更好的主意。
import configparser
import io
from mock import patch, mock_open
import unittest
def read_config_sections(filename):
cp = configparser.ConfigParser()
cp.read(filename)
sections = list()
for section in cp.sections():
sections.append(section)
return sections
class TestReadConfigSection(unittest.TestCase):
@patch("builtins.open", return_value=io.StringIO("[SECTION1]"))
def test_read_config_sections(self, mock_open):
sections = read_config_sections("somename.ini")
self.assertEqual(sections, ["SECTION1"])
if "__main__" == __name__:
unittest.main()
在這里找到解決方案: https : //mapleoin.github.io/perma/mocking-python-file-open
感謝幫助。
最好的祝福。
我相信您想要__builtins__.open
而不是__main__.open
您也可以改用mock_open
函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.