Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed Link validation #714

Merged
merged 5 commits into from
Oct 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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