equinor / everest-models

GNU General Public License v3.0
2 stars 5 forks source link

All catching parent field validator overrides/ignores child's field validator #3

Closed sregales-TNO closed 6 months ago

sregales-TNO commented 6 months ago

https://github.com/equinor/everest-models/blob/b0539dc26a0f83025c3e34793b6701515b8abf0f/src/everest_models/jobs/shared/models/base_config/base.py#L24

the following validator checks if there are any lingering ... values in coming data. This value is produced when data is generated by a schema initializer. a field with the is value implies that the field is required and does not have a default.

The nice thing about this validator is that checks all fields @field_validator("*") and does this validation for all the fields of all models that inherit from our ModelConfig, But this pro is also its con, it overrides/ignores all child field validator since they have already been executed by parent.

The solution is to change it from a field_validator to a model_validator a model can run multiple model_validator thus our override/ignore problem can be avoided.

Example Code Snippet Solution:

 @model_validator(mode="before")
    @classmethod
    def check_for_ellipses(cls, data: Any) -> Any:
        def any_ellipses(data: Any):
            return any(
                any_ellipses(value) if isinstance(value, dict) else value == "..."
                for value in data.values()
            )

        if any_ellipses(data):
            raise ValueError(
                "Please replace any and/or all `...`, these field are required"
            )
        return data