FakeLogger: Mis-formatted log messages will raise Exception
When using the FakeLogger, have mis-formatted logging messages raise an exception. Normally when using the logging module, mis-formatted logging messages will not raise an exception. Instead the exception will be printed but not raised. Change this behavior so that mis-formatted log messages can be caught during unit-testing. Closes-Bug: #1503049 Change-Id: I8d3e94d131289300ae020eb1d63306489e986335
This commit is contained in:
3
NEWS
3
NEWS
@@ -13,6 +13,9 @@ NEXT
|
||||
backport has significant bugfixes over older but still supported CPython
|
||||
stdlib versions. (Robert Collins)
|
||||
|
||||
* ``fixtures.FakeLogger`` now detects incorrectly formatted log messages.
|
||||
(John Villalovos, #1503049)
|
||||
|
||||
1.3.1
|
||||
~~~~~
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
# limitations under that license.
|
||||
|
||||
from logging import StreamHandler, getLogger, INFO, Formatter
|
||||
import six
|
||||
import sys
|
||||
|
||||
from testtools.compat import _u
|
||||
|
||||
@@ -61,6 +63,12 @@ class LogHandler(Fixture):
|
||||
self.addCleanup(logger.removeHandler, self.handler)
|
||||
|
||||
|
||||
class StreamHandlerRaiseException(StreamHandler):
|
||||
"""Handler class that will raise an exception on formatting errors."""
|
||||
def handleError(self, record):
|
||||
six.reraise(*sys.exc_info())
|
||||
|
||||
|
||||
class FakeLogger(Fixture):
|
||||
"""Replace a logger and capture its output."""
|
||||
|
||||
@@ -98,7 +106,7 @@ class FakeLogger(Fixture):
|
||||
name = _u("pythonlogging:'%s'") % self._name
|
||||
output = self.useFixture(StringStream(name)).stream
|
||||
self._output = output
|
||||
handler = StreamHandler(output)
|
||||
handler = StreamHandlerRaiseException(output)
|
||||
if self._format:
|
||||
formatter = (self._formatter or Formatter)
|
||||
handler.setFormatter(formatter(self._format, self._datefmt))
|
||||
|
||||
@@ -17,6 +17,7 @@ import logging
|
||||
import sys
|
||||
import time
|
||||
|
||||
import testtools
|
||||
from testtools import TestCase
|
||||
from testtools.compat import StringIO
|
||||
|
||||
@@ -140,6 +141,11 @@ class FakeLoggerTest(TestCase, TestWithFixtures):
|
||||
except:
|
||||
pass
|
||||
|
||||
def test_exceptionraised(self):
|
||||
with FakeLogger():
|
||||
with testtools.ExpectedException(TypeError):
|
||||
logging.info("Some message", "wrongarg")
|
||||
|
||||
|
||||
class LogHandlerTest(TestCase, TestWithFixtures):
|
||||
|
||||
|
||||
Reference in New Issue
Block a user