Skip to content

Commit

Permalink
fix: strictbytes-max-length (#4383)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
JeanArhancet and hramezani committed Aug 16, 2022
1 parent 2f883b9 commit 67b653f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
1 change: 1 addition & 0 deletions changes/4380-JeanArhancet.md
@@ -0,0 +1 @@
Fix `StrictBytes` does not raise `ValidationError` when `max_length` is present in `Field`
9 changes: 8 additions & 1 deletion pydantic/schema.py
Expand Up @@ -57,6 +57,7 @@
ConstrainedStr,
SecretBytes,
SecretStr,
StrictBytes,
conbytes,
condecimal,
confloat,
Expand Down Expand Up @@ -1087,7 +1088,13 @@ def constraint_func(**kw: Any) -> Type[Any]:
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_,
(
Expand Down
12 changes: 12 additions & 0 deletions tests/test_types.py
Expand Up @@ -1634,6 +1634,18 @@ class Model(BaseModel):
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
Expand Down

0 comments on commit 67b653f

Please sign in to comment.