首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模拟ConfigObj实例

模拟ConfigObj实例
EN

Stack Overflow用户
提问于 2016-09-20 07:57:04
回答 1查看 116关注 0票数 1

使用ConfigObj,我想测试一些部分创建代码:

代码语言:javascript
复制
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)

我想写一些单元测试,但我遇到了一个问题。例如,

代码语言:javascript
复制
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对象定义为模拟?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-20 08:05:32

这就是为什么你不应该,永远,永远,在你完全清醒之前发帖:

代码语言:javascript
复制
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.")

我将把这个答案/问题留给后人,以防其他人出现脑功能衰竭…。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39588617

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档