python - 两个文件的 python 'open' 中的模拟

标签 python python-2.7

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

关于python - 两个文件的 python 'open' 中的模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29471565/

相关文章:

python - 如何有效地将 tsv 文件中的数组列读取到每个列的单个 npz 文件中?

python - % : 'int' and 'str' 不支持的操作数类型

python-2.7 - 获取 celery 组结果

python - BaseHTTPServer,仅在我的变量发布后接收

python - 将变量分配给列表中的元组

python - 使用python将邻接列表转换为稀疏邻接矩阵

python - 使用 np.where 查找二维数组中的匹配行

google-app-engine - 如何使用 webapp2 解析路径参数

python - 设置并要求默认 Python 脚本 OptionParser

Python:向步骤图添加文本