Skip to content

Commit

Permalink
add OAS 3.1 null translation case #1133
Browse files Browse the repository at this point in the history
  • Loading branch information
tfranzel committed Dec 26, 2023
1 parent d78a21c commit c401be4
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
2 changes: 2 additions & 0 deletions drf_spectacular/plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
35 changes: 35 additions & 0 deletions tests/test_regressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
},
}

0 comments on commit c401be4

Please sign in to comment.