1

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オブジェクトをモックとして定義するにはどうすればよいですか?

4

1 に答える 1

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

他の誰かが脳障害を起こした場合に備えて、その答え/質問を後世のためにここに残しておきます…</p>

于 2016-09-20T08:05:32.747 に答える