jsonutils: Raise ValueError in case the input can't be converted

According to the warning it was planned that this change was made in
3.0.

Change-Id: I0c1011b935f52f5ea1329e0316f935a034fdfd0e
This commit is contained in:
Takashi Kajinami 2023-11-09 00:55:22 +09:00
parent 27a8fd66c7
commit c83a4c9968
3 changed files with 12 additions and 15 deletions

View File

@ -37,7 +37,6 @@ import io
import itertools
import json
import uuid
import warnings
from xmlrpc import client as xmlrpclib
from oslo_utils import encodeutils
@ -173,13 +172,10 @@ def to_primitive(value, convert_instances=False, convert_datetime=True,
# __iter__ defined but it isn't callable as list().
return fallback(value)
if orig_fallback is not None:
return orig_fallback(value)
if orig_fallback is None:
raise ValueError("Cannot convert %r to primitive" % (value,))
# TODO(gcb) raise ValueError in version 3.0
warnings.warn("Cannot convert %r to primitive, will raise ValueError "
"instead of warning in version 3.0" % (value,))
return value
return orig_fallback(value)
JSONEncoder = json.JSONEncoder

View File

@ -261,8 +261,7 @@ class ToPrimitiveTestCase(test_base.BaseTestCase):
p = jsonutils.to_primitive(x)
self.assertEqual({'a': 1, 'b': 2, 'c': 3}, p)
@mock.patch('warnings.warn')
def test_instance(self, warn_mock):
def test_instance(self):
class MysteryClass(object):
a = 10
@ -273,8 +272,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))
warn_mock.assert_called_once()
self.assertRaises(ValueError, jsonutils.to_primitive, x)
def test_typeerror(self):
x = bytearray # Class, not instance
@ -354,8 +352,7 @@ class ToPrimitiveTestCase(test_base.BaseTestCase):
def test_fallback(self):
obj = ReprObject()
ret = jsonutils.to_primitive(obj)
self.assertIs(obj, ret)
self.assertRaises(ValueError, jsonutils.to_primitive, obj)
ret = jsonutils.to_primitive(obj, fallback=repr)
self.assertEqual('repr', ret)
@ -364,8 +361,7 @@ class ToPrimitiveTestCase(test_base.BaseTestCase):
obj = ReprObject()
obj_list = [obj]
ret = jsonutils.to_primitive(obj_list)
self.assertEqual([obj], ret)
self.assertRaises(ValueError, jsonutils.to_primitive, obj_list)
ret = jsonutils.to_primitive(obj_list, fallback=repr)
self.assertEqual(['repr'], ret)

View File

@ -0,0 +1,5 @@
---
upgrade:
- |
The ``oslo_utils.jsonutils.to_primitive`` function now raises ValueError
when the input value can't be converted.