diff --git a/meilisearch/models/document.py b/meilisearch/models/document.py index 79402749..a484e0fc 100644 --- a/meilisearch/models/document.py +++ b/meilisearch/models/document.py @@ -2,16 +2,12 @@ class Document: - __doc: Dict - def __init__(self, doc: Dict[str, Any]) -> None: - self.__doc = doc - for key in doc: - setattr(self, key, doc[key]) + self.__dict__.update(**doc) - def __getattr__(self, attr: str) -> str: - if attr in self.__doc.keys(): - return attr + def __getattr__(self, attr: str) -> Any: + if attr in self.__dict__: + return self.__dict__[attr] raise AttributeError(f"{self.__class__.__name__} object has no attribute {attr}") def __iter__(self) -> Iterator: diff --git a/tests/models/test_document.py b/tests/models/test_document.py index febce99f..8c0b9266 100644 --- a/tests/models/test_document.py +++ b/tests/models/test_document.py @@ -6,23 +6,23 @@ from meilisearch.models.document import Document +def test_doc_init(): + d = {"field1": "test 1", "field2": "test 2"} + document = Document(d) + assert dict(document) == d + + def test_getattr(): - document = Document({"field1": "test 1", "fiels2": "test 2"}) - assert document.__getattr__("field1") == "field1" + document = Document({"field1": "test 1", "field2": "test 2"}) + assert document.__getattr__("field1") == "test 1" def test_getattr_not_found(): - document = Document({"field1": "test 1", "fiels2": "test 2"}) + document = Document({"field1": "test 1", "field2": "test 2"}) with pytest.raises(AttributeError): document.__getattr__("bad") def test_iter(): - # I wrote a test what what this does, but I have a feeling this isn't actually what it was - # expected to do when written as it doesn't really act like I would expect an iterator to act. - document = Document({"field1": "test 1", "fiels2": "test 2"}) - - assert next(document.__iter__()) == ( - "_Document__doc", - {"field1": "test 1", "fiels2": "test 2"}, - ) + document = Document({"field1": "test 1", "field2": "test 2"}) + assert list(iter(document)) == [("field1", "test 1"), ("field2", "test 2")]