From 40314950d0ce27ac02a89fc41fdd8c57ab2c9c85 Mon Sep 17 00:00:00 2001 From: Kiall Mac Innes Date: Thu, 3 Jul 2014 17:21:02 +0100 Subject: [PATCH] Implement DesignateObject.__deepcopy__ Change-Id: I9cbd7255a9dd4b5e1a79b53cefb41216603c7ae8 --- designate/objects/base.py | 20 ++++++++++++++++++++ designate/tests/test_objects/test_base.py | 22 ++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/designate/objects/base.py b/designate/objects/base.py index 1a3a87e6..607ffef3 100644 --- a/designate/objects/base.py +++ b/designate/objects/base.py @@ -12,6 +12,8 @@ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. +import copy + import six from designate.openstack.common import importutils @@ -215,6 +217,24 @@ class DesignateObject(DictObjectMixin): else: self._obj_changes.clear() + def __deepcopy__(self, memodict={}): + """ + Efficiently make a deep copy of this object. + + "Efficiently" is used here a relative term, this will be faster + than allowing python to naively deepcopy the object. + """ + c_obj = self.__class__() + + for field in self.FIELDS: + if self.obj_attr_is_set(field): + c_field = copy.deepcopy(getattr(self, field), memodict) + setattr(c_obj, field, c_field) + + c_obj._obj_changes = set(self._obj_changes) + + return c_obj + def __iter__(self): # Redundant? self._i = iter(self.FIELDS) diff --git a/designate/tests/test_objects/test_base.py b/designate/tests/test_objects/test_base.py index 4b17096a..6f37623b 100644 --- a/designate/tests/test_objects/test_base.py +++ b/designate/tests/test_objects/test_base.py @@ -13,6 +13,8 @@ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. +import copy + import testtools from designate.openstack.common import log as logging @@ -204,3 +206,23 @@ class DesignateObjectTest(tests.TestCase): self.assertEqual(1, len(obj.obj_what_changed())) self.assertEqual({'name': "My Name"}, obj.obj_get_changes()) + + def test_deepcopy(self): + # Create the Original object + o_obj = TestObject() + o_obj.id = "My ID" + o_obj.name = "My Name" + + # Clear the "changed" flag for one of the two fields we set + o_obj.obj_reset_changes(['name']) + + # Deepcopy the object + c_obj = copy.deepcopy(o_obj) + + # Ensure the copy was sucessful + self.assertEqual(o_obj.id, c_obj.id) + self.assertEqual(o_obj.name, c_obj.name) + self.assertEqual(o_obj.nested, c_obj.nested) + + self.assertEqual(o_obj.obj_get_changes(), c_obj.obj_get_changes()) + self.assertEqual(o_obj.to_primitive(), c_obj.to_primitive())