Skip to content

Commit 9af7d1b

Browse files
committed
Merge pull request #186 from tseaver/135-key-parent-contract
Fix #135: Document / enforce gcloud.datastore.key.Key.parent() contract
2 parents 1bb281c + 8ce18c9 commit 9af7d1b

2 files changed

Lines changed: 23 additions & 5 deletions

File tree

gcloud/datastore/key.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ def _clone(self):
3333
We make a shallow copy of the :class:`gcloud.datastore.dataset.Dataset`
3434
because it holds a reference an authenticated connection,
3535
which we don't want to lose.
36+
37+
:rtype: :class:`gcloud.datastore.key.Key`
38+
:returns: a new `Key` instance
3639
"""
3740
clone = copy.deepcopy(self)
3841
clone._dataset = self._dataset # Make a shallow copy of the Dataset.
@@ -265,8 +268,15 @@ def id_or_name(self):
265268
return self.id() or self.name()
266269

267270
def parent(self):#pragma NO COVER
268-
# See https://github.com/GoogleCloudPlatform/gcloud-python/issues/135
269-
raise NotImplementedError
271+
"""Getter: return a new key for the next highest element in path.
272+
273+
:rtype: :class:`gcloud.datastore.key.Key`
274+
:returns: a new `Key` instance, whose path consists of all but the last
275+
element of self's path. If self has only one path element, return None.
276+
"""
277+
if len(self._path) <= 1:
278+
return None
279+
return self.path(self.path()[:-1])
270280

271281
def __repr__(self): #pragma NO COVER
272282
return '<Key%s>' % self.path()

gcloud/datastore/test_key.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,14 @@ def test_id_or_name_w_name_only(self):
346346
key = self._makeOne(path=_PATH)
347347
self.assertEqual(key.id_or_name(), _NAME)
348348

349-
def _ugh(self):
350-
protokey = key.to_protobuf()
351-
self.assertEqual(protokey.partition_id.dataset_id, _DATASET)
349+
def test_parent_default(self):
350+
key = self._makeOne()
351+
self.assertEqual(key.parent(), None)
352+
353+
def test_parent_explicit_top_level(self):
354+
key = self._getTargetClass().from_path('abc', 'def')
355+
self.assertEqual(key.parent(), None)
356+
357+
def test_parent_explicit_nested(self):
358+
key = self._getTargetClass().from_path('abc', 'def', 'ghi', 123)
359+
self.assertEqual(key.parent().path(), [{'kind': 'abc', 'name': 'def'}])

0 commit comments

Comments
 (0)