Add objectify decorator for readability

Because it isn't inherently clear what register_if(False) does on top of
a class, a functionally equivalent objectify decorator is added to make
things a little more readable.

The register_if() decorator was also cleaned up a little bit to reuse
the register() decorator. Unit tests were also added for the register()
functions to ensure none of the functionality is changing.

Change-Id: I0bec8e7e587b81dc0484a7b39f0cf57308d3b3d4
This commit is contained in:
Ryan Rossiter 2016-05-19 21:09:09 +00:00
parent 05d98a8432
commit 9403927de4
2 changed files with 46 additions and 2 deletions

View File

@ -143,13 +143,16 @@ class VersionedObjectRegistry(object):
def register_if(cls, condition):
def wraps(obj_cls):
if condition:
registry = cls()
registry._register_class(obj_cls)
obj_cls = cls.register(obj_cls)
else:
_make_class_properties(obj_cls)
return obj_cls
return wraps
@classmethod
def objectify(cls, obj_cls):
return cls.register_if(False)(obj_cls)
@classmethod
def obj_classes(cls):
registry = cls()

View File

@ -324,6 +324,47 @@ class TestRegistry(test.TestCase):
self.assertEqual(AVersionedObject1.reg_to, "one")
self.assertEqual(AVersionedObject2.reg_to, "two")
@mock.patch.object(base.VersionedObjectRegistry, '__new__')
def test_register(self, mock_registry):
mock_reg_obj = mock.Mock()
mock_registry.return_value = mock_reg_obj
mock_reg_obj._register_class = mock.Mock()
class my_class(object):
pass
base.VersionedObjectRegistry.register(my_class)
mock_reg_obj._register_class.assert_called_once_with(my_class)
@mock.patch.object(base.VersionedObjectRegistry, 'register')
def test_register_if(self, mock_register):
class my_class(object):
pass
base.VersionedObjectRegistry.register_if(True)(my_class)
mock_register.assert_called_once_with(my_class)
@mock.patch.object(base, '_make_class_properties')
def test_register_if_false(self, mock_make_props):
class my_class(object):
pass
base.VersionedObjectRegistry.register_if(False)(my_class)
mock_make_props.assert_called_once_with(my_class)
@mock.patch.object(base.VersionedObjectRegistry, 'register_if')
def test_objectify(self, mock_register_if):
mock_reg_callable = mock.Mock()
mock_register_if.return_value = mock_reg_callable
class my_class(object):
pass
base.VersionedObjectRegistry.objectify(my_class)
mock_register_if.assert_called_once_with(False)
mock_reg_callable.assert_called_once_with(my_class)
class TestObjMakeList(test.TestCase):