简体   繁体   English

模拟ConfigObj实例

[英]Mocking ConfigObj instances

Using ConfigObj , I want to test some section creation code: 使用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)

I would like to write a few unit tests but I am hitting a problem. 我想写几个单元测试,但我遇到了问题。 For example, 例如,

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

Clearly, the test method will fail because of a TypeError as the argument of type 'Mock' is not iterable. 显然,测试方法因TypeError而失败,因为'Mock'类型的参数不可迭代。

How can I define the config object as a mock? 如何将config对象定义为模拟?

And this is why you should never, ever , post before you are wide awake: 这就是为什么你应该永远, 永远 ,后在你面前是很清醒:

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

I shall leave that answer/question here for posterity in case someone else has a brain failure… 我将把这个答案/问题留给后人,以防万一其他人有脑衰...

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

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