Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix polymodel put and get #151

Merged
merged 5 commits into from
Aug 5, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions src/google/cloud/ndb/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,14 @@ def _entity_from_ds_entity(ds_entity, model_class=None):
"""
model_class = model_class or Model._lookup_model(ds_entity.kind)
entity = model_class()

# Check if we are dealing with a PolyModel, and if so get correct subclass.
# We need to import here to avoid circular import.
from google.cloud.ndb import PolyModel

if isinstance(entity, PolyModel) and "class" in ds_entity:
entity = entity._class_map[tuple(ds_entity["class"])]()

if ds_entity.key:
entity._key = key_module.Key._from_ds_key(ds_entity.key)

Expand Down Expand Up @@ -655,8 +663,7 @@ def _entity_to_ds_entity(entity, set_key=True):
if set_key:
key = entity._key
if key is None:
# use _class_name instead of _get_kind, to get PolyModel right
key = key_module.Key(entity._class_name(), None)
key = key_module.Key(entity._get_kind(), None)
ds_entity = ds_entity_module.Entity(
key._key, exclude_from_indexes=exclude_from_indexes
)
Expand Down Expand Up @@ -1950,12 +1957,10 @@ def _validate_key(value, entity=None):
raise exceptions.BadValueError("Expected Key, got {!r}".format(value))

if entity and type(entity) not in (Model, Expando):
# Need to use _class_name instead of _get_kind, to be able to
# return the correct kind if this is a PolyModel
if value.kind() != entity._class_name():
if value.kind() != entity._get_kind():
raise KindError(
"Expected Key kind to be {}; received "
"{}".format(entity._class_name(), value.kind())
"{}".format(entity._get_kind(), value.kind())
)

return value
Expand Down Expand Up @@ -4518,7 +4523,7 @@ class a different name when stored in Google Cloud Datastore than the

@classmethod
def _class_name(cls):
"""A hook for polymodel to override.
"""A hook for PolyModel to override.

For regular models and expandos this is just an alias for
_get_kind(). For PolyModel subclasses, it returns the class name
Expand Down
29 changes: 29 additions & 0 deletions tests/system/test_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,35 @@ def make_entities():
assert not more


@pytest.mark.usefixtures("client_context")
def test_polymodel_query(ds_entity):
class Animal(ndb.PolyModel):
foo = ndb.IntegerProperty()

class Cat(Animal):
foo = ndb.IntegerProperty()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it necessary to repeat the definition of foo?


animal = Animal(foo=1)
animal.put()
cat = Cat(foo=2)
cat.put()

query = Animal.query()
results = eventually(query.fetch, _length_equals(2))

results = sorted(results, key=operator.attrgetter("foo"))
assert isinstance(results[0], Animal)
assert not isinstance(results[0], Cat)
assert isinstance(results[1], Animal)
assert isinstance(results[1], Cat)

query = Cat.query()
results = eventually(query.fetch, _length_equals(1))

assert isinstance(results[0], Animal)
assert isinstance(results[0], Cat)


@pytest.mark.skip("Requires an index")
@pytest.mark.usefixtures("client_context")
def test_query_repeated_property(ds_entity):
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1347,11 +1347,11 @@ class Mine(model.Model):

value = model.Key(Mine, "yours")
entity = unittest.mock.Mock(spec=Mine)
entity._class_name.return_value = "Mine"
entity._get_kind.return_value = "Mine"

result = model._validate_key(value, entity=entity)
assert result is value
entity._class_name.assert_called_once_with()
entity._get_kind.assert_called_once_with()

@staticmethod
@pytest.mark.usefixtures("in_context")
Expand All @@ -1361,13 +1361,13 @@ class Mine(model.Model):

value = model.Key(Mine, "yours")
entity = unittest.mock.Mock(spec=Mine)
entity._class_name.return_value = "NotMine"
entity._get_kind.return_value = "NotMine"

with pytest.raises(model.KindError):
model._validate_key(value, entity=entity)

calls = [unittest.mock.call(), unittest.mock.call()]
entity._class_name.assert_has_calls(calls)
entity._get_kind.assert_has_calls(calls)


class TestModelKey:
Expand Down
3 changes: 2 additions & 1 deletion tests/unit/test_polymodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,9 @@ class Animal(polymodel.PolyModel):
class Cat(Animal):
pass

key = datastore.Key("Cat", 123, project="testing")
key = datastore.Key("Animal", 123, project="testing")
datastore_entity = datastore.Entity(key=key)
datastore_entity["class"] = ["Animal", "Cat"]
protobuf = helpers.entity_to_protobuf(datastore_entity)
entity = model._entity_from_protobuf(protobuf)
assert isinstance(entity, Cat)