Skip to content

Commit

Permalink
Fix encoding of floating point values into XML.
Browse files Browse the repository at this point in the history
The encoding functionality in `XMLEncoderAdapter` would throw an exception
when encountering a floating point value, indicating that the value was not
XML serializable.  This has been corrected by adding special handing for
floating point values, analogous to how other data types are handled.

Testing Done:
Added new unit tests to exercise both the JSON and XML encoder adapters.
Encoding is attempted on a variety of data types.  Prior to the fix, the
XML-based test would fail due to the presence of floating point data types.

Reviewed at https://reviews.reviewboard.org/r/8249/
  • Loading branch information
gkm4d authored and Barret Rennie committed Jun 22, 2016
1 parent bdd1252 commit a098afe
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
2 changes: 2 additions & 0 deletions djblets/webapi/encoders.py
Expand Up @@ -173,6 +173,8 @@ def __encode(self, o, *args, **kwargs):
self.text(o)
elif isinstance(o, six.integer_types):
self.text("%d" % o)
elif isinstance(o, float):
self.text("%s" % o)
elif isinstance(o, bool):
if o:
self.text("True")
Expand Down
59 changes: 59 additions & 0 deletions djblets/webapi/tests/test_encoders.py
@@ -0,0 +1,59 @@
from __future__ import unicode_literals

import json

from djblets.testing.testcases import TestCase
from djblets.webapi.encoders import (JSONEncoderAdapter, WebAPIEncoder,
XMLEncoderAdapter)


class EncoderAdapterTests(TestCase):
"""Tests encoding correctness of WebAPIEncoder adapters"""
data = {
'dict_val': {'foo': 'bar'},
'list_val': [10, 'baz'],
'string_val': 'foobar',
'int_val': 42,
'float_val': 3.14159,
'scientific_val': 2.75e-15,
'bool_val': True,
"none_val": None
}

def test_json_encoder_adapter(self):
"""Testing JSONEncoderAdapter.encode"""
encoder = WebAPIEncoder()
adapter = JSONEncoderAdapter(encoder)

content = adapter.encode(self.data)
self.assertEqual(content, json.dumps(self.data))

def test_xml_encoder_adapter(self):
"""Testing XMLEncoderAdapter.encode"""
encoder = WebAPIEncoder()
adapter = XMLEncoderAdapter(encoder)

expected = (
'<?xml version="1.0" encoding="utf-8"?>\n'
'<rsp>\n'
' <string_val>foobar</string_val>\n'
' <none_val>\n'
' </none_val>\n'
' <dict_val>\n'
' <foo>bar</foo>\n'
' </dict_val>\n'
' <bool_val>1</bool_val>\n'
' <scientific_val>2.75e-15</scientific_val>\n'
' <int_val>42</int_val>\n'
' <float_val>3.14159</float_val>\n'
' <list_val>\n'
' <array>\n'
' <item>10</item>\n'
' <item>baz</item>\n'
' </array>\n'
' </list_val>\n'
'</rsp>'
)

content = adapter.encode(self.data)
self.assertEqual(content, expected)

0 comments on commit a098afe

Please sign in to comment.