模拟蟒蛇'开放'两个文件

时间:2015-04-06 12:43:15

标签: python python-2.7

我想测试一个叫做getFileAsJson的appendRole,用open来读取文件。 我的问题是,我不知道接下来会打开哪个。有很多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))

1 个答案:

答案 0 :(得分:1)

即使您可以在Python mock builtin 'open' in a class using two different files找到问题的答案,我也鼓励您改变为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()