Skip to content

Commit

Permalink
Use Python descriptors to access entity properties
Browse files Browse the repository at this point in the history
  • Loading branch information
umax committed Dec 4, 2023
1 parent d7e0203 commit eabff78
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## 0.2.0 ()

- Use Python descriptors to access entity properties.
- Add validation for `id` field of PathElement.
- Add validation for `path` field of Key.

Expand Down
9 changes: 9 additions & 0 deletions aiodatastore/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ def __eq__(self, other: Any) -> bool:
and self.properties == other.properties
)

def __getitem__(self, key):
return self.properties[key]

def __setitem__(self, key, value):
self.properties[key] = value

def __delitem__(self, key):
del self.properties[key]

@classmethod
def from_ds(cls, data: Dict[str, Any]) -> "Entity":
properties = {}
Expand Down
19 changes: 19 additions & 0 deletions tests/unit/test_entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,25 @@ def test__init(self):
assert e.key is None
assert e.properties == {}

def test__getitem__(self):
entity = Entity(None, {"field1": StringValue("str1")})
assert entity["field1"] == entity.properties["field1"]

with self.assertRaises(KeyError):
entity["some-key123"]

def test__setitem__(self):
entity = Entity(None, {})
entity["field2"] = StringValue("str2")
assert entity["field2"] == entity.properties["field2"]

def test__delitem__(self):
entity = Entity(None, {"field3": StringValue("str3")})
assert len(entity.properties) == 1
del entity["field3"]
assert len(entity.properties) == 0
assert "field3" not in entity.properties

def test_eq(self):
key1 = Key(PartitionId("project1"), [PathElement("kind1")])
key2 = Key(PartitionId("project1"), [PathElement("kind1")])
Expand Down

0 comments on commit eabff78

Please sign in to comment.