2015-04-06 81 views
1

我想測試appendRole,它被稱爲getFileAsJson來讀取打開的文件。 我的問題是我不知道接下來會打開哪一個。有很多if/elif。模擬python「打開」兩個文件

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

即使你可以找到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()