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

Nested allow_none=True implementation #122

Open
wants to merge 2 commits 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
10 changes: 9 additions & 1 deletion marshmallow_jsonschema/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def _from_nested_schema(self, obj, field):
self._nested_schema_classes.update(wrapped_nested._nested_schema_classes)

# and the schema is just a reference to the def
schema = {"type": "object", "$ref": "#/definitions/{}".format(name)}
schema = {"$ref": "#/definitions/{}".format(name)}

# NOTE: doubled up to maintain backwards compatibility
metadata = field.metadata.get("metadata", {})
Expand All @@ -252,6 +252,14 @@ def _from_nested_schema(self, obj, field):
continue
schema[md_key] = md_val

if field.allow_none:
schema = {
"anyOf": [
schema,
{"type": "null"}
]
}

if field.many:
schema = {
"type": "array" if field.required else ["array", "null"],
Expand Down
22 changes: 21 additions & 1 deletion tests/test_dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ class TestSchema(Schema):

nested_def = dumped["definitions"]["TestNamedNestedSchema"]
nested_dmp = dumped["definitions"]["TestSchema"]["properties"]["nested"]
assert nested_dmp["type"] == "object"
assert nested_def["properties"]["foo"]["format"] == "integer"


Expand Down Expand Up @@ -416,6 +415,27 @@ class TestSchema(Schema):
}


def test_allow_none_on_nested():
"""A Nested field with allow_none set to True should result in anyOf"""
class ChildSchema(Schema):
id = fields.Integer(required=True)

class TestSchema(Schema):
id = fields.Integer(required=True)
nested_fld = fields.Nested(ChildSchema, allow_none=True)

schema = TestSchema()

dumped = validate_and_dump(schema)

assert dumped["definitions"]["TestSchema"]["properties"]["nested_fld"] == {
"anyOf": [
{'$ref': '#/definitions/ChildSchema'},
{"type": "null"}
]
}


def test_dumps_iterable_enums():
mapping = {"a": 0, "b": 1, "c": 2}

Expand Down