fix: strictbytes-max-length (#4383)

* fix: strictbytes-max-length

* fix: apply feedbacks

* Update changes/4380-JeanArhancet.md

Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com>

Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com>
This commit is contained in:
Jean
2022-08-16 23:41:17 +02:00
committed by GitHub
parent 2f883b9509
commit 67b653f19a
3 changed files with 21 additions and 1 deletions
+1
View File
@@ -0,0 +1 @@
Fix `StrictBytes` does not raise `ValidationError` when `max_length` is present in `Field`
+8 -1
View File
@@ -57,6 +57,7 @@ from .types import (
ConstrainedStr,
SecretBytes,
SecretStr,
StrictBytes,
conbytes,
condecimal,
confloat,
@@ -1087,7 +1088,13 @@ def get_annotation_with_constraints(annotation: Any, field_info: FieldInfo) -> T
constraint_func = constr
elif issubclass(type_, bytes):
attrs = ('max_length', 'min_length', 'regex')
constraint_func = conbytes
if issubclass(type_, StrictBytes):
def constraint_func(**kw: Any) -> Type[Any]:
return type(type_.__name__, (type_,), kw)
else:
constraint_func = conbytes
elif issubclass(type_, numeric_types) and not issubclass(
type_,
(
+12
View File
@@ -1634,6 +1634,18 @@ def test_strict_bytes():
Model(v=0.42)
def test_strict_bytes_max_length():
class Model(BaseModel):
u: StrictBytes = Field(..., max_length=5)
assert Model(u=b'foo').u == b'foo'
with pytest.raises(ValidationError, match='byte type expected'):
Model(u=123)
with pytest.raises(ValidationError, match='ensure this value has at most 5 characters'):
Model(u=b'1234567')
def test_strict_bytes_subclass():
class MyStrictBytes(StrictBytes):
pass