繁体   English   中英

模拟ConfigObj实例

[英]Mocking ConfigObj instances

使用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而失败,因为'Mock'类型的参数不可迭代。

如何将config对象定义为模拟?

这就是为什么你应该永远, 永远 ,后在你面前是很清醒:

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.")

我将把这个答案/问题留给后人,以防万一其他人有脑衰...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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