Address Copilot review on PR #16023

Replace `type(mock_response).content = property(...)` with a tiny
_BodyReadErrorResponse stub class. The previous form mutates
MagicMock's class globally, which can leak into every other
MagicMock-using test in this file.
This commit is contained in:
J. Nick Koston
2026-04-26 10:39:29 -05:00
parent 24a3c2202f
commit 6e13182120
+23 -14
View File
@@ -238,6 +238,25 @@ def test_download_content_with_network_error_no_cache_fails(
external_files.download_content(url, test_file)
class _BodyReadErrorResponse:
"""Stand-in for `requests.Response` whose `.content` raises on access.
A small dedicated stub avoids mutating `MagicMock`'s class with a
`property` (which would leak across every other MagicMock-based test
in this file).
"""
def __init__(self, exc: Exception) -> None:
self._exc = exc
def raise_for_status(self) -> None:
return None
@property
def content(self) -> bytes:
raise self._exc
@patch("esphome.external_files.requests.get")
@patch("esphome.external_files.has_remote_file_changed")
def test_download_content_with_body_read_error_uses_cache(
@@ -253,14 +272,9 @@ def test_download_content_with_body_read_error_uses_cache(
test_file.write_bytes(cached_content)
mock_has_changed.return_value = True
mock_response = MagicMock()
mock_response.raise_for_status = MagicMock()
type(mock_response).content = property(
lambda self: (_ for _ in ()).throw(
requests.exceptions.ChunkedEncodingError("body truncated")
)
mock_get.return_value = _BodyReadErrorResponse(
requests.exceptions.ChunkedEncodingError("body truncated")
)
mock_get.return_value = mock_response
result = external_files.download_content("https://example.com/file.txt", test_file)
@@ -278,14 +292,9 @@ def test_download_content_with_body_read_error_no_cache_fails(
test_file = setup_core / "nonexistent.txt"
mock_has_changed.return_value = True
mock_response = MagicMock()
mock_response.raise_for_status = MagicMock()
type(mock_response).content = property(
lambda self: (_ for _ in ()).throw(
requests.exceptions.ChunkedEncodingError("body truncated")
)
mock_get.return_value = _BodyReadErrorResponse(
requests.exceptions.ChunkedEncodingError("body truncated")
)
mock_get.return_value = mock_response
with pytest.raises(Invalid, match="Could not download from.*body truncated"):
external_files.download_content("https://example.com/file.txt", test_file)