From d3795cf3b16a9703626143e7c070e74bfb9fd95e Mon Sep 17 00:00:00 2001 From: LouisGobert Date: Tue, 16 Apr 2024 22:51:45 +0200 Subject: [PATCH] Fix field validation on Base64Bytes and Base64Str --- pydantic/types.py | 4 +++- tests/test_types.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/pydantic/types.py b/pydantic/types.py index f1025a5102..237c5be600 100644 --- a/pydantic/types.py +++ b/pydantic/types.py @@ -2344,9 +2344,11 @@ def __get_pydantic_json_schema__( return field_schema def __get_pydantic_core_schema__(self, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: + base_schema: Any = handler(source) + del base_schema['type'] return core_schema.with_info_after_validator_function( function=self.decode, - schema=core_schema.bytes_schema(), + schema=core_schema.bytes_schema(**base_schema), serialization=core_schema.plain_serializer_function_ser_schema(function=self.encode), ) diff --git a/tests/test_types.py b/tests/test_types.py index da1903b575..78bef9950c 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -5508,6 +5508,42 @@ class Model(BaseModel): } +def test_base64_with_valid_min_length() -> None: + class Model(BaseModel): + base64_value: Base64Bytes = Field(min_length=3) + + value = b'Zm9v' + m = Model.model_construct(base64_value=value) + assert m.base64_value == value + assert Model.model_json_schema() == { + 'properties': { + 'base64_value': { + 'format': 'base64', + 'minLength': 3, + 'title': 'Base64 Value', + 'type': 'string', + } + }, + 'required': ['base64_value'], + 'title': 'Model', + 'type': 'object', + } + + +def test_base64_with_invalid_min_length() -> None: + """Check that an error is raised when the length of the base64 + value is less or more than the min_length and max_length""" + + class Model(BaseModel): + base64_value: Base64Bytes = Field(min_length=3, max_length=5) + + with pytest.raises(ValidationError): + Model(**{'base64_value': b''}) + + with pytest.raises(ValidationError): + Model(**{'base64_value': b'123456'}) + + @pytest.mark.parametrize( ('field_type', 'input_data'), [