From fd9fdc628367be9d0c3daa91e3a63e3ce6199924 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 23 Jun 2022 13:32:45 -0500 Subject: [PATCH] Fix error reporting with unserializable json (#73908) --- homeassistant/util/json.py | 4 +++- tests/util/test_json.py | 14 +++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/homeassistant/util/json.py b/homeassistant/util/json.py index 82ecfd34d6d..8a9663bb95d 100644 --- a/homeassistant/util/json.py +++ b/homeassistant/util/json.py @@ -57,13 +57,15 @@ def save_json( Returns True on success. """ + dump: Callable[[Any], Any] = json.dumps try: if encoder: json_data = json.dumps(data, indent=2, cls=encoder) else: + dump = orjson.dumps json_data = orjson.dumps(data, option=orjson.OPT_INDENT_2).decode("utf-8") except TypeError as error: - msg = f"Failed to serialize to JSON: {filename}. Bad data at {format_unserializable_data(find_paths_unserializable_data(data))}" + msg = f"Failed to serialize to JSON: {filename}. Bad data at {format_unserializable_data(find_paths_unserializable_data(data, dump=dump))}" _LOGGER.error(msg) raise SerializationError(msg) from error diff --git a/tests/util/test_json.py b/tests/util/test_json.py index 461d94d0c67..abf47b0bc53 100644 --- a/tests/util/test_json.py +++ b/tests/util/test_json.py @@ -11,6 +11,7 @@ import pytest from homeassistant.core import Event, State from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers.template import TupleWrapper from homeassistant.util.json import ( SerializationError, find_paths_unserializable_data, @@ -72,7 +73,7 @@ def test_overwrite_and_reload(atomic_writes): def test_save_bad_data(): - """Test error from trying to save unserialisable data.""" + """Test error from trying to save unserializable data.""" with pytest.raises(SerializationError) as excinfo: save_json("test4", {"hello": set()}) @@ -82,6 +83,17 @@ def test_save_bad_data(): ) +def test_save_bad_data_tuple_wrapper(): + """Test error from trying to save unserializable data.""" + with pytest.raises(SerializationError) as excinfo: + save_json("test4", {"hello": TupleWrapper(("4", "5"))}) + + assert ( + "Failed to serialize to JSON: test4. Bad data at $.hello=('4', '5')(" + in str(excinfo.value) + ) + + def test_load_bad_data(): """Test error from trying to load unserialisable data.""" fname = _path_for("test5")