Python mocking logging while retaining log output

社会主义新天地 提交于 2020-02-01 07:59:04

问题


I have a series of unit/integration tests which using the python logging module. I would like to test that the right things are logged when appropriate which I can achieve using the mock module as follows:

@mock.patch('logging.Logger.info')

However, when I do this the actual logging is stopped (for obvious reasons!) and this is useful for me to debug why my tests are working etc.

My question is as follows: Is there a way in why I can mock out logging calls so I can assert they have been called with the expected arguments but still keep the logging functionality?

My current approach is to make a wrapper class which contains a MagicMock and an un-mocked logger:

class MonkeyPatchLogger(object):
    MOCK = mock.MagicMock()
    @classmethod
    def info(cls, *args, **kwargs):
        cls.MOCK(*args, **kwargs)
        logger.info(*args, **kwargs)

but this isn't working.

Cheers, Jack


回答1:


I posted this in 2010 about unit testing and logging - it should still be relevant. The contents are too big to summarise in an answer here, so a link is provided.




回答2:


You should look that Mock(wraps=...):

wraps: Item for the mock object to wrap. If wraps is not None then calling the Mock will pass the call through to the wrapped object (returning the real result). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn’t exist will raise an AttributeError).

If the mock has an explicit return_value set then calls are not passed to the wrapped object and the return_value is returned instead.



来源:https://stackoverflow.com/questions/44204459/python-mocking-logging-while-retaining-log-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!