Skip to content

Commit

Permalink
Fix nullable nested schemas with metadata..
Browse files Browse the repository at this point in the history
#955

Applied the same `allOf` logic seen used in 3.1 (See
#904)
  • Loading branch information
luhn committed Nov 23, 2024
1 parent 209a7d8 commit 7975a12
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/apispec/ext/marshmallow/field_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,11 @@ def field2nullable(self, field: marshmallow.fields.Field, ret) -> dict:
{"type": "object", "nullable": True},
{"$ref": ret.pop("$ref")},
]
elif "allOf" in ret:
attributes["anyOf"] = [
*ret.pop("allOf"),
{"type": "object", "nullable": True},
]
else:
attributes["nullable"] = True
else:
Expand Down
36 changes: 36 additions & 0 deletions tests/test_ext_marshmallow_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,42 @@ class Child(Schema):
}


@pytest.mark.parametrize("spec_fixture", ("2.0", "3.0.0", "3.1.0"), indirect=True)
def test_nested_nullable_with_metadata(spec_fixture):
# Regression test for https://github.com/marshmallow-code/apispec/issues/955
class Child(Schema):
name = fields.Str()

field = fields.Nested(
Child,
allow_none=True,
metadata={"description": "foo"},
)
res = spec_fixture.openapi.field2property(field)
version = spec_fixture.openapi.openapi_version
if version.major < 3:
assert res == {
"allOf": [
{"$ref": "#/definitions/Child"},
],
"x-nullable": True,
"description": "foo",
}
elif version.major == 3 and version.minor < 1:
assert res == {
"anyOf": [
{"$ref": "#/components/schemas/Child"},
{"type": "object", "nullable": True},
],
"description": "foo",
}
else:
assert res == {
"anyOf": [{"$ref": "#/components/schemas/Child"}, {"type": "null"}],
"description": "foo",
}


@pytest.mark.parametrize("spec_fixture", ("2.0", "3.0.0", "3.1.0"), indirect=True)
def test_nullable_pluck(spec_fixture):
class Example(Schema):
Expand Down

0 comments on commit 7975a12

Please sign in to comment.