2016-09-20 70 views
1

使用ConfigObj,我想測試一些section創建代碼:嘲諷ConfigObj實例

def create_section(config, section): 
    config.reload() 
    if section not in config: 
     config[session] = {} 
     logging.info("Created new section %s.", section) 
    else: 
     logging.debug("Section %s already exists.", section) 

我想多寫幾個單元測試,但我打一個問題。例如,

def test_create_section_created(): 
    config = Mock(spec=ConfigObj) # ← This is not right… 
    create_section(config, 'ook') 
    assert 'ook' in config 
    config.reload.assert_called_once_with() 

顯然,試驗方法將失敗,因爲一個TypeError類型的自變量的「模擬」不是可迭代。

如何將config對象定義爲模擬對象?

回答

0

這就是爲什麼你永遠不應該,永遠,後期你是醒着前:

def test_create_section_created(): 
    logger.info = Mock() 
    config = MagicMock(spec=ConfigObj) # ← This IS right… 
    config.__contains__.return_value = False # Negates the next assert. 
    create_section(config, 'ook') 
    # assert 'ook' in config ← This is now a pointless assert! 
    config.reload.assert_called_once_with() 
    logger.info.assert_called_once_with("Created new section ook.") 

我要離開這裏了這個問題的答案/問題留給後人的情況下,其他人有大腦失敗...