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

kick off type validation before update #615

Merged
merged 2 commits into from
May 7, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions aredis_om/model/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1628,6 +1628,11 @@ def check(self):
*_, validation_error = validate_model(self.__class__, self.__dict__)
if validation_error:
raise validation_error
else:
from pydantic import TypeAdapter

adapter = TypeAdapter(self.__class__)
adapter.validate_python(self.__dict__)


class HashModel(RedisModel, abc.ABC):
Expand Down
19 changes: 19 additions & 0 deletions tests/test_hash_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -875,3 +875,22 @@ async def test_xfix_queries(members, m):

result = await m.Member.find(m.Member.bio % "*eat*").first()
assert result.first_name == "Andrew"


@py_test_mark_asyncio
async def test_update_validation():
class TestUpdate(HashModel):
name: str
age: int

await Migrator().run()
t = TestUpdate(name="steve", age=34)
await t.save()
update_dict = dict()
update_dict["age"] = "cat"

with pytest.raises(ValidationError):
await t.update(**update_dict)

rematerialized = await TestUpdate.find(TestUpdate.pk == t.pk).first()
assert rematerialized.age == 34
32 changes: 32 additions & 0 deletions tests/test_json_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -971,3 +971,35 @@ async def test_xfix_queries(m):

result = await m.Member.find(m.Member.bio % "*ack*").first()
assert result.first_name == "Steve"


@py_test_mark_asyncio
async def test_update_validation():

class Embedded(EmbeddedJsonModel):
price: float
name: str = Field(index=True)

class TestUpdatesClass(JsonModel):
name: str
age: int
embedded: Embedded

await Migrator().run()
embedded = Embedded(price=3.14, name="foo")
t = TestUpdatesClass(name="str", age=42, embedded=embedded)
await t.save()

update_dict = dict()
update_dict["age"] = "foo"
with pytest.raises(ValidationError):
await t.update(**update_dict)

t.age = 42
update_dict.clear()
update_dict["embedded"] = "hello"
with pytest.raises(ValidationError):
await t.update(**update_dict)

rematerialized = await TestUpdatesClass.find(TestUpdatesClass.pk == t.pk).first()
assert rematerialized.age == 42
Loading