Skip to content

Commit

Permalink
fix OAS3.1 validator omission #1302
Browse files Browse the repository at this point in the history
  • Loading branch information
tfranzel committed Oct 1, 2024
1 parent 96a4f38 commit 8156c0b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
4 changes: 4 additions & 0 deletions drf_spectacular/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1069,6 +1069,10 @@ def _map_basic_serializer(self, serializer, direction):
def _insert_field_validators(self, field, schema):
schema_type = schema.get('type')

# OAS 3.1 special case - extract the main type
if isinstance(schema_type, list):
schema_type = [t for t in schema_type if t != 'null'][0]

def update_constraint(schema, key, function, value, *, exclusive=False):
if callable(value):
value = value()
Expand Down
23 changes: 22 additions & 1 deletion tests/test_oas31.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from unittest import mock

from rest_framework import serializers
from rest_framework import serializers, viewsets
from rest_framework.views import APIView

from drf_spectacular.utils import extend_schema
from tests import generate_schema
from tests.models import SimpleModel


@mock.patch('drf_spectacular.settings.spectacular_settings.OAS_VERSION', '3.1.0')
Expand Down Expand Up @@ -68,3 +69,23 @@ def get(self, request):
'required': ['foo'],
'type': 'object'
}


@mock.patch('drf_spectacular.settings.spectacular_settings.OAS_VERSION', '3.1.0')
def test_validator_addition_for_oas31(no_warnings):

class XSerializer(serializers.Serializer):
field = serializers.CharField(allow_blank=True, allow_null=True, max_length=40, required=False)

class XViewset(viewsets.ModelViewSet):
serializer_class = XSerializer
queryset = SimpleModel.objects.none()

schema = generate_schema('x', XViewset)

assert schema['components']['schemas']['X'] == {
'properties': {
'field': {'maxLength': 40, 'type': ['string', 'null']}
},
'type': 'object'
}

0 comments on commit 8156c0b

Please sign in to comment.