From bfbed13737fe3099aef67864a26cd8dd38b30e96 Mon Sep 17 00:00:00 2001 From: Martin Yeo Date: Tue, 27 Apr 2021 15:46:46 +0100 Subject: [PATCH] Iris-specific extension to AssertLogs(). --- lib/iris/tests/__init__.py | 25 +++++++++++++++++++ .../unit/experimental/ugrid/test_Mesh.py | 4 +-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/lib/iris/tests/__init__.py b/lib/iris/tests/__init__.py index b2eebc4f03..2ce9769bcc 100644 --- a/lib/iris/tests/__init__.py +++ b/lib/iris/tests/__init__.py @@ -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. diff --git a/lib/iris/tests/unit/experimental/ugrid/test_Mesh.py b/lib/iris/tests/unit/experimental/ugrid/test_Mesh.py index a2abb2124f..9b5f4e64e4 100644 --- a/lib/iris/tests/unit/experimental/ugrid/test_Mesh.py +++ b/lib/iris/tests/unit/experimental/ugrid/test_Mesh.py @@ -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) @@ -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)