1
1
import pytest
2
2
from pydantic import BaseModel , Field
3
3
4
- from beanie import Link , PydanticObjectId
4
+ from beanie import BackLink , Link , PydanticObjectId
5
5
from beanie .odm .utils .pydantic import IS_PYDANTIC_V2
6
- from tests .odm .models import DocumentTestModelWithSoftDelete
6
+ from tests .odm .models import (
7
+ DocumentTestModelWithSoftDelete ,
8
+ DocumentWithBackLink ,
9
+ DocumentWithLink ,
10
+ )
7
11
8
12
9
13
class TestModel (BaseModel ):
@@ -20,6 +24,17 @@ def data_maker():
20
24
)
21
25
22
26
27
+ def data_maker_backlink_pair ():
28
+ back_link_doc = DocumentWithBackLink (
29
+ id = "5f4e3f3b7c0c9d001f7d4c8e" ,
30
+ back_link = BackLink (document_class = DocumentWithLink ),
31
+ )
32
+ link_doc = DocumentWithLink (
33
+ id = "5f4e3f3b7c0c9d001f7d4c8f" , link = back_link_doc
34
+ )
35
+ return link_doc , back_link_doc
36
+
37
+
23
38
@pytest .mark .skipif (
24
39
not IS_PYDANTIC_V2 ,
25
40
reason = "model dumping support is more complete with pydantic v2" ,
@@ -38,3 +53,18 @@ def test_id_types_serialized_when_dumping_to_json():
38
53
dumped = data_maker ().model_dump (mode = "json" )
39
54
assert isinstance (dumped ["my_id" ], str )
40
55
assert isinstance (dumped ["fake_doc" ]["id" ], str )
56
+
57
+
58
+ @pytest .mark .skipif (
59
+ not IS_PYDANTIC_V2 ,
60
+ reason = "model dumping support is more complete with pydantic v2" ,
61
+ )
62
+ def test_backlink_serialization_to_json_when_fetched ():
63
+ link_doc , back_link_doc = data_maker_backlink_pair ()
64
+
65
+ # presume we have fetched this BackLink by using fetch_links=True, nesting_depth=1
66
+ back_link_doc .back_link = link_doc
67
+
68
+ dumped_model = back_link_doc .model_dump (mode = "json" )
69
+
70
+ assert dumped_model ["back_link" ] == {"collection" : "DocumentWithLink" }
0 commit comments