Fix REST sensor charset handling to respect Content-Type header (#148223)

This commit is contained in:
J. Nick Koston
2025-07-07 08:32:58 -05:00
committed by Franck Nijhof
parent c965da6559
commit 9650727515
3 changed files with 114 additions and 4 deletions

View File

@@ -191,7 +191,6 @@ class AiohttpClientMockResponse:
if response is None:
response = b""
self.charset = "utf-8"
self.method = method
self._url = url
self.status = status
@@ -261,16 +260,32 @@ class AiohttpClientMockResponse:
"""Return content."""
return mock_stream(self.response)
@property
def charset(self):
"""Return charset from Content-Type header."""
if (content_type := self._headers.get("content-type")) is None:
return None
content_type = content_type.lower()
if "charset=" in content_type:
return content_type.split("charset=")[1].split(";")[0].strip()
return None
async def read(self):
"""Return mock response."""
return self.response
async def text(self, encoding="utf-8", errors="strict"):
async def text(self, encoding=None, errors="strict") -> str:
"""Return mock response as a string."""
# Match real aiohttp behavior: encoding=None means auto-detect
if encoding is None:
encoding = self.charset or "utf-8"
return self.response.decode(encoding, errors=errors)
async def json(self, encoding="utf-8", content_type=None, loads=json_loads):
async def json(self, encoding=None, content_type=None, loads=json_loads) -> Any:
"""Return mock response as a json."""
# Match real aiohttp behavior: encoding=None means auto-detect
if encoding is None:
encoding = self.charset or "utf-8"
return loads(self.response.decode(encoding))
def release(self):