在python中模拟“打开”两个文件

2024-09-30 10:41:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想测试名为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))

Tags: pathselfnoneconfigjsondataifis
1条回答
网友
1楼 · 发布于 2024-09-30 10:41:36

即使您可以在Python mock builtin 'open' in a class using two different files找到问题的答案,我也希望您改变您的方法,为getFileAsJson()编写测试,然后信任它。在

要测试appendRole(),请使用^{}来修补getFileAsJson(),然后通过side_effect属性,可以指示模拟返回测试所需的内容。在

因此,在对getFileAsJson()进行一些测试之后,您可以使用^{}来模拟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()

相关问题 更多 >

    热门问题