diff --git a/google/cloud/ndb/model.py b/google/cloud/ndb/model.py index 4b7dd6f1..57691a76 100644 --- a/google/cloud/ndb/model.py +++ b/google/cloud/ndb/model.py @@ -4026,7 +4026,7 @@ def _to_base_type(self, value): "Cannot convert to protocol buffer. Expected {} value; " "received {}".format(self._model_class.__name__, value) ) - return _entity_to_ds_entity(value) + return _entity_to_ds_entity(value, set_key=False) def _from_base_type(self, value): """Convert a value from the "base" value type for this property. diff --git a/tests/system/test_misc.py b/tests/system/test_misc.py new file mode 100644 index 00000000..eeb6d172 --- /dev/null +++ b/tests/system/test_misc.py @@ -0,0 +1,62 @@ +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Difficult to classify regression tests. +""" +import pickle + +import pytest +import six + +from google.cloud import ndb + + +# Pickle can only pickle/unpickle global classes +class PickleOtherKind(ndb.Model): + foo = ndb.IntegerProperty() + + @classmethod + def _get_kind(cls): + return "OtherKind" + + +class PickleSomeKind(ndb.Model): + other = ndb.StructuredProperty(PickleOtherKind) + + @classmethod + def _get_kind(cls): + return "SomeKind" + + +@pytest.mark.skipif( + six.PY2, reason="Pickling doesn't work in Python 2. See: Issue #311" +) +@pytest.mark.usefixtures("client_context") +def test_pickle_roundtrip_structured_property(dispose_of): + """Regression test for Issue #281. + + https://github.com/googleapis/python-ndb/issues/281 + """ + ndb.Model._kind_map["SomeKind"] = PickleSomeKind + ndb.Model._kind_map["OtherKind"] = PickleOtherKind + + entity = PickleSomeKind(other=PickleOtherKind(foo=1)) + key = entity.put() + dispose_of(key._key) + + entity = key.get(use_cache=False) + assert entity.other.key is None or entity.other.key.id() is None + entity = pickle.loads(pickle.dumps(entity)) + assert entity.other.foo == 1 diff --git a/tests/unit/test_model.py b/tests/unit/test_model.py index c29d3733..6853b7eb 100644 --- a/tests/unit/test_model.py +++ b/tests/unit/test_model.py @@ -3320,7 +3320,7 @@ class MineToo(model.Model): ds_bar = MineToo.bar._to_base_type(minetoo.bar) assert isinstance(ds_bar, entity_module.Entity) assert ds_bar["foo"] == "bar" - assert ds_bar.kind == "Mine" + assert ds_bar.key is None @staticmethod @pytest.mark.usefixtures("in_context")