Skip to content

Commit

Permalink
catch attr exception for invalid SerializerMethodField #592
Browse files Browse the repository at this point in the history
  • Loading branch information
tfranzel committed Nov 1, 2021
1 parent 36b970e commit af1cccd
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
9 changes: 8 additions & 1 deletion drf_spectacular/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,7 +697,14 @@ def _map_serializer_field(self, field, direction, bypass_extensions=False):
return append_meta(content, meta)

if isinstance(field, serializers.SerializerMethodField):
method = getattr(field.parent, field.method_name)
method = getattr(field.parent, field.method_name, None)
if method is None:
error(
f'SerializerMethodField "{field.field_name}" is missing required method '
f'"{field.method_name}". defaulting to "string".'
)
return append_meta(build_basic_type(OpenApiTypes.STR), meta)

return append_meta(self._map_response_type_hint(method), meta)

if isinstance(field, (serializers.BooleanField, serializers.NullBooleanField)):
Expand Down
14 changes: 14 additions & 0 deletions tests/test_warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,3 +419,17 @@ def view_func(request, format=None):
generate_schema('x', view_function=view_func)
stderr = capsys.readouterr().err
assert 'invalid extension \'foo\'. vendor extensions must start with' in stderr


def test_serializer_method_missing(capsys):
class XSerializer(serializers.Serializer):
some_field = serializers.SerializerMethodField()

@extend_schema(responses=XSerializer)
@api_view(['GET'])
def view_func(request):
pass # pragma: no cover

generate_schema('x', view_function=view_func)
stderr = capsys.readouterr().err
assert 'SerializerMethodField "some_field" is missing required method "get_some_field"' in stderr

0 comments on commit af1cccd

Please sign in to comment.