From 0fd72f17ee18506c02b4c0f0e4af368e3bedac3e Mon Sep 17 00:00:00 2001 From: Guilherme Munarolo Date: Thu, 10 Oct 2019 03:50:20 -0300 Subject: [PATCH] Fixed crash deleting required schema parameter key on PATCH requests. (#6944) Closes #6941 --- rest_framework/schemas/openapi.py | 4 ++-- tests/schemas/test_openapi.py | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py index ac846bf80..09a5598f5 100644 --- a/rest_framework/schemas/openapi.py +++ b/rest_framework/schemas/openapi.py @@ -387,7 +387,7 @@ class AutoSchema(ViewInspector): result = { 'properties': properties } - if len(required) > 0: + if required: result['required'] = required return result @@ -463,7 +463,7 @@ class AutoSchema(ViewInspector): content = self._map_serializer(serializer) # No required fields for PATCH if method == 'PATCH': - del content['required'] + content.pop('required', None) # No read_only fields for request. for name, schema in content['properties'].copy().items(): if 'readOnly' in schema: diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py index d9375585b..e1d29f6fe 100644 --- a/tests/schemas/test_openapi.py +++ b/tests/schemas/test_openapi.py @@ -169,6 +169,31 @@ class TestOperationIntrospection(TestCase): for response in inspector._get_responses(path, method).values(): assert 'required' not in response['content']['application/json']['schema'] + def test_empty_required_with_patch_method(self): + path = '/' + method = 'PATCH' + + class Serializer(serializers.Serializer): + read_only = serializers.CharField(read_only=True) + write_only = serializers.CharField(write_only=True, required=False) + + class View(generics.GenericAPIView): + serializer_class = Serializer + + view = create_view( + View, + method, + create_request(path) + ) + inspector = AutoSchema() + inspector.view = view + + request_body = inspector._get_request_body(path, method) + # there should be no empty 'required' property, see #6834 + assert 'required' not in request_body['content']['application/json']['schema'] + for response in inspector._get_responses(path, method).values(): + assert 'required' not in response['content']['application/json']['schema'] + def test_response_body_generation(self): path = '/' method = 'POST'