Skip to content

Commit

Permalink
fix(schema): add basic support of Pattern type in schema generation
Browse files Browse the repository at this point in the history
closes #1767
  • Loading branch information
PrettyWood committed Jul 27, 2020
1 parent e985857 commit 03a1517
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
1 change: 1 addition & 0 deletions changes/1767-PrettyWood.md
@@ -0,0 +1 @@
add basic support of Pattern type in schema generation
7 changes: 7 additions & 0 deletions pydantic/schema.py
Expand Up @@ -14,6 +14,7 @@
Iterable,
List,
Optional,
Pattern,
Sequence,
Set,
Tuple,
Expand Down Expand Up @@ -698,6 +699,12 @@ def field_singleton_schema( # noqa: C901 (ignore complexity)
field_type = literal_value.__class__
f_schema['const'] = literal_value

# `typing.Pattern` is not a valid type and should be considered as a string.
# Note: We should probably add `pattern: <the regex>` in the schema
# but it requires `.schema()` to be an instance method instead of a class one.
if field_type is Pattern:
field_type = str

if lenient_issubclass(field_type, Enum):
enum_name = normalize_name(field_type.__name__)
f_schema = {'$ref': ref_prefix + enum_name}
Expand Down
7 changes: 7 additions & 0 deletions tests/test_types.py
Expand Up @@ -2055,6 +2055,13 @@ class Foobar(BaseModel):
f2 = Foobar(pattern=p)
assert f2.pattern is p

assert Foobar.schema() == {
'type': 'object',
'title': 'Foobar',
'properties': {'pattern': {'type': 'string', 'title': 'Pattern'}},
'required': ['pattern'],
}


def test_pattern_error():
class Foobar(BaseModel):
Expand Down

0 comments on commit 03a1517

Please sign in to comment.