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 StrictStr does not raise ValidationError when max_length is present in Field #4388

Merged
merged 1 commit into from Aug 19, 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/4388-hramezani.md
@@ -0,0 +1 @@
Fix `StrictStr` does not raise `ValidationError` when `max_length` is present in `Field`
12 changes: 9 additions & 3 deletions pydantic/schema.py
Expand Up @@ -54,10 +54,10 @@
ConstrainedInt,
ConstrainedList,
ConstrainedSet,
ConstrainedStr,
SecretBytes,
SecretStr,
StrictBytes,
StrictStr,
conbytes,
condecimal,
confloat,
Expand Down Expand Up @@ -1083,9 +1083,15 @@ def go(type_: Any) -> Type[Any]:
def constraint_func(**kw: Any) -> Type[Any]:
return type(type_.__name__, (type_,), kw)

elif issubclass(type_, str) and not issubclass(type_, (EmailStr, AnyUrl, ConstrainedStr)):
elif issubclass(type_, str) and not issubclass(type_, (EmailStr, AnyUrl)):
attrs = ('max_length', 'min_length', 'regex')
constraint_func = constr
if issubclass(type_, StrictStr):

def constraint_func(**kw: Any) -> Type[Any]:
return type(type_.__name__, (type_,), kw)

else:
constraint_func = constr
elif issubclass(type_, bytes):
attrs = ('max_length', 'min_length', 'regex')
if issubclass(type_, StrictBytes):
Expand Down
13 changes: 13 additions & 0 deletions tests/test_types.py
Expand Up @@ -1690,6 +1690,19 @@ class Model(BaseModel):
assert m.v == 'foobar'


def test_strict_str_max_length():
class Model(BaseModel):
u: StrictStr = Field(..., max_length=5)

assert Model(u='foo').u == 'foo'

with pytest.raises(ValidationError, match='str type expected'):
Model(u=123)

with pytest.raises(ValidationError, match='ensure this value has at most 5 characters'):
Model(u='1234567')


def test_strict_bool():
class Model(BaseModel):
v: StrictBool
Expand Down