简体   繁体   中英

Mock in python 'open' of two files

I want to test appendRole which is called getFileAsJson to read file with open. My problem is that I don't know which open will be next. There are many 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))

Even you can find an answer to your question at Python mock builtin 'open' in a class using two different files I would like encourage you to change your approach to write tests for getFileAsJson() and then trust it.

To test appendRole() use mock.patch to patch getFileAsJson() , then by side_effect attribute you can instruct the mock to return exactly what you need for your test.

So, after some test on getFileAsJson() where you can use mock_open() to mock open builtin (maybe you need to patch createFile() too). Your appendRole() 's test looks like something like this:

@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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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