2016-09-20 88 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.") 

我要离开这里了这个问题的答案/问题留给后人的情况下,其他人有大脑失败...