Skip to content

Commit

Permalink
Iris-specific extension to AssertLogs().
Browse files Browse the repository at this point in the history
  • Loading branch information
trexfeathers committed Apr 27, 2021
1 parent 24cbc66 commit bfbed13
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
25 changes: 25 additions & 0 deletions lib/iris/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,31 @@ def assertWarnsRegexp(self, expected_regexp=""):
msg = msg.format(expected_regexp)
self.assertTrue(matches, msg)

@contextlib.contextmanager
def assertLogs(self, logger=None, level=None):
"""
An extended version of the usual :meth:`unittest.TestCase.assertLogs`,
which also exercises the logger's message formatting.
The inherited version of this method temporarily *replaces* the logger
in order to capture log records generated within the context.
However, in doing so it prevents any messages from being formatted
by the original logger.
This version first calls the original method, but then *also* exercises
the message formatters of all the logger's handlers, just to check that
there are no formatting errors.
"""
# Invoke the standard assertLogs behaviour.
assertlogging_context = super().assertLogs(logger, level)
with assertlogging_context as watcher:
# Run the caller context, as per original method.
yield watcher
# Check for any formatting errors by running all the formatters.
for record in watcher.records:
for handler in assertlogging_context.logger.handlers:
handler.format(record)

@contextlib.contextmanager
def assertNoWarningsRegexp(self, expected_regexp=""):
# Check that no warning matching the given expression is raised.
Expand Down
4 changes: 2 additions & 2 deletions lib/iris/tests/unit/experimental/ugrid/test_Mesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -816,7 +816,7 @@ def test_remove_connectivities(self):
for kwargs in negative_kwargs:
with self.assertLogs(ugrid.logger, level="DEBUG") as log:
# Check that the only debug log is the one we inserted.
ugrid.logger.debug("foo")
ugrid.logger.debug("foo", extra=dict(cls=None))
self.mesh.remove_connectivities(**kwargs)
self.assertEqual(1, len(log.records))
self.assertEqual(self.EDGE_NODE, self.mesh.edge_node_connectivity)
Expand Down Expand Up @@ -854,7 +854,7 @@ def test_remove_coords(self):
for kwargs in negative_kwargs:
with self.assertLogs(ugrid.logger, level="DEBUG") as log:
# Check that the only debug log is the one we inserted.
ugrid.logger.debug("foo")
ugrid.logger.debug("foo", extra=dict(cls=None))
self.mesh.remove_coords(**kwargs)
self.assertEqual(1, len(log.records))
self.assertEqual(self.NODE_LON, self.mesh.node_coords.node_x)
Expand Down

0 comments on commit bfbed13

Please sign in to comment.