From 3727b2d6e051b7b07680df361f38b9dbb576462c Mon Sep 17 00:00:00 2001 From: "ChangBo Guo(gcb)" Date: Wed, 17 May 2017 15:51:22 +0800 Subject: [PATCH] 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 --- oslo_serialization/jsonutils.py | 2 +- oslo_serialization/tests/test_jsonutils.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/oslo_serialization/jsonutils.py b/oslo_serialization/jsonutils.py index 7df6496..90a5acf 100644 --- a/oslo_serialization/jsonutils.py +++ b/oslo_serialization/jsonutils.py @@ -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 diff --git a/oslo_serialization/tests/test_jsonutils.py b/oslo_serialization/tests/test_jsonutils.py index f649db3..b030b8f 100644 --- a/oslo_serialization/tests/test_jsonutils.py +++ b/oslo_serialization/tests/test_jsonutils.py @@ -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