11import numpy as np
2+ import pytest
3+ from typing import Dict , List
24
5+ from docarray import DocList
36from docarray .base_doc import AnyDoc , BaseDoc
47from docarray .typing import NdArray
58
@@ -22,3 +25,67 @@ class CustomDoc(BaseDoc):
2225 assert any_doc .text == doc .text
2326 assert any_doc .inner .text == doc .inner .text
2427 assert (any_doc .inner .tensor == doc .inner .tensor ).all ()
28+
29+
30+ @pytest .mark .parametrize ('protocol' , ['proto' , 'json' ])
31+ def test_any_document_from_to (protocol ):
32+ class InnerDoc (BaseDoc ):
33+ text : str
34+ t : Dict [str , str ]
35+
36+ class DocTest (BaseDoc ):
37+ text : str
38+ tags : Dict [str , int ]
39+ l : List [int ]
40+ d : InnerDoc
41+ ld : DocList [InnerDoc ]
42+
43+ inner_doc = InnerDoc (text = 'I am inner' , t = {'a' : 'b' })
44+ da = DocList [DocTest ](
45+ [
46+ DocTest (
47+ text = 'type1' ,
48+ tags = {'type' : 1 },
49+ l = [1 , 2 ],
50+ d = inner_doc ,
51+ ld = DocList [InnerDoc ]([inner_doc ]),
52+ ),
53+ DocTest (
54+ text = 'type2' ,
55+ tags = {'type' : 2 },
56+ l = [1 , 2 ],
57+ d = inner_doc ,
58+ ld = DocList [InnerDoc ]([inner_doc ]),
59+ ),
60+ ]
61+ )
62+
63+ from docarray .base_doc import AnyDoc
64+
65+ if protocol == 'proto' :
66+ aux = DocList [AnyDoc ].from_protobuf (da .to_protobuf ())
67+ else :
68+ aux = DocList [AnyDoc ].from_json (da .to_json ())
69+ assert len (aux ) == 2
70+ assert len (aux .id ) == 2
71+ for i , d in enumerate (aux ):
72+ assert d .tags ['type' ] == i + 1
73+ assert d .text == f'type{ i + 1 } '
74+ assert d .l == [1 , 2 ]
75+ if protocol == 'proto' :
76+ assert isinstance (d .d , AnyDoc )
77+ assert d .d .text == 'I am inner' # inner Document is a Dict
78+ assert d .d .t == {'a' : 'b' }
79+ else :
80+ assert isinstance (d .d , dict )
81+ assert d .d ['text' ] == 'I am inner' # inner Document is a Dict
82+ assert d .d ['t' ] == {'a' : 'b' }
83+ assert len (d .ld ) == 1
84+ if protocol == 'proto' :
85+ assert isinstance (d .ld [0 ], AnyDoc )
86+ assert d .ld [0 ].text == 'I am inner'
87+ assert d .ld [0 ].t == {'a' : 'b' }
88+ else :
89+ assert isinstance (d .ld [0 ], dict )
90+ assert d .ld [0 ]['text' ] == 'I am inner'
91+ assert d .ld [0 ]['t' ] == {'a' : 'b' }
0 commit comments