Mocking ConfigObj instances
<p>Using <a href="https://configobj.readthedocs.io" rel="nofollow">ConfigObj</a>, I want to test some <a href="https://configobj.readthedocs.io/en/latest/configobj.html#sections" rel="nofollow">section</a> creation code:</p>

<pre><code>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)
</code></pre>

<p>I would like to write a few unit tests but I am hitting a problem. For example, </p>

<pre><code>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()
</code></pre>

<p>Clearly, the test method will fail because of a <code>TypeError</code> as the argument of type 'Mock' is not iterable.</p>

<p>How can I define the <code>config</code> object as a mock?</p>

<p>And this is why you should never, <em>ever</em>, post before you are wide awake:</p>

<pre><code>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.")
</code></pre>

<p>I shall leave that answer/question here for posterity in case someone else has a brain failureâ¦</p>

python unit-testing mocking configobj