简体   繁体   中英

Mocking ConfigObj instances

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…

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM