Skip to content

Commit

Permalink
Fix discarded falsy examples values #1049
Browse files Browse the repository at this point in the history
  • Loading branch information
tfranzel committed Aug 8, 2023
1 parent 388da8d commit afe8b3b
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
3 changes: 2 additions & 1 deletion drf_spectacular/plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from django.utils.translation import gettext_lazy as _
from rest_framework import exceptions, fields, mixins, serializers, versioning
from rest_framework.compat import unicode_http_header
from rest_framework.fields import empty
from rest_framework.settings import api_settings
from rest_framework.test import APIRequestFactory
from rest_framework.utils.mediatypes import _MediaType
Expand Down Expand Up @@ -322,7 +323,7 @@ def build_examples_list(examples):
for example in examples:
normalized_name = inflection.camelize(example.name.replace(' ', '_'))
sub_schema = {}
if example.value:
if example.value is not empty:
sub_schema['value'] = example.value
if example.external_value:
sub_schema['externalValue'] = example.external_value
Expand Down
2 changes: 1 addition & 1 deletion drf_spectacular/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ class OpenApiExample(OpenApiSchemaBase):
def __init__(
self,
name: str,
value: Any = None,
value: Any = empty,
external_value: str = '',
summary: _StrOrPromise = '',
description: _StrOrPromise = '',
Expand Down
28 changes: 28 additions & 0 deletions tests/test_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,31 @@ class XListView(generics.ListAPIView):
'schema': {'$ref': '#/components/schemas/Simple'},
'examples': {'AnExample': {'value': {'id': 3}, 'summary': 'an example'}}
}


def test_examples_with_falsy_values(no_warnings):
@extend_schema(
responses=OpenApiResponse(
description='something',
response=OpenApiTypes.JSON_PTR,
examples=[
OpenApiExample('one', value=1),
OpenApiExample('empty-list', value=[]),
OpenApiExample('false', value=False),
OpenApiExample('zero', value=0),
OpenApiExample('empty'),
],
),
)
class XListView(generics.ListAPIView):
model = SimpleModel
serializer_class = SimpleSerializer

schema = generate_schema('/x/', view=XListView)
assert schema['paths']['/x/']['get']['responses']['200']['content']['application/json']['examples'] == {
'One': {'summary': 'one', 'value': 1},
'Empty-list': {'summary': 'empty-list', 'value': []},
'False': {'summary': 'false', 'value': False},
'Zero': {'summary': 'zero', 'value': 0},
'Empty': {'summary': 'empty'},
}

0 comments on commit afe8b3b

Please sign in to comment.