Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions custom_components/xiaomi_miot/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -597,9 +597,13 @@ async def fetch_latest_message(self):
}
try:
res = await mic.async_request_api(api, data=dat, method='GET', cookies=cks) or {}
rdt = res.get('data', {})
if not isinstance(rdt, dict):
rdt = res.get('data')
if rdt is None:
return {}
if isinstance(rdt, (str, bytes, bytearray)):
rdt = json.loads(rdt) or {}
Comment on lines +603 to 604

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If json.loads(rdt) raises a JSONDecodeError (which is a subclass of ValueError), the execution falls into the outer except block. Currently, that block sets rdt = {} and continues execution, which clears the conversation and its attributes (setting them to empty/None).

To fully satisfy the PR's goal of preserving the last valid conversation on unexpected payloads or failures, we should handle JSON parsing errors gracefully by returning {} immediately. Additionally, you should consider updating the outer except block to also return {} instead of setting rdt = {} so that connection or API errors do not clear the last valid conversation.

Suggested change
if isinstance(rdt, (str, bytes, bytearray)):
rdt = json.loads(rdt) or {}
if isinstance(rdt, (str, bytes, bytearray)):
try:
rdt = json.loads(rdt) or {}
except (TypeError, ValueError):
return {}

if not isinstance(rdt, dict):
return {}
except (TypeError, ValueError, Exception) as exc:
rdt = {}
_LOGGER.warning(
Expand Down
39 changes: 39 additions & 0 deletions tests/test_xiaoai_conversation_sensor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from types import SimpleNamespace
from unittest.mock import AsyncMock

import pytest

from custom_components.xiaomi_miot import sensor as sensor_module
from custom_components.xiaomi_miot.sensor import XiaoaiConversationSensor


@pytest.mark.parametrize('response_data', [None, []])
async def test_invalid_response_data_keeps_last_conversation(monkeypatch, response_data):
class FakeMiotCloud:
async_request_api = AsyncMock(return_value={'data': response_data})

monkeypatch.setattr(sensor_module, 'MiotCloud', FakeMiotCloud)
previous = {
'content': 'turn off the computer',
'answers': [],
'history': [],
'timestamp': None,
}
sensor = XiaoaiConversationSensor.__new__(XiaoaiConversationSensor)
sensor._parent = SimpleNamespace(
xiaoai_cloud=FakeMiotCloud(),
xiaoai_device={'deviceID': 'test-device', 'hardware': 'test-hardware'},
device_name='Test Speaker',
)
sensor._model = 'test.speaker'
sensor._available = True
sensor._attr_native_value = previous['content']
sensor._state_attrs = previous.copy()
sensor.conversation = {'query': previous['content']}

result = await sensor.fetch_latest_message()

assert result == {}
assert sensor._attr_native_value == previous['content']
assert sensor._state_attrs == previous
assert sensor.conversation == {'query': previous['content']}