Skip to content

Commit

Permalink
Fixed Link validation (#714)
Browse files Browse the repository at this point in the history
* fixed Link validation in validate_self method

* reorganized tests

* added comments

* imports sorted
  • Loading branch information
iterlace authored Oct 12, 2023
1 parent b264169 commit 549aa8c
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 1 deletion.
10 changes: 10 additions & 0 deletions beanie/odm/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,16 @@ def validate(v: Union[DBRef, T], validation_info: ValidationInfo):
return cls(ref=v, document_class=document_class)
if isinstance(v, Link):
return v
if isinstance(v, dict) and v.keys() == {"id", "collection"}:
return cls(
ref=DBRef(
collection=v["collection"],
id=TypeAdapter(
document_class.model_fields["id"].annotation
).validate_python(v["id"]),
),
document_class=document_class,
)
if isinstance(v, dict) or isinstance(v, BaseModel):
return parse_obj(document_class, v)
new_id = TypeAdapter(
Expand Down
2 changes: 2 additions & 0 deletions tests/odm/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
Vehicle,
Window,
WindowWithRevision,
WindowWithValidationOnSave,
Yard,
YardWithRevision,
)
Expand Down Expand Up @@ -210,6 +211,7 @@ async def init(db):
DocumentWithRevisionTurnedOn,
House,
Window,
WindowWithValidationOnSave,
Door,
Roof,
Yard,
Expand Down
17 changes: 16 additions & 1 deletion tests/odm/documents/test_validation_on_save.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import pytest
from pydantic import ValidationError

from tests.odm.models import DocumentWithValidationOnSave
from tests.odm.models import (
DocumentWithValidationOnSave,
Lock,
WindowWithValidationOnSave,
)


async def test_validate_on_insert():
Expand Down Expand Up @@ -37,3 +41,14 @@ async def test_validate_on_save_skip_action():
doc = DocumentWithValidationOnSave(num_1=1, num_2=2)
await doc.insert(skip_actions=["num_2_plus_1"])
assert doc.num_2 == 2


async def test_validate_on_save_dbref():
lock = Lock(k=1)
await lock.insert()
window = WindowWithValidationOnSave(
x=1,
y=1,
lock=lock.to_ref(), # this is what exactly we want to test
)
await window.insert()
9 changes: 9 additions & 0 deletions tests/odm/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,15 @@ class Window(Document):
lock: Optional[Link[Lock]] = None


class WindowWithValidationOnSave(Document):
x: int
y: int
lock: Optional[Link[Lock]] = None

class Settings:
validate_on_save = True


class Door(Document):
t: int = 10
window: Optional[Link[Window]] = None
Expand Down

0 comments on commit 549aa8c

Please sign in to comment.