Skip to content
This repository was archived by the owner on Aug 19, 2023. It is now read-only.

Commit ab95156

Browse files
authored
Handle custom formats with fastjsonschema correctly (#158)
1 parent 00b9db2 commit ab95156

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

dataclasses_jsonschema/__init__.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
from .field_types import ( # noqa: F401
2222
FieldEncoder, DateFieldEncoder, DateTimeFieldEncoder, UuidField, DecimalField,
23-
IPv4AddressField, IPv6AddressField, DateTimeField, UUID_REGEX
23+
IPv4AddressField, IPv6AddressField, DateTimeField
2424
)
2525
from .type_defs import JsonDict, SchemaType, JsonSchemaMeta, _NULL_TYPE, NULL # noqa: F401
2626
from .type_hints import get_class_type_hints
@@ -474,8 +474,14 @@ def _validate(cls, data: JsonDict, validate_enums: bool = True):
474474
# TODO: Support validating with other schema types
475475
schema_validator = cls.__compiled_schema.get(SchemaOptions(DEFAULT_SCHEMA_TYPE, validate_enums))
476476
if schema_validator is None:
477+
formats = {}
478+
for encoder in cls._field_encoders.values():
479+
schema = encoder.json_schema
480+
if 'pattern' in schema and 'format' in schema:
481+
formats[schema['format']] = schema['pattern']
482+
477483
schema_validator = fastjsonschema.compile(
478-
cls.json_schema(validate_enums=validate_enums), formats={'uuid': UUID_REGEX}
484+
cls.json_schema(validate_enums=validate_enums), formats=formats
479485
)
480486
cls.__compiled_schema[SchemaOptions(DEFAULT_SCHEMA_TYPE, validate_enums)] = schema_validator
481487
schema_validator(data)

tests/test_core.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -978,3 +978,27 @@ class Pet(JsonSchemaMixin):
978978
schema = Pet.json_schema(embeddable=True, schema_type=SchemaType.OPENAPI_3)
979979
assert schema['Pet']['x-module-name'] == 'tests.test_core'
980980
assert schema['Pet']['properties']['type']['x-module-name'] == 'tests.test_core'
981+
982+
983+
def test_custom_format():
984+
Slug = NewType('Slug', str)
985+
986+
class SlugField(FieldEncoder[Slug, str]):
987+
988+
@property
989+
def json_schema(self) -> JsonDict:
990+
return {
991+
'type': 'string',
992+
'format': 'slug',
993+
'pattern': r'^[a-z0-9\-]+$',
994+
}
995+
996+
JsonSchemaMixin.register_field_encoders({Slug: SlugField()})
997+
998+
@dataclass
999+
class Post(JsonSchemaMixin):
1000+
slug: Slug
1001+
content: str
1002+
1003+
post = Post.from_dict({"content": "Lorem ipsum dolor ...", "slug": "some-post"})
1004+
assert post.slug == Slug("some-post")

0 commit comments

Comments
 (0)