Skip to content

Commit

Permalink
Fix (#1079) crash when generating schema for field with UUID choices.
Browse files Browse the repository at this point in the history
The crash was fixed by replacing the JSON encoder used to hash elements
for enum deduplication with DRF JSON encoder which is capable of handling
type outside of the usual JSON standard types.
  • Loading branch information
phb-teleclinic committed Sep 21, 2023
1 parent 933f7b7 commit 1e8b172
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
3 changes: 2 additions & 1 deletion drf_spectacular/plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from rest_framework.fields import empty
from rest_framework.settings import api_settings
from rest_framework.test import APIRequestFactory
from rest_framework.utils.encoders import JSONEncoder
from rest_framework.utils.mediatypes import _MediaType
from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList
from uritemplate import URITemplate
Expand Down Expand Up @@ -839,7 +840,7 @@ def load_enum_name_overrides():


def list_hash(lst):
return hashlib.sha256(json.dumps(list(lst), sort_keys=True).encode()).hexdigest()
return hashlib.sha256(json.dumps(list(lst), sort_keys=True, cls=JSONEncoder).encode()).hexdigest()


def anchor_pattern(pattern: str) -> str:
Expand Down
26 changes: 26 additions & 0 deletions tests/test_postprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,3 +314,29 @@ def get(self, request):
'items': {'$ref': '#/components/schemas/QualityLevelsEnum'},
'readOnly': True
}


def test_uuid_choices(no_warnings):

import uuid

class XSerializer(serializers.Serializer):
foo = serializers.ChoiceField(
choices=[
(uuid.UUID('93d7527f-de3c-4a76-9cc2-5578675630d4'), 'baz'),
(uuid.UUID('47a4b873-409e-4e43-81d5-fafc3faeb849'), 'bar')
]
)

class XAPIView(APIView):
@extend_schema(responses=XSerializer)
def get(self, request):
pass # pragma: no cover

schema = generate_schema('x', view=XAPIView)

assert 'FooEnum' in schema['components']['schemas']
assert schema['components']['schemas']['FooEnum']['enum'] == [
uuid.UUID('93d7527f-de3c-4a76-9cc2-5578675630d4'),
uuid.UUID('47a4b873-409e-4e43-81d5-fafc3faeb849')
]

0 comments on commit 1e8b172

Please sign in to comment.