Skip to content

Commit

Permalink
SchemaJSRenderer renders invalid Javascript (#5607)
Browse files Browse the repository at this point in the history
* SchemaJSRenderer renders invalid Javascript

Under Py3 the base64.b64encode() method returns a binary object, which gets rendered as `b'...'` in schema.js. This results in the output becoming:

    var coreJSON = window.atob('b'eyJf...'');

which is invalid Javascript. Because base64 only uses ASCII characters it is safe to decode('ascii') it. Under Py2 this will result in a unicode object, which is fine. Under Py3 it results in a string, which is also fine. This solves the problem and results in a working schema.js output.

* Add regression test for #5608

* Add regression test for #5608

* Apparently the linter on Travis wants the imports in a different order than on my box...
  • Loading branch information
steffann authored and carltongibson committed Nov 22, 2017
1 parent 1a667f4 commit d71bd57
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
2 changes: 1 addition & 1 deletion rest_framework/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -852,7 +852,7 @@ class SchemaJSRenderer(BaseRenderer):

def render(self, data, accepted_media_type=None, renderer_context=None):
codec = coreapi.codecs.CoreJSONCodec()
schema = base64.b64encode(codec.encode(data))
schema = base64.b64encode(codec.encode(data)).decode('ascii')

template = loader.get_template(self.template)
context = {'schema': mark_safe(schema)}
Expand Down
19 changes: 18 additions & 1 deletion tests/test_renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from rest_framework import permissions, serializers, status
from rest_framework.renderers import (
AdminRenderer, BaseRenderer, BrowsableAPIRenderer, DocumentationRenderer,
HTMLFormRenderer, JSONRenderer, StaticHTMLRenderer
HTMLFormRenderer, JSONRenderer, SchemaJSRenderer, StaticHTMLRenderer
)
from rest_framework.request import Request
from rest_framework.response import Response
Expand Down Expand Up @@ -736,3 +736,20 @@ def test_document_with_link_named_data(self):

html = renderer.render(document, accepted_media_type="text/html", renderer_context={"request": request})
assert '<h1>Data Endpoint API</h1>' in html


class TestSchemaJSRenderer(TestCase):

def test_schemajs_output(self):
"""
Test output of the SchemaJS renderer as per #5608. Django 2.0 on Py3 prints binary data as b'xyz' in templates,
and the base64 encoding used by SchemaJSRenderer outputs base64 as binary. Test fix.
"""
factory = APIRequestFactory()
request = factory.get('/')

renderer = SchemaJSRenderer()

output = renderer.render('data', renderer_context={"request": request})
assert "'ImRhdGEi'" in output
assert "'b'ImRhdGEi''" not in output

0 comments on commit d71bd57

Please sign in to comment.