Skip to content

Commit

Permalink
improve component discard logic #395
Browse files Browse the repository at this point in the history
  • Loading branch information
tfranzel committed May 31, 2021
1 parent 6eaf796 commit f824bf1
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
6 changes: 5 additions & 1 deletion drf_spectacular/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1184,7 +1184,11 @@ def resolve_serializer(self, serializer, direction) -> ResolvedComponent:
# components with empty schemas serve no purpose
not component.schema
# concrete component without properties are likely only transactional so discard
or (component.schema.get('type') == 'object' and not component.schema.get('properties'))
or (
component.schema.get('type') == 'object'
and not component.schema.get('properties')
and 'additionalProperties' not in component.schema
)
)

if discard_component:
Expand Down
19 changes: 13 additions & 6 deletions tests/test_regressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1870,11 +1870,15 @@ def test_yaml_encoder_parity(no_warnings, value):
assert OpenApiYamlRenderer().render(value)


@pytest.mark.parametrize('comp_schema', [
{'type': 'number'},
{'type': 'array', 'items': {'type': 'number'}},
@pytest.mark.parametrize(['comp_schema', 'discarded'], [
({'type': 'object'}, True),
({'type': 'object', 'properties': {}}, True),
({'type': 'object', 'additionalProperties': {}}, False),
({'type': 'object', 'additionalProperties': {'type': 'number'}}, False),
({'type': 'number'}, False),
({'type': 'array', 'items': {'type': 'number'}}, False),
])
def test_serializer_extension_with_non_object_schema(no_warnings, comp_schema):
def test_serializer_extension_with_non_object_schema(no_warnings, comp_schema, discarded):
class XSerializer(serializers.Serializer):
field = serializers.CharField()

Expand All @@ -1892,8 +1896,11 @@ def post(self, request):
schema = generate_schema('x', view=XAPIView)

operation = schema['paths']['/x']['post']
assert get_request_schema(operation)['$ref'] == '#/components/schemas/X'
assert schema['components']['schemas']['X'] == comp_schema
if discarded:
assert 'requestBody' not in operation
else:
assert get_request_schema(operation)['$ref'] == '#/components/schemas/X'
assert schema['components']['schemas']['X'] == comp_schema


def test_response_header_with_serializer_component(no_warnings):
Expand Down

0 comments on commit f824bf1

Please sign in to comment.