繁体   English   中英

模拟两个文件的python'open'

[英]Mock in python 'open' of two files

我想测试称为getFileAsJson的appendRole以读取打开的文件。 我的问题是我不知道下一个开放。 有很多if / elif。

def appendRole(self, hosts=None, _newrole=None, newSubroles=None, undoRole=False, config_path=None):
    """ Same as changeRole but keeps subroles """

    if hosts is None:
        hosts = ["127.0.0.1"]
    if newSubroles is None:
        newSubroles = {}
    if config_path is None:
        config_path = self.config_path


    with self._lock:
        default = {}
        data = self.getFileAsJson(config_path, default)
        ...................
        ...................
        ...................
        ...................   

        data1 = self.getFileAsJson(self.config_path_all, {"some"})
        data2 = self.getFileAsJson(self.config_path_core, {"something"})
        ...................   
        ...................   
        ...................   

def getFileAsJson(self, config_path, init_value):
    """ 
        read file and return json data
        if it wasn't create. Will created.
    """
    self.createFile(config_path, init_value)
    try:
        with open(config_path, "r") as json_data:
            data = json.load(json_data)
        return data
    except Exception as e:
        self.logAndRaiseValueError(
            "Can't read data from %s because %s" % (config_path, e))

甚至您也可以在使用两个不同文件的类中的Python模拟内置“ open”中找到问题的答案,我想鼓励您更改为getFileAsJson()编写测试的方法,然后再信任它。

要测试appendRole()使用mock.patch修补getFileAsJson() ,然后通过side_effect属性,您可以指示该模拟完全返回测试所需的内容。

因此,在对getFileAsJson()进行一些测试之后,您可以在其中使用mock_open()来模拟内置的open (也许也需要修补createFile() )。 您的appendRole()的测试如下所示:

@mock.patch('mymodule.getFileAsJson', autospec=True)
def test_appendRole(self, mock_getFileAsJson)
    mock_getFileAsJson.side_effect = [m_data, m_data1,m_data2,...]
    # where m_data, m_data1,m_data2, ... is what is supposed 
    # getFileAsJson return in your test
    # Invoke appendRole() to test it 
    appendRole(bla, bla)
    # Now you can use mock_getFileAsJson.assert* family methods to
    # check how your appendRole call it.
    # Moreover add what you need to test in appendRole()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM