Explicitly raise ValueError in to_primitive

The problem in the current version of to_primitive function
from jsonutils module is in the situation when the function
doesn't know how to convert an object to primitive. In that
case the function simply returns the same object which causes
the following exception later in json.dumps:
ValueError: Circular reference detected. This exception is not
obvious and is quite misleading. So I think it would be better
to explicitly raise ValueError here.

Closes-Bug: #1593641

Change-Id: If9e8dd5cc2634168910d5f9f8d9302aeefa16097
This commit is contained in:
ChangBo Guo(gcb) 2017-05-17 15:51:22 +08:00
parent 7fded98036
commit 3727b2d6e0
2 changed files with 2 additions and 2 deletions

View File

@ -167,7 +167,7 @@ def to_primitive(value, convert_instances=False, convert_datetime=True,
# __iter__ defined but it isn't callable as list().
return six.text_type(value)
return value
raise ValueError("Cannot convert %r to primitive" % (value,))
JSONEncoder = json.JSONEncoder

View File

@ -254,7 +254,7 @@ class ToPrimitiveTestCase(test_base.BaseTestCase):
self.assertEqual(dict(b=1),
jsonutils.to_primitive(x, convert_instances=True))
self.assertEqual(x, jsonutils.to_primitive(x))
self.assertRaises(ValueError, jsonutils.to_primitive, x)
def test_typeerror(self):
x = bytearray # Class, not instance