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
changes/22/639822/1
Ben Nemec 4 years ago
parent 106a86d18e
commit 61732757c0
  1. 2
      oslo_policy/generator.py
  2. 18
      oslo_policy/tests/test_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

@ -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')

Loading…
Cancel
Save