Skip to content

Commit

Permalink
Add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jag-k committed Mar 25, 2024
1 parent 376b406 commit 1e06ec3
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions tests/test_types.py
Expand Up @@ -3936,6 +3936,45 @@ class Foobar(BaseModel):
}


@pytest.mark.parametrize(
'use_field',
[pytest.param(True, id='Field'), pytest.param(False, id='constr')],
)
def test_compiled_pattern_in_field(use_field):
"""
https://github.com/pydantic/pydantic/issues/9052
https://github.com/pydantic/pydantic/pull/9053
"""
pattern_value = r'^whatev.r\d$'
field_pattern = re.compile(pattern_value)

if use_field:

class Foobar(BaseModel):
str_regex: str = Field(..., pattern=field_pattern)
else:

class Foobar(BaseModel):
str_regex: constr(pattern=field_pattern) = ...

matching_value = 'whatever1'
f = Foobar(str_regex=matching_value)
assert f.str_regex == matching_value

with pytest.raises(
ValidationError,
match=re.escape("String should match pattern '" + pattern_value + "'"),
):
Foobar(str_regex=' whatever1')

assert Foobar.model_json_schema() == {
'type': 'object',
'title': 'Foobar',
'properties': {'str_regex': {'pattern': pattern_value, 'title': 'Str Regex', 'type': 'string'}},
'required': ['str_regex'],
}


def test_pattern_with_invalid_param():
with pytest.raises(
PydanticSchemaGenerationError,
Expand Down

0 comments on commit 1e06ec3

Please sign in to comment.