Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: strictbytes-max-length #4383

Merged
merged 3 commits into from Aug 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add a test with a byte (to make strictness pass) with

  • short length to raise ValidationError
  • long length to pass
    ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, What do you think?

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