Skip to content

Commit 06dc84b

Browse files
committed
Fix deepcopy issue with classes deriving from dicts (mongomock#52)
1 parent 71459bd commit 06dc84b

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

Makefile

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
test:
2+
nosetests

mongomock/__init__.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -141,15 +141,19 @@ def insert(self, data):
141141
if isinstance(data, list):
142142
return [self._insert(element) for element in data]
143143
return self._insert(data)
144+
144145
def _insert(self, data):
145-
if not '_id' in data:
146+
if '_id' not in data:
146147
data['_id'] = ObjectId()
147148
object_id = data['_id']
148149
if object_id in self._documents:
149150
raise DuplicateKeyError("Duplicate Key Error", 11000)
150-
self._documents[object_id] = copy.deepcopy(data)
151+
self._documents[object_id] = self._internalize_dict(data)
151152
return object_id
152153

154+
def _internalize_dict(self, d):
155+
return dict((k, copy.deepcopy(v)) for k, v in iteritems(d))
156+
153157
def _has_key(self, doc, key):
154158
return key in doc
155159

tests/test__mongomock.py

+15
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,21 @@ def test__getting_collection_via_getattr(self):
8888
self.assertIs(col1, self.db['some_collection_here'])
8989
self.assertIsInstance(col1, mongomock.Collection)
9090

91+
def test__save_class_deriving_from_dict(self):
92+
# See https://github.com/vmalloc/mongomock/issues/52
93+
class Document(dict):
94+
def __init__(self, collection):
95+
self.collection = collection
96+
super(Document, self).__init__()
97+
self.save()
98+
99+
def save(self):
100+
self.collection.save(self)
101+
102+
doc = Document(self.db.collection)
103+
self.assertIn("_id", doc)
104+
self.assertNotIn("collection", doc)
105+
91106
def test__getting_collection_via_getitem(self):
92107
col1 = self.db['some_collection_here']
93108
col2 = self.db['some_collection_here']

0 commit comments

Comments
 (0)