Skip to content

kick off type validation before update #615

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

Merged
merged 2 commits into from
May 7, 2024
Merged
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
5 changes: 5 additions & 0 deletions aredis_om/model/model.py
Original file line number Diff line number Diff line change
@@ -1638,6 +1638,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):
19 changes: 19 additions & 0 deletions tests/test_hash_model.py
Original file line number Diff line number Diff line change
@@ -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
31 changes: 31 additions & 0 deletions tests/test_json_model.py
Original file line number Diff line number Diff line change
@@ -974,6 +974,37 @@ async def test_xfix_queries(m):


@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


async def test_model_with_dict():
class EmbeddedJsonModelWithDict(EmbeddedJsonModel):
dict: Dict