Skip to content

Commit 2b436e9

Browse files
authored
Merge pull request #1113 from nnethercott/improve-document-serde
Fix Document model: bad test, attribute bug, and field cleanup
2 parents c2bab14 + 4cb403c commit 2b436e9

File tree

2 files changed

+15
-19
lines changed

2 files changed

+15
-19
lines changed

meilisearch/models/document.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,12 @@
22

33

44
class Document:
5-
__doc: Dict
6-
75
def __init__(self, doc: Dict[str, Any]) -> None:
8-
self.__doc = doc
9-
for key in doc:
10-
setattr(self, key, doc[key])
6+
self.__dict__.update(**doc)
117

12-
def __getattr__(self, attr: str) -> str:
13-
if attr in self.__doc.keys():
14-
return attr
8+
def __getattr__(self, attr: str) -> Any:
9+
if attr in self.__dict__:
10+
return self.__dict__[attr]
1511
raise AttributeError(f"{self.__class__.__name__} object has no attribute {attr}")
1612

1713
def __iter__(self) -> Iterator:

tests/models/test_document.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,23 @@
66
from meilisearch.models.document import Document
77

88

9+
def test_doc_init():
10+
d = {"field1": "test 1", "field2": "test 2"}
11+
document = Document(d)
12+
assert dict(document) == d
13+
14+
915
def test_getattr():
10-
document = Document({"field1": "test 1", "fiels2": "test 2"})
11-
assert document.__getattr__("field1") == "field1"
16+
document = Document({"field1": "test 1", "field2": "test 2"})
17+
assert document.__getattr__("field1") == "test 1"
1218

1319

1420
def test_getattr_not_found():
15-
document = Document({"field1": "test 1", "fiels2": "test 2"})
21+
document = Document({"field1": "test 1", "field2": "test 2"})
1622
with pytest.raises(AttributeError):
1723
document.__getattr__("bad")
1824

1925

2026
def test_iter():
21-
# I wrote a test what what this does, but I have a feeling this isn't actually what it was
22-
# expected to do when written as it doesn't really act like I would expect an iterator to act.
23-
document = Document({"field1": "test 1", "fiels2": "test 2"})
24-
25-
assert next(document.__iter__()) == (
26-
"_Document__doc",
27-
{"field1": "test 1", "fiels2": "test 2"},
28-
)
27+
document = Document({"field1": "test 1", "field2": "test 2"})
28+
assert list(iter(document)) == [("field1", "test 1"), ("field2", "test 2")]

0 commit comments

Comments
 (0)