gh-99925: Fix inconsistency in `json.dumps()` error messages (GH-99926)

This commit is contained in:
František Nesveda 2022-12-20 10:54:56 +00:00 committed by GitHub
parent a6331b605e
commit d98ca8172c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 9 additions and 3 deletions

View File

@ -26,7 +26,8 @@ class TestFloat:
res = self.loads(out) res = self.loads(out)
self.assertEqual(len(res), 1) self.assertEqual(len(res), 1)
self.assertNotEqual(res[0], res[0]) self.assertNotEqual(res[0], res[0])
self.assertRaises(ValueError, self.dumps, [val], allow_nan=False) msg = f'Out of range float values are not JSON compliant: {val}'
self.assertRaisesRegex(ValueError, msg, self.dumps, [val], allow_nan=False)
class TestPyFloat(TestFloat, PyTest): pass class TestPyFloat(TestFloat, PyTest): pass

View File

@ -0,0 +1,4 @@
Unify error messages in JSON serialization between
``json.dumps(float('nan'), allow_nan=False)`` and ``json.dumps(float('nan'),
allow_nan=False, indent=<SOMETHING>)``. Now both include the representation
of the value that could not be serialized.

View File

@ -1319,9 +1319,10 @@ encoder_encode_float(PyEncoderObject *s, PyObject *obj)
double i = PyFloat_AS_DOUBLE(obj); double i = PyFloat_AS_DOUBLE(obj);
if (!Py_IS_FINITE(i)) { if (!Py_IS_FINITE(i)) {
if (!s->allow_nan) { if (!s->allow_nan) {
PyErr_SetString( PyErr_Format(
PyExc_ValueError, PyExc_ValueError,
"Out of range float values are not JSON compliant" "Out of range float values are not JSON compliant: %R",
obj
); );
return NULL; return NULL;
} }