Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add workaround for orjson not handling subclasses of str #105314

Merged
merged 4 commits into from
Dec 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 11 additions & 3 deletions homeassistant/util/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,17 @@ class SerializationError(HomeAssistantError):
"""Error serializing the data to JSON."""


json_loads: Callable[[bytes | bytearray | memoryview | str], JsonValueType]
json_loads = orjson.loads
"""Parse JSON data."""
def json_loads(__obj: bytes | bytearray | memoryview | str) -> JsonValueType:
"""Parse JSON data.

This adds a workaround for orjson not handling subclasses of str,
https://github.com/ijl/orjson/issues/445.
"""
if type(__obj) in (bytes, bytearray, memoryview, str):
return orjson.loads(__obj) # type:ignore[no-any-return]
if isinstance(__obj, str):
return orjson.loads(str(__obj)) # type:ignore[no-any-return]
return orjson.loads(__obj) # type:ignore[no-any-return]


def json_loads_array(__obj: bytes | bytearray | memoryview | str) -> JsonArrayType:
Expand Down
19 changes: 19 additions & 0 deletions tests/util/test_json.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
"""Test Home Assistant json utility functions."""
from pathlib import Path

import orjson
import pytest

from homeassistant.exceptions import HomeAssistantError
from homeassistant.util.json import (
json_loads,
json_loads_array,
json_loads_object,
load_json,
Expand Down Expand Up @@ -153,3 +155,20 @@ async def test_deprecated_save_json(
save_json(fname, TEST_JSON_A)
assert "uses save_json from homeassistant.util.json" in caplog.text
assert "should be updated to use homeassistant.helpers.json module" in caplog.text


async def test_loading_derived_class():
"""Test loading data from classes derived from str."""

class MyStr(str):
pass

class MyBytes(bytes):
pass

assert json_loads('"abc"') == "abc"
assert json_loads(MyStr('"abc"')) == "abc"

assert json_loads(b'"abc"') == "abc"
with pytest.raises(orjson.JSONDecodeError):
assert json_loads(MyBytes(b'"abc"')) == "abc"