How can I patch / mock logging.getlogger()

I have this code that I want to test:

log = logging.getLogger(__name__)


class A(object):
    def __init__(self):
        log.debug('Init')

but I cannot figure out how to assert that log.debug was called with ‘Init’

I tried patching logger but inspecting it I only found a getLogger mock.

I’m sure its simple, but I just cant figure it!

Thanks in advance for any and all help!

Answer

Alternative solution, which lets you verify that you’re using the correct logger too:

logger = logging.getLogger('path.to.module.under.test')
with mock.patch.object(logger, 'debug') as mock_debug:
    run_code_under_test()
    mock_debug.assert_called_once_with('Init')