Skip to content

Commit

Permalink
Making Key parent data agree with child.
Browse files Browse the repository at this point in the history
Also making _clone() and _parent() methods use self.__class__
to make subclassing easier.

h/t to @tseaver for feedback.
  • Loading branch information
dhermes committed Dec 31, 2014
1 parent 8486080 commit 2fe9e6e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
19 changes: 13 additions & 6 deletions gcloud/datastore/key.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,14 @@ def _combine_args(self):
# We know that _parent.path() will return a copy.
child_path = self._parent.path + child_path
self._flat_path = self._parent.flat_path + self._flat_path
self._namespace = self._namespace or self._parent.namespace
self._dataset_id = self._dataset_id or self._parent.dataset_id
if (self._namespace is not None and
self._namespace != self._parent.namespace):
raise ValueError('Child namespace must agree with parent\'s.')
self._namespace = self._parent.namespace
if (self._dataset_id is not None and
self._dataset_id != self._parent.dataset_id):
raise ValueError('Child dataset ID must agree with parent\'s.')
self._dataset_id = self._parent.dataset_id

return child_path

Expand All @@ -168,8 +174,9 @@ def _clone(self):
:rtype: :class:`gcloud.datastore.key.Key`
:returns: A new `Key` instance with the same data as the current one.
"""
return Key(*self.flat_path, parent=self.parent,
dataset_id=self.dataset_id, namespace=self.namespace)
return self.__class__(*self.flat_path, parent=self.parent,
dataset_id=self.dataset_id,
namespace=self.namespace)

def completed_key(self, id_or_name):
"""Creates new key from existing partial key by adding final ID/name.
Expand Down Expand Up @@ -321,8 +328,8 @@ def _make_parent(self):
else:
parent_args = self.flat_path[:-2]
if parent_args:
return Key(*parent_args, dataset_id=self.dataset_id,
namespace=self.namespace)
return self.__class__(*parent_args, dataset_id=self.dataset_id,
namespace=self.namespace)

@property
def parent(self):
Expand Down
10 changes: 10 additions & 0 deletions gcloud/datastore/test_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,16 @@ def test_ctor_parent_bad_type(self):
with self.assertRaises(AttributeError):
self._makeOne('KIND2', 1234, parent=('KIND1', 1234))

def test_ctor_parent_bad_namespace(self):
parent_key = self._makeOne('KIND', 1234, namespace='FOO')
with self.assertRaises(ValueError):
self._makeOne('KIND2', 1234, namespace='BAR', parent=parent_key)

def test_ctor_parent_bad_dataset_id(self):
parent_key = self._makeOne('KIND', 1234, dataset_id='FOO')
with self.assertRaises(ValueError):
self._makeOne('KIND2', 1234, dataset_id='BAR', parent=parent_key)

def test_ctor_explicit(self):
_DATASET = 'DATASET-ALT'
_NAMESPACE = 'NAMESPACE'
Expand Down

0 comments on commit 2fe9e6e

Please sign in to comment.