Skip to content

Commit

Permalink
Fix field validation on Base64Bytes and Base64Str
Browse files Browse the repository at this point in the history
  • Loading branch information
LouisGobert committed Apr 16, 2024
1 parent ae71183 commit d3795cf
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
4 changes: 3 additions & 1 deletion pydantic/types.py
Expand Up @@ -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),
)

Expand Down
36 changes: 36 additions & 0 deletions tests/test_types.py
Expand Up @@ -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'),
[
Expand Down

0 comments on commit d3795cf

Please sign in to comment.