From a785ad34417024ce4adb49420782b3b2cd3033f0 Mon Sep 17 00:00:00 2001 From: Matthew Booth Date: Fri, 30 Jun 2017 12:34:03 +0100 Subject: [PATCH] Allow wrapping of closures get_wrapped_function() assumes that any function which is a closure is a decorator, and therefore has a function argument. This assumption fails when the function is just a regular closure, and we end up falling through and returning None. Change-Id: I18da02d83fd9884e2e8c2173acf124140bd43525 --- nova/safe_utils.py | 2 ++ nova/tests/unit/test_safeutils.py | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/nova/safe_utils.py b/nova/safe_utils.py index 64885a32aa6c..0ee71620a4a0 100644 --- a/nova/safe_utils.py +++ b/nova/safe_utils.py @@ -36,4 +36,6 @@ def get_wrapped_function(function): elif hasattr(closure.cell_contents, '__call__'): return closure.cell_contents + return function + return _get_wrapped_function(function) diff --git a/nova/tests/unit/test_safeutils.py b/nova/tests/unit/test_safeutils.py index 1215c30b4386..cfac25560ffc 100644 --- a/nova/tests/unit/test_safeutils.py +++ b/nova/tests/unit/test_safeutils.py @@ -18,6 +18,15 @@ from nova import safe_utils from nova import test +def get_closure(): + x = 1 + + def wrapper(self, instance, red=None, blue=None): + return x + + return wrapper + + class WrappedCodeTestCase(test.NoDBTestCase): """Test the get_wrapped_function utility method.""" @@ -68,3 +77,13 @@ class WrappedCodeTestCase(test.NoDBTestCase): self.assertIn('instance', func_code.co_varnames) self.assertIn('red', func_code.co_varnames) self.assertIn('blue', func_code.co_varnames) + + def test_closure(self): + closure = get_closure() + func = safe_utils.get_wrapped_function(closure) + func_code = func.__code__ + self.assertEqual(4, len(func_code.co_varnames)) + self.assertIn('self', func_code.co_varnames) + self.assertIn('instance', func_code.co_varnames) + self.assertIn('red', func_code.co_varnames) + self.assertIn('blue', func_code.co_varnames)