Skip to content

Commit 5a37ae6

Browse files
committed
Add more tests for property validation logic.
1 parent c3a9c67 commit 5a37ae6

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

tests/test_property.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,12 +391,24 @@ class BadIntModel(pydantic.BaseModel):
391391
# Check validation for a model
392392
modelprop = example.properties["modelprop"]
393393
assert modelprop.validate(MyModel(a=3, b="four")) == MyModel(a=3, b="four")
394+
# Check that a valid model passes through unchanged: this should indicate that
395+
# we're not unnecessarily re-validating already-valid models.
394396
m = MyModel(a=3, b="four")
395397
assert modelprop.validate(m) is m
396398
assert modelprop.validate({"a": 5, "b": "six"}) == MyModel(a=5, b="six")
397399
for invalid in [{"c": 5}, (4, "f"), None]:
398400
with pytest.raises(pydantic.ValidationError):
399401
modelprop.validate(invalid)
402+
# Check that an invalid model doesn't get re-validated. This is intended behaviour:
403+
# it is another test that we're not unnecessarily re-validating a model that
404+
# should already have been validated when it was created.
405+
# Creating models with `model_construct` intentionally allows invalid models:
406+
# if this is used downstream, the downstream code should accept responsibility!
407+
bad_m = MyModel.model_construct(a="not an int", b=6)
408+
assert modelprop.validate(bad_m) is bad_m
409+
with pytest.raises(pydantic.ValidationError):
410+
# Check that passing the same data in as a dict fails validation.
411+
modelprop.validate(bad_m.model_dump())
400412

401413
# Check again for an odd rootmodel
402414
rootmodelprop = example.properties["rootmodelprop"]
@@ -409,6 +421,11 @@ class BadIntModel(pydantic.BaseModel):
409421
for invalid in ["seven", {"root": None}, 14.5, pydantic.RootModel[int](root=0)]:
410422
with pytest.raises(pydantic.ValidationError):
411423
modelprop.validate(invalid)
424+
# Tty constructing a model with an invalid root value, skipping validation
425+
invalid_model = rootmodelprop.model.model_construct(invalid)
426+
# The RootModel gets re-validated, in contrast to the BaseModel above.
427+
with pytest.raises(pydantic.ValidationError):
428+
assert modelprop.validate(invalid_model) == invalid
412429

413430

414431
def test_readonly_metadata():

0 commit comments

Comments
 (0)