From 61732757c0e934a7c61cef2b2d2651f5abbb6fc6 Mon Sep 17 00:00:00 2001 From: Ben Nemec Date: Wed, 27 Feb 2019 20:53:11 +0000 Subject: [PATCH] Provide more specific error when namespace is missing Previously if a non-existent namespace was specified, we just got a generic KeyError from stevedore that didn't say a whole lot about what went wrong. You pretty much had to go read the code to figure out what happened. This change adds an explicit check for a missing namespace and raises a KeyError with a more specific error message that explains what is wrong. Change-Id: Ia56d4655d70cee78661567188a977f67b7c3ee78 Closes-Bug: 1817953 --- oslo_policy/generator.py | 2 ++ oslo_policy/tests/test_generator.py | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/oslo_policy/generator.py b/oslo_policy/generator.py index c6ecd5b2..1ea768ea 100644 --- a/oslo_policy/generator.py +++ b/oslo_policy/generator.py @@ -84,6 +84,8 @@ def _get_enforcer(namespace): names=[namespace], on_load_failure_callback=on_load_failure_callback, invoke_on_load=True) + if namespace not in mgr: + raise KeyError('Namespace "%s" not found.' % namespace) enforcer = mgr[namespace].obj return enforcer diff --git a/oslo_policy/tests/test_generator.py b/oslo_policy/tests/test_generator.py index 98355ffd..ab0940aa 100644 --- a/oslo_policy/tests/test_generator.py +++ b/oslo_policy/tests/test_generator.py @@ -675,3 +675,21 @@ class UpgradePolicyTestCase(base.PolicyBaseTestCase): expected = '''new_policy_name: rule:admin ''' self.assertEqual(expected, stdout.getvalue()) + + +@mock.patch('stevedore.named.NamedExtensionManager') +class GetEnforcerTestCase(base.PolicyBaseTestCase): + def test_get_enforcer(self, mock_manager): + mock_instance = mock.MagicMock() + mock_instance.__contains__.return_value = True + mock_manager.return_value = mock_instance + mock_item = mock.Mock() + mock_item.obj = 'test' + mock_instance.__getitem__.return_value = mock_item + self.assertEqual('test', generator._get_enforcer('foo')) + + def test_get_enforcer_missing(self, mock_manager): + mock_instance = mock.MagicMock() + mock_instance.__contains__.return_value = False + mock_manager.return_value = mock_instance + self.assertRaises(KeyError, generator._get_enforcer, 'nonexistent')