From 059e4412468bce0211e10ae8ed275122acd758b1 Mon Sep 17 00:00:00 2001 From: Adam Chainz Date: Fri, 4 Sep 2015 15:05:50 +0100 Subject: [PATCH] Fix logcapture plugin to capture output from non-propagating loggers, and to not output 'no handlers could be found' message --- nose/plugins/logcapture.py | 7 +++++++ unit_tests/test_logcapture_plugin.py | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/nose/plugins/logcapture.py b/nose/plugins/logcapture.py index 4c9a79f6..9623ae52 100644 --- a/nose/plugins/logcapture.py +++ b/nose/plugins/logcapture.py @@ -194,6 +194,13 @@ def setupLoghandler(self): if isinstance(handler, MyMemoryHandler): root_logger.handlers.remove(handler) root_logger.addHandler(self.handler) + # Also patch any non-propagating loggers in the tree + for logger in logging.Logger.manager.loggerDict.values(): + if not getattr(logger, 'propagate', True) and hasattr(logger, "addHandler"): + for handler in logger.handlers[:]: + if isinstance(handler, MyMemoryHandler): + logger.handlers.remove(handler) + logger.addHandler(self.handler) # to make sure everything gets captured loglevel = getattr(self, "loglevel", "NOTSET") root_logger.setLevel(getattr(logging, loglevel)) diff --git a/unit_tests/test_logcapture_plugin.py b/unit_tests/test_logcapture_plugin.py index 63aa651e..1f2d50f9 100644 --- a/unit_tests/test_logcapture_plugin.py +++ b/unit_tests/test_logcapture_plugin.py @@ -255,3 +255,21 @@ class Dummy: assert msg in ev else: assert msg.encode('utf-8') in ev + + def test_non_propagating_loggers_handled(self): + c = LogCapture() + parser = OptionParser() + c.addOptions(parser, {}) + options, args = parser.parse_args([]) + c.configure(options, Config()) + + logger = logging.getLogger('foo.yes') + logger.propagate = False + + c.start() + logger.debug("test message") + c.end() + + records = c.formatLogRecords() + eq_(1, len(records)) + assert records[0].startswith('foo.yes:'), records[0]