Skip to content

Commit 75fa446

Browse files
authored
kick off type validation before update (#615)
1 parent 6fb2a73 commit 75fa446

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

aredis_om/model/model.py

+5
Original file line numberDiff line numberDiff line change
@@ -1638,6 +1638,11 @@ def check(self):
16381638
*_, validation_error = validate_model(self.__class__, self.__dict__)
16391639
if validation_error:
16401640
raise validation_error
1641+
else:
1642+
from pydantic import TypeAdapter
1643+
1644+
adapter = TypeAdapter(self.__class__)
1645+
adapter.validate_python(self.__dict__)
16411646

16421647

16431648
class HashModel(RedisModel, abc.ABC):

tests/test_hash_model.py

+19
Original file line numberDiff line numberDiff line change
@@ -875,3 +875,22 @@ async def test_xfix_queries(members, m):
875875

876876
result = await m.Member.find(m.Member.bio % "*eat*").first()
877877
assert result.first_name == "Andrew"
878+
879+
880+
@py_test_mark_asyncio
881+
async def test_update_validation():
882+
class TestUpdate(HashModel):
883+
name: str
884+
age: int
885+
886+
await Migrator().run()
887+
t = TestUpdate(name="steve", age=34)
888+
await t.save()
889+
update_dict = dict()
890+
update_dict["age"] = "cat"
891+
892+
with pytest.raises(ValidationError):
893+
await t.update(**update_dict)
894+
895+
rematerialized = await TestUpdate.find(TestUpdate.pk == t.pk).first()
896+
assert rematerialized.age == 34

tests/test_json_model.py

+31
Original file line numberDiff line numberDiff line change
@@ -974,6 +974,37 @@ async def test_xfix_queries(m):
974974

975975

976976
@py_test_mark_asyncio
977+
async def test_update_validation():
978+
979+
class Embedded(EmbeddedJsonModel):
980+
price: float
981+
name: str = Field(index=True)
982+
983+
class TestUpdatesClass(JsonModel):
984+
name: str
985+
age: int
986+
embedded: Embedded
987+
988+
await Migrator().run()
989+
embedded = Embedded(price=3.14, name="foo")
990+
t = TestUpdatesClass(name="str", age=42, embedded=embedded)
991+
await t.save()
992+
993+
update_dict = dict()
994+
update_dict["age"] = "foo"
995+
with pytest.raises(ValidationError):
996+
await t.update(**update_dict)
997+
998+
t.age = 42
999+
update_dict.clear()
1000+
update_dict["embedded"] = "hello"
1001+
with pytest.raises(ValidationError):
1002+
await t.update(**update_dict)
1003+
1004+
rematerialized = await TestUpdatesClass.find(TestUpdatesClass.pk == t.pk).first()
1005+
assert rematerialized.age == 42
1006+
1007+
9771008
async def test_model_with_dict():
9781009
class EmbeddedJsonModelWithDict(EmbeddedJsonModel):
9791010
dict: Dict

0 commit comments

Comments
 (0)