Skip to content

Commit a28076d

Browse files
committed
Add more tests for property validation logic.
1 parent 682a530 commit a28076d

1 file changed

Lines changed: 17 additions & 0 deletions

File tree

tests/test_property.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -396,12 +396,24 @@ class BadIntModel(pydantic.BaseModel):
396396
# Check validation for a model
397397
modelprop = example.properties["modelprop"]
398398
assert modelprop.validate(MyModel(a=3, b="four")) == MyModel(a=3, b="four")
399+
# Check that a valid model passes through unchanged: this should indicate that
400+
# we're not unnecessarily re-validating already-valid models.
399401
m = MyModel(a=3, b="four")
400402
assert modelprop.validate(m) is m
401403
assert modelprop.validate({"a": 5, "b": "six"}) == MyModel(a=5, b="six")
402404
for invalid in [{"c": 5}, (4, "f"), None]:
403405
with pytest.raises(pydantic.ValidationError):
404406
modelprop.validate(invalid)
407+
# Check that an invalid model doesn't get re-validated. This is intended behaviour:
408+
# it is another test that we're not unnecessarily re-validating a model that
409+
# should already have been validated when it was created.
410+
# Creating models with `model_construct` intentionally allows invalid models:
411+
# if this is used downstream, the downstream code should accept responsibility!
412+
bad_m = MyModel.model_construct(a="not an int", b=6)
413+
assert modelprop.validate(bad_m) is bad_m
414+
with pytest.raises(pydantic.ValidationError):
415+
# Check that passing the same data in as a dict fails validation.
416+
modelprop.validate(bad_m.model_dump())
405417

406418
# Check again for an odd rootmodel
407419
rootmodelprop = example.properties["rootmodelprop"]
@@ -414,6 +426,11 @@ class BadIntModel(pydantic.BaseModel):
414426
for invalid in ["seven", {"root": None}, 14.5, pydantic.RootModel[int](root=0)]:
415427
with pytest.raises(pydantic.ValidationError):
416428
modelprop.validate(invalid)
429+
# Tty constructing a model with an invalid root value, skipping validation
430+
invalid_model = rootmodelprop.model.model_construct(invalid)
431+
# The RootModel gets re-validated, in contrast to the BaseModel above.
432+
with pytest.raises(pydantic.ValidationError):
433+
assert modelprop.validate(invalid_model) == invalid
417434

418435

419436
def test_readonly_metadata():

0 commit comments

Comments
 (0)