久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

使用兩個不同文件的類中的 Python 模擬內(nèi)置“打開

Python mock builtin #39;open#39; in a class using two different files(使用兩個不同文件的類中的 Python 模擬內(nèi)置“打開)
本文介紹了使用兩個不同文件的類中的 Python 模擬內(nèi)置“打開"的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!

問題描述

當(dāng)它們都使用上下文管理器時,我無法弄清楚如何模擬一個類中打開的兩個文件.我知道如何使用這樣的模擬模塊為一個上下文管理的文件執(zhí)行此操作:

I am having trouble figuring out how to mock two file opens in a class when they both use context managers. I know how to do it for one context-managed file using the mock module like this:

@patch('__builtin__.open')
def test_interface_mapping(self, mock_config):
        m = MagicMock(spec=file)
        handle = m.return_value.__enter__.return_value
        handle.__iter__.return_value = ('aa', 'bb')

我的問題是當(dāng)一個類在同一個調(diào)用中打開兩個不同的文件時如何做到這一點(diǎn).在我的例子中,類 __init__() 將文件預(yù)加載到兩個映射中.該類用于其他類.我想模擬這兩個文件的加載以提供我的測試數(shù)據(jù),以便可以針對我預(yù)加載的測試文件內(nèi)容測試使用 IfAddrConfig 對象的其他類.

My problem is how to do this when a class opens two different files in the same call. In my case, the class __init__() preloads the files into two maps. This class is used in other classes. I want to mock the loading of these two files to provide my test data so that the other classes that use the IfAddrConfig object can be tested against my preloaded test file content.

這是一個我正在努力使用的類的示例,它在 __init__() 中加載兩個文件,我想模擬這兩個文件以加載我的測試注入文件內(nèi)容.getInterfaceMap() 是經(jīng)常調(diào)用的函數(shù),所以我不希望每次調(diào)用都加載和解析文件,因此在 __init__() 中預(yù)加載地圖一次.

Here's an example of the class I am struggling with that loads two files in __init__(), both of which I want to mock to load my test injected file contents. getInterfaceMap() is the function that is called frequently so I do not want that to be loading and parsing the files every call, hence the reason for preloading the maps in __init__() once.

class IfAddrConfig(object):
    def __init__(self):
        # Initialize the static maps once since they require file operations
        # that we do not want to be calling every time getInterfaceMap() is used
        self.settings_map = self.loadSettings()
        self.config_map = self.loadConfig()

    def loadConfig(self):
        config_map = defaultdict(dict)
        with open(os.path.join('some_path.cfg'), 'r') as stream:
            for line in stream:
                # Parse line and build up config_map entries
        return config_map

    def loadSettings(self):
        settings_map = {}
        with open('another_path.cfg', 'r') as stream:
            for line in stream:
                # Parse line and build up settings_map entries
        return settings_map

    def getInterfaceMap(self, interface):
        # Uses both the settings and config maps to finally create a composite map
        # that is returned to called
        interface_map = {}
        for values in self.config_map.values():
            # Accesss self.settings_map and combine/compare entries with
            # self.config_map values to build new composite mappings that
            # depend on supplied interface value
        return interface_map

推薦答案

你必須使用你的補(bǔ)丁 open 對象的 side_effect 屬性 (mock_open) 并且不要忘記為 __exit__ 方法設(shè)置 return_value.

You must use side_effect attribute of your patched open object (mock_open) and don't forget to set the return_value for __exit__ method.

@patch('__builtin__.open', spec=open)
def test_interface_mapping(self, mock_open):
    handle1 = MagicMock()
    handle1.__enter__.return_value.__iter__.return_value = ('aa', 'bb')
    handle1.__exit__.return_value=False
    handle2 = MagicMock()
    handle2.__enter__.return_value.__iter__.return_value = ('AA', 'BB')
    handle2.__exit__.return_value=False
    mock_open.side_effect = (handle1, handle2)
    with open("ppp") as f:
        self.assertListEqual(["aa","bb"],[x for x in f])
    with open("ppp") as f:
        self.assertListEqual(["AA","BB"],[x for x in f])

<小時>

我找到了一種更優(yōu)雅的方法來做到這一點(diǎn) Mock builtin開放"在 contextlib 中使用時的函數(shù)


I found a much more elegant way to do it Mock builtin 'open" function when used in contextlib

所以你可以像這樣重寫測試

So you can rewrote test like

@patch('__builtin__.open', new_callable=mock_open, read_data="aa
bb")
def test_interface_mapping_new(self, mo):
    handlers = (mo.return_value,mock_open(read_data="AA
BB").return_value,)
    mo.side_effect = handlers
    with open("ppp") as f:
        self.assertEqual("aa
bb",f.read())
    with open("ppp") as f:
        self.assertEqual("AA
BB",f.read())

從 python 3.4 開始,您還可以使用 readline()、readlines() 而無需模擬其他任何內(nèi)容.

And from python 3.4 you can use also readline(), readlines() without mocking anything else.

這篇關(guān)于使用兩個不同文件的類中的 Python 模擬內(nèi)置“打開"的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

How should I verify a log message when testing Python code under nose?(在鼻子下測試 Python 代碼時,我應(yīng)該如何驗(yàn)證日志消息?)
Patch __call__ of a function(修補(bǔ)函數(shù)的 __call__)
How to call self in a mock method of an object in Python?(如何在 Python 中對象的模擬方法中調(diào)用 self?)
Mocking only a single method on an object(僅模擬對象上的單個方法)
Mocking a subprocess call in Python(在 Python 中模擬子進(jìn)程調(diào)用)
Checking call order across multiple mocks(檢查多個模擬的調(diào)用順序)
主站蜘蛛池模板: 一区二区激情 | 亚洲一区二区久久 | 久久精品国产免费高清 | 成年人免费看 | 国产精品一区二区三区在线 | 亚洲视频中文字幕 | 99久久精品国产毛片 | 性一交一乱一透一a级 | 欧美一区二区三区视频在线播放 | 欧美性猛片aaaaaaa做受 | 国产精品美女一区二区 | 日韩国产在线 | 精品一区二区三区四区五区 | 精品欧美一区二区在线观看欧美熟 | 国产精品毛片无码 | 国产高清视频在线播放 | 久久国产精品精品国产色婷婷 | 色网站在线免费观看 | 日韩一区二区免费视频 | 国产高清自拍视频在线观看 | 亚洲美女网站 | 国产精品18久久久久久久 | 亚洲天天| 91成人午夜性a一级毛片 | 欧美精品在线看 | 日本不卡高字幕在线2019 | 国产一级一级 | 亚洲欧美一区二区三区国产精品 | 成人妇女免费播放久久久 | 国产在线一区二区三区 | 婷婷久久五月天 | 精品亚洲一区二区三区四区五区高 | 一区二区三区免费 | 日韩视频91| av男人的天堂av | 久久在看 | 99久久精品免费看国产四区 | 成年人在线观看 | 中文字幕一区二区三区在线乱码 | 中文字幕在线观看精品 | 麻豆久久精品 |