簡體   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