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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow callable defaults and verify serializability #181

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions marshmallow_jsonschema/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import datetime
import decimal
import json
import uuid
from enum import Enum
from inspect import isclass
Expand Down Expand Up @@ -195,8 +196,13 @@ def _from_python_type(self, obj, field, pytype) -> typing.Dict[str, typing.Any]:
if field.dump_only:
json_schema["readOnly"] = True

if field.default is not missing and not callable(field.default):
json_schema["default"] = field.default
if field.default is not missing:
if (not callable(field.default) and self._is_serializable(field.default)):
json_schema["default"] = field.default
else:
default_value = field.default()
if self._is_serializable(default_value):
json_schema["default"] = default_value

if ALLOW_ENUMS and isinstance(field, EnumField):
json_schema["enum"] = self._get_enum_values(field)
Expand Down Expand Up @@ -225,6 +231,13 @@ def _from_python_type(self, obj, field, pytype) -> typing.Dict[str, typing.Any]:
)
return json_schema

def _is_serializable(self, value):
try:
json.dumps(value)
return True
except TypeError:
return False

def _get_enum_values(self, field) -> typing.List[str]:
assert ALLOW_ENUMS and isinstance(field, EnumField)

Expand Down
11 changes: 11 additions & 0 deletions tests/test_dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,17 @@ class TestSchema(Schema):
props = dumped["definitions"]["TestSchema"]["properties"]
assert "default" not in props["uid"]

def test_default_callable_serialized():
class TestSchema(Schema):
uid = fields.UUID(default=lambda: str(uuid.uuid4()))

schema = TestSchema()

dumped = validate_and_dump(schema)

props = dumped["definitions"]["TestSchema"]["properties"]
assert "default" in props["uid"]


def test_uuid():
schema = UserSchema()
Expand Down