Skip to content

Commit

Permalink
fix: io blocking when downloading amazon images (#924)
Browse files Browse the repository at this point in the history
* fix: usps_mail_delivered device_class

* disable sensor by default

* fix test

* fix: io blocking when downloading amazon images

* fix test

* fix missing `await`, fix test
  • Loading branch information
firstof9 authored Jun 23, 2024
1 parent 7d52bce commit 6076568
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
12 changes: 7 additions & 5 deletions custom_components/mail_and_packages/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1163,10 +1163,12 @@ def get_amazon_image(

if img_url is not None:
# Download the image we found
hass.add_job(download_img(img_url, image_path, image_name))
hass.add_job(download_img(hass, img_url, image_path, image_name))


async def download_img(img_url: str, img_path: str, img_name: str) -> None:
async def download_img(
hass: HomeAssistant, img_url: str, img_path: str, img_name: str
) -> None:
"""Download image from url."""
img_path = f"{img_path}amazon/"
filepath = f"{img_path}{img_name}"
Expand All @@ -1181,9 +1183,9 @@ async def download_img(img_url: str, img_path: str, img_name: str) -> None:
if "image" in content_type:
data = await resp.read()
_LOGGER.debug("Downloading image to: %s", filepath)
with open(filepath, "wb") as the_file:
the_file.write(data)
_LOGGER.debug("Amazon image downloaded")
the_file = await hass.async_add_executor_job(open, filepath, "wb")
the_file.write(data)
_LOGGER.debug("Amazon image downloaded")


def _process_amazon_forwards(email_list: Union[List[str], None]) -> list:
Expand Down
5 changes: 4 additions & 1 deletion tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -948,6 +948,7 @@ async def test_usps_exception(hass, mock_imap_usps_exception):

@pytest.mark.asyncio
async def test_download_img(
hass,
aioclient_mock,
mock_osremove,
mock_osmakedir,
Expand All @@ -960,6 +961,7 @@ async def test_download_img(
m_open = mock_open()
with patch("builtins.open", m_open, create=True):
await download_img(
hass,
"http://fake.website.com/not/a/real/website/image.jpg",
"/fake/directory/",
"testfilename.jpg",
Expand All @@ -971,10 +973,11 @@ async def test_download_img(


@pytest.mark.asyncio
async def test_download_img_error(aioclient_mock_error, caplog):
async def test_download_img_error(hass, aioclient_mock_error, caplog):
m_open = mock_open()
with patch("builtins.open", m_open, create=True):
await download_img(
hass,
"http://fake.website.com/not/a/real/website/image.jpg",
"/fake/directory/",
"testfilename.jpg",
Expand Down

0 comments on commit 6076568

Please sign in to comment.