Skip to content

Commit

Permalink
Fix StrictStr does not raise ValidationError when max_length is…
Browse files Browse the repository at this point in the history
… present in `Field`
  • Loading branch information
hramezani committed Aug 17, 2022
1 parent 67b653f commit b5335a7
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
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

0 comments on commit b5335a7

Please sign in to comment.