Skip to content

Commit

Permalink
FakeLogger: Mis-formatted log messages will raise Exception
Browse files Browse the repository at this point in the history
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
  • Loading branch information
John L. Villalovos committed Oct 8, 2015
1 parent 5522eb9 commit 67dd295
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
3 changes: 3 additions & 0 deletions NEWS
Original file line number Diff line number Diff line change
Expand Up @@ -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
~~~~~

Expand Down
10 changes: 9 additions & 1 deletion fixtures/_fixtures/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
# limitations under that license.

from logging import StreamHandler, getLogger, INFO, Formatter
import six
import sys

from testtools.compat import _u

Expand Down Expand Up @@ -61,6 +63,12 @@ def _setUp(self):
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."""

Expand Down Expand Up @@ -98,7 +106,7 @@ def _setUp(self):
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))
Expand Down
6 changes: 6 additions & 0 deletions fixtures/tests/_fixtures/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import sys
import time

import testtools
from testtools import TestCase
from testtools.compat import StringIO

Expand Down Expand Up @@ -140,6 +141,11 @@ def test_logging_output_included_in_details(self):
except:
pass

def test_exceptionraised(self):
with FakeLogger():
with testtools.ExpectedException(TypeError):
logging.info("Some message", "wrongarg")


class LogHandlerTest(TestCase, TestWithFixtures):

Expand Down

0 comments on commit 67dd295

Please sign in to comment.