From 881df8bde7bfc90e3a349c420d0b0b7d46237d59 Mon Sep 17 00:00:00 2001 From: Selim Belhaouane Date: Thu, 30 Apr 2020 14:05:42 -0400 Subject: [PATCH] move const validator to post validators. fixes #1410 (#1446) --- changes/1410-selimb.md | 1 + docs/usage/schema.md | 2 +- pydantic/fields.py | 4 ++-- tests/test_main.py | 9 +++++++++ 4 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 changes/1410-selimb.md diff --git a/changes/1410-selimb.md b/changes/1410-selimb.md new file mode 100644 index 0000000000..3768cf770c --- /dev/null +++ b/changes/1410-selimb.md @@ -0,0 +1 @@ +Move `const` validator to post-validators so it validates the parsed value diff --git a/docs/usage/schema.md b/docs/usage/schema.md index 02ba8e0c49..028e7731f2 100644 --- a/docs/usage/schema.md +++ b/docs/usage/schema.md @@ -48,7 +48,7 @@ It has the following arguments: * `title`: if omitted, `field_name.title()` is used * `description`: if omitted and the annotation is a sub-model, the docstring of the sub-model will be used -* `const`: this argument *must* have be the same as the field's default value if present +* `const`: this argument *must* be the same as the field's default value if present. * `gt`: for numeric values (``int``, `float`, `Decimal`), adds a validation of "greater than" and an annotation of `exclusiveMinimum` to the JSON Schema * `ge`: for numeric values, this adds a validation of "greater than or equal" and an annotation of `minimum` to the diff --git a/pydantic/fields.py b/pydantic/fields.py index c444587122..c49ad7f047 100644 --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -510,11 +510,11 @@ def populate_validators(self) -> None: ) self.validators = prep_validators(v_funcs) - # Add const validator self.pre_validators = [] self.post_validators = [] + if self.field_info and self.field_info.const: - self.pre_validators = [make_generic_validator(constant_validator)] + self.post_validators.append(make_generic_validator(constant_validator)) if class_validators_: self.pre_validators += prep_validators(v.func for v in class_validators_ if not v.each_item and v.pre) diff --git a/tests/test_main.py b/tests/test_main.py index 71371d3bcc..fdbc9ea3f1 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -383,6 +383,15 @@ class Model(BaseModel): assert m.a == 3 +def test_const_validates_after_type_validators(): + # issue #1410 + class Model(BaseModel): + a: int = Field(3, const=True) + + m = Model(a='3') + assert m.a == 3 + + def test_const_with_wrong_value(): class Model(BaseModel): a: int = Field(3, const=True)