Using ConfigObj, I want to test some section creation 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)
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.
How can I define the config
object as a mock?
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…