From c401be447d41f6e98418f6395195c1048cadb5d5 Mon Sep 17 00:00:00 2001 From: "T. Franzel" Date: Tue, 26 Dec 2023 15:33:42 +0100 Subject: [PATCH] add OAS 3.1 null translation case #1133 --- drf_spectacular/plumbing.py | 2 ++ tests/test_regressions.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/drf_spectacular/plumbing.py b/drf_spectacular/plumbing.py index c5a6a03b..f6c8d5c3 100644 --- a/drf_spectacular/plumbing.py +++ b/drf_spectacular/plumbing.py @@ -535,6 +535,8 @@ def append_meta(schema: _SchemaType, meta: _SchemaType) -> _SchemaType: schema = {'oneOf': [schema, {'type': 'null'}]} elif len(schema) == 1 and 'oneOf' in schema: schema['oneOf'].append({'type': 'null'}) + elif not schema and not meta: + schema = {'oneOf': [{}, {'type': 'null'}]} else: assert False, 'Invalid nullable case' # pragma: no cover diff --git a/tests/test_regressions.py b/tests/test_regressions.py index 478c721e..a8188537 100644 --- a/tests/test_regressions.py +++ b/tests/test_regressions.py @@ -3260,3 +3260,38 @@ def view_func(request, format=None): assert get_request_schema(schema['paths']['/x/']['post']) == { '$ref': '#/components/schemas/Simple' } + + +@mock.patch('drf_spectacular.settings.spectacular_settings.OAS_VERSION', '3.1.0') +def test_basic_oas_3_1_nullable_cases(no_warnings, django_transforms): + class M14(models.Model): + field_json = models.JSONField(null=True) # case 1 + + class XSerializer(serializers.ModelSerializer): + + field_method_hint = serializers.SerializerMethodField() + + def get_field_method_hint(self, obj) -> typing.Union[int, str, None]: # case 2 + pass # pragma: no cover + + class Meta: + fields = '__all__' + model = M14 + + class XViewset(viewsets.ReadOnlyModelViewSet): + serializer_class = XSerializer + queryset = M14.objects.none() + + schema = generate_schema('m2', XViewset) + assert schema['components']['schemas']['X']['properties'] == { + 'id': {'readOnly': True, 'type': 'integer'}, + 'field_json': {'oneOf': [{}, {'type': 'null'}]}, + 'field_method_hint': { + 'oneOf': [ + {'type': 'integer'}, + {'type': 'string'}, + {'type': 'null'} + ], + 'readOnly': True + }, + }