Skip to content

Commit

Permalink
prevent pagination on error responses. #277
Browse files Browse the repository at this point in the history
although it is a deviation from the main behaviour,
paginating error responses makes little sense in
virtually all realistic scenarios.
  • Loading branch information
tfranzel committed Mar 19, 2021
1 parent 9bd14f2 commit ff0a892
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
8 changes: 7 additions & 1 deletion drf_spectacular/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1027,6 +1027,8 @@ def _get_response_for_code(self, serializer, status_code, media_types=None):
elif isinstance(serializer, dict):
# bypass processing and use given schema directly
schema = serializer
# prevent invalid dict case in _is_list_view() as this not a status_code dict.
serializer = None
else:
warn(
f'could not resolve "{serializer}" for {self.method} {self.path}. Expected either '
Expand All @@ -1036,7 +1038,11 @@ def _get_response_for_code(self, serializer, status_code, media_types=None):
schema = build_basic_type(OpenApiTypes.OBJECT)
schema['description'] = _('Unspecified response body')

if self._is_list_view(serializer) and not get_override(serializer, 'many') is False:
if (
self._is_list_view(serializer)
and get_override(serializer, 'many') is not False
and '200' <= status_code < '300'
):
schema = build_array_type(schema)
paginator = self._get_paginator()

Expand Down
25 changes: 25 additions & 0 deletions tests/test_regressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1721,3 +1721,28 @@ def view_func(request, format=None):

schema = generate_schema('/api/v1/x/', view_function=view_func)
assert '/x/' in schema['paths']


def test_list_and_pagination_on_non_2XX_schemas(no_warnings):
@extend_schema_view(
list=extend_schema(responses={
200: SimpleSerializer,
400: {'type': 'object', 'properties': {'code': {'type': 'string'}}},
403: OpenApiTypes.OBJECT
})
)
class XViewset(mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = SimpleSerializer
queryset = SimpleModel.objects.none()
pagination_class = pagination.LimitOffsetPagination

schema = generate_schema('x', XViewset)
assert get_response_schema(schema['paths']['/x/']['get']) == {
'$ref': '#/components/schemas/PaginatedSimpleList'
}
assert get_response_schema(schema['paths']['/x/']['get'], '400') == {
'type': 'object', 'properties': {'code': {'type': 'string'}}
}
assert get_response_schema(schema['paths']['/x/']['get'], '403') == {
'type': 'object', 'additionalProperties': {}
}

0 comments on commit ff0a892

Please sign in to comment.