From 6e131821208d4a4129d9c61d6ad466c2cf9762d2 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 26 Apr 2026 10:39:29 -0500 Subject: [PATCH] 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. --- tests/unit_tests/test_external_files.py | 37 +++++++++++++++---------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/tests/unit_tests/test_external_files.py b/tests/unit_tests/test_external_files.py index f4853160973..e81a8349db5 100644 --- a/tests/unit_tests/test_external_files.py +++ b/tests/unit_tests/test_external_files.py @@ -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)