Skip to content

Commit

Permalink
handle drf type error for yaml. #41
Browse files Browse the repository at this point in the history
  • Loading branch information
tfranzel committed May 3, 2020
1 parent 69bcc05 commit 5f4fa7d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
12 changes: 11 additions & 1 deletion drf_spectacular/renderers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import yaml
from rest_framework.exceptions import ErrorDetail
from rest_framework.renderers import OpenAPIRenderer, JSONRenderer


Expand All @@ -11,7 +12,16 @@ class Dumper(yaml.SafeDumper):
def ignore_aliases(self, data):
return True

return yaml.dump(data, default_flow_style=False, sort_keys=False, Dumper=Dumper).encode('utf-8')
def error_detail_representer(dumper, data):
return dumper.represent_dict({'string': str(data), 'code': data.code})
Dumper.add_representer(ErrorDetail, error_detail_representer)

return yaml.dump(
data,
default_flow_style=False,
sort_keys=False,
Dumper=Dumper
).encode('utf-8')


class OpenApiYamlRenderer2(OpenApiYamlRenderer):
Expand Down
10 changes: 10 additions & 0 deletions tests/test_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,13 @@ def test_spectacular_view_accept(accept, format, indent):
assert response.content.startswith(b'{\n' + indent * b' ' + b'"openapi": "3.0.3"')
if format == 'yaml':
assert response.content.startswith(b'openapi: 3.0.3\n')


@pytest.mark.urls(__name__)
def test_spectacular_view_accept_unknown(no_warnings):
response = APIClient().get('/api/v1/schema', HTTP_ACCEPT='application/unknown')
assert response.status_code == 406
assert response.content == (
b'detail:\n string: Could not satisfy the request Accept header.\n'
b' code: not_acceptable\n'
)

0 comments on commit 5f4fa7d

Please sign in to comment.