Skip to content

Commit

Permalink
check for required properties before put
Browse files Browse the repository at this point in the history
  • Loading branch information
cguardia authored Jul 15, 2019
1 parent 0b7eeed commit 460cceb
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/google/cloud/ndb/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -614,8 +614,12 @@ def _entity_to_ds_entity(entity, set_key=True):
Returns:
google.cloud.datastore.entity.Entity: The converted entity.
Raises:
ndb.exceptions.BadValueError: If entity has uninitialized properties.
"""
data = {}
uninitialized = []
exclude_from_indexes = []

for cls in type(entity).mro():
Expand All @@ -630,6 +634,9 @@ def _entity_to_ds_entity(entity, set_key=True):
):
continue

if not prop._is_initialized(entity):
uninitialized.append(prop._name)

value = prop._get_base_value_unwrapped_as_list(entity)
if not prop._repeated:
value = value[0]
Expand All @@ -638,6 +645,12 @@ def _entity_to_ds_entity(entity, set_key=True):
if not prop._indexed:
exclude_from_indexes.append(prop._name)

if uninitialized:
names = ", ".join(uninitialized)
raise exceptions.BadValueError(
"Entity has uninitialized properties: {}".format(names)
)

ds_entity = None
if set_key:
key = entity._key
Expand Down
11 changes: 11 additions & 0 deletions tests/system/test_crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -600,3 +600,14 @@ class SomeKind(ndb.Model):
assert isinstance(retrieved.updated_at, datetime.datetime)

dispose_of(key._key)


@pytest.mark.usefixtures("client_context")
def test_uninitialized_property(dispose_of):
class SomeKind(ndb.Model):
foo = ndb.StringProperty(required=True)

entity = SomeKind()

with pytest.raises(ndb.exceptions.BadValueError):
entity.put()
11 changes: 11 additions & 0 deletions tests/unit/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -4542,6 +4542,17 @@ class ThisKind(ThatKind):
assert pickle.loads(e_values[1].blob_value) == dill
assert "__key__" not in entity_pb.properties

@staticmethod
@pytest.mark.usefixtures("in_context")
def test_uninitialized_property():
class ThisKind(model.Model):
foo = model.StringProperty(required=True)

entity = ThisKind()

with pytest.raises(exceptions.BadValueError):
model._entity_to_protobuf(entity)


class TestExpando:
@staticmethod
Expand Down

0 comments on commit 460cceb

Please sign in to comment.