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
…1768)

closes #1767
  • Loading branch information
PrettyWood committed Oct 8, 2020
1 parent a2fc01a commit 55e78cc
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 1 deletion.
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 docs/build/schema_mapping.py
Expand Up @@ -145,6 +145,13 @@
'JSON Schema Validation',
''
],
[
'Pattern',
'string',
{'format': 'regex'},
'JSON Schema Validation',
''
],
[
'bytes',
'string',
Expand Down
5 changes: 4 additions & 1 deletion pydantic/schema.py
Expand Up @@ -14,6 +14,7 @@
Iterable,
List,
Optional,
Pattern,
Sequence,
Set,
Tuple,
Expand Down Expand Up @@ -618,6 +619,7 @@ def field_singleton_sub_fields_schema(
(IPv6Interface, {'type': 'string', 'format': 'ipv6interface'}),
(IPv4Address, {'type': 'string', 'format': 'ipv4'}),
(IPv6Address, {'type': 'string', 'format': 'ipv6'}),
(Pattern, {'type': 'string', 'format': 'regex'}),
(str, {'type': 'string'}),
(bytes, {'type': 'string', 'format': 'binary'}),
(bool, {'type': 'boolean'}),
Expand All @@ -643,7 +645,8 @@ def add_field_type_to_schema(field_type: Any, schema: Dict[str, Any]) -> None:
and then modifies the given `schema` with the information from that type.
"""
for type_, t_schema in field_class_to_schema:
if issubclass(field_type, type_):
# Fallback for `typing.Pattern` as it is not a valid class
if lenient_issubclass(field_type, type_) or field_type is type_ is Pattern:
schema.update(t_schema)
break

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', 'format': 'regex', 'title': 'Pattern'}},
'required': ['pattern'],
}


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

0 comments on commit 55e78cc

Please sign in to comment.