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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

[1.10.X] Fix field regex with StrictStr type annotation #4538

Merged
merged 3 commits into from Sep 20, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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/4538-sisp.md
@@ -0,0 +1 @@
Fix field regex with `StrictStr` type annotation.
16 changes: 11 additions & 5 deletions pydantic/types.py
Expand Up @@ -403,16 +403,17 @@ class ConstrainedStr(str):
min_length: OptionalInt = None
max_length: OptionalInt = None
curtail_length: OptionalInt = None
regex: Optional[Pattern[str]] = None
regex: Optional[Union[str, Pattern[str]]] = None
strict = False

@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
regex = cls._regex()
Copy link
Member

Choose a reason for hiding this comment

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

you'll therefore still need an isinstance check here.

update_not_none(
field_schema,
minLength=cls.min_length,
maxLength=cls.max_length,
pattern=cls.regex and cls.regex.pattern,
pattern=regex and regex.pattern,
)

@classmethod
Expand All @@ -429,12 +430,17 @@ def validate(cls, value: Union[str]) -> Union[str]:
if cls.curtail_length and len(value) > cls.curtail_length:
value = value[: cls.curtail_length]

if cls.regex:
if not cls.regex.match(value):
raise errors.StrRegexError(pattern=cls.regex.pattern)
regex = cls._regex()
if regex:
if not regex.match(value):
Copy link
Member

Choose a reason for hiding this comment

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

I'm afraid this might be slow since the compiled regex might not be cached.

Better to do the following which I think should work in both cases

Suggested change
regex = cls._regex()
if regex:
if not regex.match(value):
if cls.regex:
if not re.match(cls.regex, value):

raise errors.StrRegexError(pattern=regex.pattern)

return value

@classmethod
def _regex(cls) -> Optional[Pattern[str]]:
return re.compile(cls.regex) if isinstance(cls.regex, str) else cls.regex


def constr(
*,
Expand Down
39 changes: 39 additions & 0 deletions tests/test_types.py
Expand Up @@ -1759,6 +1759,45 @@ class Model(BaseModel):
Model(u='1234567')


def test_strict_str_regex():
class Model(BaseModel):
u: StrictStr = Field(..., regex=r'^[0-9]+$')

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

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

with pytest.raises(ValidationError) as exc_info:
Model(u='abc')
assert exc_info.value.errors() == [
{
'loc': ('u',),
'msg': 'string does not match regex "^[0-9]+$"',
'type': 'value_error.str.regex',
'ctx': {'pattern': '^[0-9]+$'},
}
]


def test_string_regex():
class Model(BaseModel):
u: str = Field(..., regex=r'^[0-9]+$')

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

with pytest.raises(ValidationError) as exc_info:
Model(u='abc')
assert exc_info.value.errors() == [
{
'loc': ('u',),
'msg': 'string does not match regex "^[0-9]+$"',
'type': 'value_error.str.regex',
'ctx': {'pattern': '^[0-9]+$'},
}
]


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