init home-assistant
This commit is contained in:
1
home-assistant/tests/components/image/__init__.py
Normal file
1
home-assistant/tests/components/image/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""The tests for the image integration."""
|
||||
218
home-assistant/tests/components/image/conftest.py
Normal file
218
home-assistant/tests/components/image/conftest.py
Normal file
@@ -0,0 +1,218 @@
|
||||
"""Test helpers for image."""
|
||||
|
||||
from collections.abc import Generator
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components import image
|
||||
from homeassistant.config_entries import ConfigEntry, ConfigFlow
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
|
||||
from homeassistant.setup import async_setup_component
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from tests.common import (
|
||||
MockConfigEntry,
|
||||
MockModule,
|
||||
mock_config_flow,
|
||||
mock_integration,
|
||||
mock_platform,
|
||||
)
|
||||
|
||||
TEST_DOMAIN = "test"
|
||||
|
||||
|
||||
class MockImageEntity(image.ImageEntity):
|
||||
"""Mock image entity."""
|
||||
|
||||
_attr_name = "Test"
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Set the update time."""
|
||||
self._attr_image_last_updated = dt_util.utcnow()
|
||||
|
||||
async def async_image(self) -> bytes | None:
|
||||
"""Return bytes of image."""
|
||||
return b"Test"
|
||||
|
||||
|
||||
class MockImageEntityInvalidContentType(image.ImageEntity):
|
||||
"""Mock image entity."""
|
||||
|
||||
_attr_name = "Test"
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Set the update time and assign and incorrect content type."""
|
||||
self._attr_content_type = "text/json"
|
||||
self._attr_image_last_updated = dt_util.utcnow()
|
||||
|
||||
async def async_image(self) -> bytes | None:
|
||||
"""Return bytes of image."""
|
||||
return b"Test"
|
||||
|
||||
|
||||
class MockImageEntityCapitalContentType(image.ImageEntity):
|
||||
"""Mock image entity with correct content type, but capitalized."""
|
||||
|
||||
_attr_name = "Test"
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Set the update time and assign and incorrect content type."""
|
||||
self._attr_content_type = "Image/jpeg"
|
||||
self._attr_image_last_updated = dt_util.utcnow()
|
||||
|
||||
async def async_image(self) -> bytes | None:
|
||||
"""Return bytes of image."""
|
||||
return b"Test"
|
||||
|
||||
|
||||
class MockURLImageEntity(image.ImageEntity):
|
||||
"""Mock image entity."""
|
||||
|
||||
_attr_image_url = "https://example.com/myimage.jpg"
|
||||
_attr_name = "Test"
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Set the update time."""
|
||||
self._attr_image_last_updated = dt_util.utcnow()
|
||||
|
||||
|
||||
class MockImageNoStateEntity(image.ImageEntity):
|
||||
"""Mock image entity."""
|
||||
|
||||
_attr_name = "Test"
|
||||
|
||||
async def async_image(self) -> bytes | None:
|
||||
"""Return bytes of image."""
|
||||
return b"Test"
|
||||
|
||||
|
||||
class MockImageNoDataEntity(image.ImageEntity):
|
||||
"""Mock image entity."""
|
||||
|
||||
_attr_name = "Test"
|
||||
|
||||
async def async_image(self) -> bytes | None:
|
||||
"""Return bytes of image."""
|
||||
return None
|
||||
|
||||
|
||||
class MockImageSyncEntity(image.ImageEntity):
|
||||
"""Mock image entity."""
|
||||
|
||||
_attr_name = "Test"
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Set the update time."""
|
||||
self._attr_image_last_updated = dt_util.utcnow()
|
||||
|
||||
def image(self) -> bytes | None:
|
||||
"""Return bytes of image."""
|
||||
return b"Test"
|
||||
|
||||
|
||||
class MockImageConfigEntry:
|
||||
"""A mock image config entry."""
|
||||
|
||||
def __init__(self, entities: list[image.ImageEntity]) -> None:
|
||||
"""Initialize."""
|
||||
self._entities = entities
|
||||
|
||||
async def async_setup_entry(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
config_entry: ConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up test image platform via config entry."""
|
||||
async_add_entities([self._entities])
|
||||
|
||||
|
||||
class MockImagePlatform:
|
||||
"""A mock image platform."""
|
||||
|
||||
PLATFORM_SCHEMA = image.PLATFORM_SCHEMA
|
||||
|
||||
def __init__(self, entities: list[image.ImageEntity]) -> None:
|
||||
"""Initialize."""
|
||||
self._entities = entities
|
||||
|
||||
async def async_setup_platform(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
config: ConfigType,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
discovery_info: DiscoveryInfoType | None = None,
|
||||
) -> None:
|
||||
"""Set up the mock image platform."""
|
||||
async_add_entities(self._entities)
|
||||
|
||||
|
||||
@pytest.fixture(name="config_flow")
|
||||
def config_flow_fixture(hass: HomeAssistant) -> Generator[None]:
|
||||
"""Mock config flow."""
|
||||
|
||||
class MockFlow(ConfigFlow):
|
||||
"""Test flow."""
|
||||
|
||||
mock_platform(hass, f"{TEST_DOMAIN}.config_flow")
|
||||
|
||||
with mock_config_flow(TEST_DOMAIN, MockFlow):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="mock_image_config_entry")
|
||||
async def mock_image_config_entry_fixture(
|
||||
hass: HomeAssistant, config_flow: None
|
||||
) -> ConfigEntry:
|
||||
"""Initialize a mock image config_entry."""
|
||||
|
||||
async def async_setup_entry_init(
|
||||
hass: HomeAssistant, config_entry: ConfigEntry
|
||||
) -> bool:
|
||||
"""Set up test config entry."""
|
||||
await hass.config_entries.async_forward_entry_setups(
|
||||
config_entry, [image.DOMAIN]
|
||||
)
|
||||
return True
|
||||
|
||||
async def async_unload_entry_init(
|
||||
hass: HomeAssistant, config_entry: ConfigEntry
|
||||
) -> bool:
|
||||
"""Unload test config entry."""
|
||||
await hass.config_entries.async_unload_platforms(config_entry, [image.DOMAIN])
|
||||
return True
|
||||
|
||||
mock_integration(
|
||||
hass,
|
||||
MockModule(
|
||||
TEST_DOMAIN,
|
||||
async_setup_entry=async_setup_entry_init,
|
||||
async_unload_entry=async_unload_entry_init,
|
||||
),
|
||||
)
|
||||
|
||||
mock_platform(
|
||||
hass,
|
||||
f"{TEST_DOMAIN}.{image.DOMAIN}",
|
||||
MockImageConfigEntry(MockImageEntity(hass)),
|
||||
)
|
||||
|
||||
config_entry = MockConfigEntry(domain=TEST_DOMAIN)
|
||||
config_entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
return config_entry
|
||||
|
||||
|
||||
@pytest.fixture(name="mock_image_platform")
|
||||
async def mock_image_platform_fixture(hass: HomeAssistant) -> None:
|
||||
"""Initialize a mock image platform."""
|
||||
mock_integration(hass, MockModule(domain="test"))
|
||||
mock_platform(hass, "test.image", MockImagePlatform([MockImageEntity(hass)]))
|
||||
assert await async_setup_component(
|
||||
hass, image.DOMAIN, {"image": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
495
home-assistant/tests/components/image/test_init.py
Normal file
495
home-assistant/tests/components/image/test_init.py
Normal file
@@ -0,0 +1,495 @@
|
||||
"""The tests for the image component."""
|
||||
|
||||
from datetime import datetime
|
||||
from http import HTTPStatus
|
||||
import ssl
|
||||
from unittest.mock import MagicMock, mock_open, patch
|
||||
|
||||
from aiohttp import hdrs
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import httpx
|
||||
import pytest
|
||||
import respx
|
||||
|
||||
from homeassistant.components import image
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import ATTR_ENTITY_ID
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from .conftest import (
|
||||
MockImageEntity,
|
||||
MockImageEntityCapitalContentType,
|
||||
MockImageEntityInvalidContentType,
|
||||
MockImageNoDataEntity,
|
||||
MockImageNoStateEntity,
|
||||
MockImagePlatform,
|
||||
MockImageSyncEntity,
|
||||
MockURLImageEntity,
|
||||
)
|
||||
|
||||
from tests.common import (
|
||||
MockModule,
|
||||
async_fire_time_changed,
|
||||
mock_integration,
|
||||
mock_platform,
|
||||
)
|
||||
from tests.typing import ClientSessionGenerator
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2023-04-01 00:00:00+00:00")
|
||||
async def test_state(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator, mock_image_platform: None
|
||||
) -> None:
|
||||
"""Test image state."""
|
||||
state = hass.states.get("image.test")
|
||||
assert state.state == "2023-04-01T00:00:00+00:00"
|
||||
access_token = state.attributes["access_token"]
|
||||
assert state.attributes == {
|
||||
"access_token": access_token,
|
||||
"entity_picture": f"/api/image_proxy/image.test?token={access_token}",
|
||||
"friendly_name": "Test",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2023-04-01 00:00:00+00:00")
|
||||
async def test_config_entry(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
mock_image_config_entry: ConfigEntry,
|
||||
) -> None:
|
||||
"""Test setting up an image platform from a config entry."""
|
||||
state = hass.states.get("image.test")
|
||||
assert state.state == "2023-04-01T00:00:00+00:00"
|
||||
access_token = state.attributes["access_token"]
|
||||
assert state.attributes == {
|
||||
"access_token": access_token,
|
||||
"entity_picture": f"/api/image_proxy/image.test?token={access_token}",
|
||||
"friendly_name": "Test",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2023-04-01 00:00:00+00:00")
|
||||
async def test_state_attr(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test image state with entity picture from attr."""
|
||||
mock_integration(hass, MockModule(domain="test"))
|
||||
entity = MockImageEntity(hass)
|
||||
entity._attr_entity_picture = "abcd"
|
||||
mock_platform(hass, "test.image", MockImagePlatform([entity]))
|
||||
assert await async_setup_component(
|
||||
hass, image.DOMAIN, {"image": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get("image.test")
|
||||
assert state.state == "2023-04-01T00:00:00+00:00"
|
||||
access_token = state.attributes["access_token"]
|
||||
assert state.attributes == {
|
||||
"access_token": access_token,
|
||||
"entity_picture": "abcd",
|
||||
"friendly_name": "Test",
|
||||
}
|
||||
|
||||
|
||||
async def test_no_state(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test image state."""
|
||||
mock_integration(hass, MockModule(domain="test"))
|
||||
mock_platform(hass, "test.image", MockImagePlatform([MockImageNoStateEntity(hass)]))
|
||||
assert await async_setup_component(
|
||||
hass, image.DOMAIN, {"image": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get("image.test")
|
||||
assert state.state == "unknown"
|
||||
access_token = state.attributes["access_token"]
|
||||
assert state.attributes == {
|
||||
"access_token": access_token,
|
||||
"entity_picture": f"/api/image_proxy/image.test?token={access_token}",
|
||||
"friendly_name": "Test",
|
||||
}
|
||||
|
||||
|
||||
async def test_no_valid_content_type(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test invalid content type."""
|
||||
mock_integration(hass, MockModule(domain="test"))
|
||||
mock_platform(
|
||||
hass, "test.image", MockImagePlatform([MockImageEntityInvalidContentType(hass)])
|
||||
)
|
||||
assert await async_setup_component(
|
||||
hass, image.DOMAIN, {"image": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
client = await hass_client()
|
||||
|
||||
state = hass.states.get("image.test")
|
||||
# assert state.state == "unknown"
|
||||
access_token = state.attributes["access_token"]
|
||||
assert state.attributes == {
|
||||
"access_token": access_token,
|
||||
"entity_picture": f"/api/image_proxy/image.test?token={access_token}",
|
||||
"friendly_name": "Test",
|
||||
}
|
||||
resp = await client.get(f"/api/image_proxy/image.test?token={access_token}")
|
||||
assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR
|
||||
|
||||
|
||||
async def test_valid_but_capitalized_content_type(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test invalid content type."""
|
||||
mock_integration(hass, MockModule(domain="test"))
|
||||
mock_platform(
|
||||
hass, "test.image", MockImagePlatform([MockImageEntityCapitalContentType(hass)])
|
||||
)
|
||||
assert await async_setup_component(
|
||||
hass, image.DOMAIN, {"image": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
client = await hass_client()
|
||||
|
||||
state = hass.states.get("image.test")
|
||||
access_token = state.attributes["access_token"]
|
||||
assert state.attributes == {
|
||||
"access_token": access_token,
|
||||
"entity_picture": f"/api/image_proxy/image.test?token={access_token}",
|
||||
"friendly_name": "Test",
|
||||
}
|
||||
resp = await client.get(f"/api/image_proxy/image.test?token={access_token}")
|
||||
assert resp.status == HTTPStatus.OK
|
||||
|
||||
|
||||
async def test_fetch_image_authenticated(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator, mock_image_platform: None
|
||||
) -> None:
|
||||
"""Test fetching an image with an authenticated client."""
|
||||
client = await hass_client()
|
||||
|
||||
resp = await client.get("/api/image_proxy/image.test")
|
||||
assert resp.status == HTTPStatus.OK
|
||||
body = await resp.read()
|
||||
assert body == b"Test"
|
||||
|
||||
resp = await client.get("/api/image_proxy/image.unknown")
|
||||
assert resp.status == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
async def test_fetch_image_fail(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator, mock_image_platform: None
|
||||
) -> None:
|
||||
"""Test fetching an image with an authenticated client."""
|
||||
client = await hass_client()
|
||||
|
||||
with patch.object(MockImageEntity, "async_image", side_effect=TimeoutError):
|
||||
resp = await client.get("/api/image_proxy/image.test")
|
||||
assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR
|
||||
|
||||
|
||||
async def test_fetch_image_sync(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test fetching an image with an authenticated client."""
|
||||
mock_integration(hass, MockModule(domain="test"))
|
||||
mock_platform(hass, "test.image", MockImagePlatform([MockImageSyncEntity(hass)]))
|
||||
assert await async_setup_component(
|
||||
hass, image.DOMAIN, {"image": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
client = await hass_client()
|
||||
|
||||
resp = await client.get("/api/image_proxy/image.test")
|
||||
assert resp.status == HTTPStatus.OK
|
||||
body = await resp.read()
|
||||
assert body == b"Test"
|
||||
|
||||
|
||||
async def test_fetch_image_unauthenticated(
|
||||
hass: HomeAssistant,
|
||||
hass_client_no_auth: ClientSessionGenerator,
|
||||
mock_image_platform: None,
|
||||
) -> None:
|
||||
"""Test fetching an image with an unauthenticated client."""
|
||||
client = await hass_client_no_auth()
|
||||
|
||||
resp = await client.get("/api/image_proxy/image.test")
|
||||
assert resp.status == HTTPStatus.FORBIDDEN
|
||||
|
||||
resp = await client.get("/api/image_proxy/image.test")
|
||||
assert resp.status == HTTPStatus.FORBIDDEN
|
||||
|
||||
resp = await client.get(
|
||||
"/api/image_proxy/image.test", headers={hdrs.AUTHORIZATION: "blabla"}
|
||||
)
|
||||
assert resp.status == HTTPStatus.UNAUTHORIZED
|
||||
|
||||
state = hass.states.get("image.test")
|
||||
resp = await client.get(state.attributes["entity_picture"])
|
||||
assert resp.status == HTTPStatus.OK
|
||||
body = await resp.read()
|
||||
assert body == b"Test"
|
||||
|
||||
resp = await client.get("/api/image_proxy/image.unknown")
|
||||
assert resp.status == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_fetch_image_url_success(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test fetching an image with an authenticated client."""
|
||||
respx.get("https://example.com/myimage.jpg").respond(
|
||||
status_code=HTTPStatus.OK, content_type="image/png", content=b"Test"
|
||||
)
|
||||
|
||||
mock_integration(hass, MockModule(domain="test"))
|
||||
mock_platform(hass, "test.image", MockImagePlatform([MockURLImageEntity(hass)]))
|
||||
assert await async_setup_component(
|
||||
hass, image.DOMAIN, {"image": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
client = await hass_client()
|
||||
|
||||
resp = await client.get("/api/image_proxy/image.test")
|
||||
assert resp.status == HTTPStatus.OK
|
||||
body = await resp.read()
|
||||
assert body == b"Test"
|
||||
|
||||
|
||||
@respx.mock
|
||||
@pytest.mark.parametrize(
|
||||
"side_effect",
|
||||
[
|
||||
httpx.RequestError("server offline", request=MagicMock()),
|
||||
httpx.TimeoutException,
|
||||
ssl.SSLError,
|
||||
],
|
||||
)
|
||||
async def test_fetch_image_url_exception(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
side_effect: Exception,
|
||||
) -> None:
|
||||
"""Test fetching an image with an authenticated client."""
|
||||
respx.get("https://example.com/myimage.jpg").mock(side_effect=side_effect)
|
||||
|
||||
mock_integration(hass, MockModule(domain="test"))
|
||||
mock_platform(hass, "test.image", MockImagePlatform([MockURLImageEntity(hass)]))
|
||||
assert await async_setup_component(
|
||||
hass, image.DOMAIN, {"image": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
client = await hass_client()
|
||||
|
||||
resp = await client.get("/api/image_proxy/image.test")
|
||||
assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR
|
||||
|
||||
|
||||
@respx.mock
|
||||
@pytest.mark.parametrize(
|
||||
"content_type",
|
||||
[
|
||||
None,
|
||||
"text/plain",
|
||||
],
|
||||
)
|
||||
async def test_fetch_image_url_wrong_content_type(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
content_type: str | None,
|
||||
) -> None:
|
||||
"""Test fetching an image with an authenticated client."""
|
||||
respx.get("https://example.com/myimage.jpg").respond(
|
||||
status_code=HTTPStatus.OK, content_type=content_type, content=b"Test"
|
||||
)
|
||||
|
||||
mock_integration(hass, MockModule(domain="test"))
|
||||
mock_platform(hass, "test.image", MockImagePlatform([MockURLImageEntity(hass)]))
|
||||
assert await async_setup_component(
|
||||
hass, image.DOMAIN, {"image": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
client = await hass_client()
|
||||
|
||||
resp = await client.get("/api/image_proxy/image.test")
|
||||
assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR
|
||||
|
||||
|
||||
async def test_image_stream(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test image stream."""
|
||||
|
||||
mock_integration(hass, MockModule(domain="test"))
|
||||
mock_image = MockURLImageEntity(hass)
|
||||
mock_platform(hass, "test.image", MockImagePlatform([mock_image]))
|
||||
assert await async_setup_component(
|
||||
hass, image.DOMAIN, {"image": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
client = await hass_client()
|
||||
|
||||
close_future = hass.loop.create_future()
|
||||
original_get_still_stream = image.async_get_still_stream
|
||||
|
||||
async def _wrap_async_get_still_stream(*args, **kwargs):
|
||||
result = await original_get_still_stream(*args, **kwargs)
|
||||
hass.loop.call_soon(close_future.set_result, None)
|
||||
return result
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.image.async_get_still_stream",
|
||||
_wrap_async_get_still_stream,
|
||||
):
|
||||
with patch.object(mock_image, "async_image", return_value=b""):
|
||||
resp = await client.get("/api/image_proxy_stream/image.test")
|
||||
assert not resp.closed
|
||||
assert resp.status == HTTPStatus.OK
|
||||
|
||||
mock_image.image_last_updated = datetime.now()
|
||||
mock_image.async_write_ha_state()
|
||||
# Two blocks to ensure the frame is written
|
||||
await hass.async_block_till_done()
|
||||
await hass.async_block_till_done()
|
||||
|
||||
with patch.object(mock_image, "async_image", return_value=b"") as mock:
|
||||
# Simulate a "keep alive" frame
|
||||
freezer.tick(55)
|
||||
async_fire_time_changed(hass)
|
||||
# Two blocks to ensure the frame is written
|
||||
await hass.async_block_till_done()
|
||||
await hass.async_block_till_done()
|
||||
mock.assert_called_once()
|
||||
|
||||
with patch.object(mock_image, "async_image", return_value=None):
|
||||
freezer.tick(55)
|
||||
async_fire_time_changed(hass)
|
||||
# Two blocks to ensure the frame is written
|
||||
await hass.async_block_till_done()
|
||||
await hass.async_block_till_done()
|
||||
|
||||
await close_future
|
||||
|
||||
|
||||
async def test_snapshot_service(hass: HomeAssistant) -> None:
|
||||
"""Test snapshot service."""
|
||||
mopen = mock_open()
|
||||
mock_integration(hass, MockModule(domain="test"))
|
||||
mock_platform(hass, "test.image", MockImagePlatform([MockImageSyncEntity(hass)]))
|
||||
assert await async_setup_component(
|
||||
hass, image.DOMAIN, {"image": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
with (
|
||||
patch("homeassistant.components.image.open", mopen, create=True),
|
||||
patch("homeassistant.components.image.os.makedirs"),
|
||||
patch.object(hass.config, "is_allowed_path", return_value=True),
|
||||
):
|
||||
await hass.services.async_call(
|
||||
image.DOMAIN,
|
||||
image.SERVICE_SNAPSHOT,
|
||||
{
|
||||
ATTR_ENTITY_ID: "image.test",
|
||||
image.ATTR_FILENAME: "/test/snapshot.jpg",
|
||||
},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
mock_write = mopen().write
|
||||
|
||||
assert len(mock_write.mock_calls) == 1
|
||||
assert mock_write.mock_calls[0][1][0] == b"Test"
|
||||
|
||||
|
||||
async def test_snapshot_service_no_image(hass: HomeAssistant) -> None:
|
||||
"""Test snapshot service with no image."""
|
||||
mopen = mock_open()
|
||||
mock_integration(hass, MockModule(domain="test"))
|
||||
mock_platform(hass, "test.image", MockImagePlatform([MockImageNoDataEntity(hass)]))
|
||||
assert await async_setup_component(
|
||||
hass, image.DOMAIN, {"image": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
with (
|
||||
patch("homeassistant.components.image.open", mopen, create=True),
|
||||
patch(
|
||||
"homeassistant.components.image.os.makedirs",
|
||||
),
|
||||
patch.object(hass.config, "is_allowed_path", return_value=True),
|
||||
):
|
||||
await hass.services.async_call(
|
||||
image.DOMAIN,
|
||||
image.SERVICE_SNAPSHOT,
|
||||
{
|
||||
ATTR_ENTITY_ID: "image.test",
|
||||
image.ATTR_FILENAME: "/test/snapshot.jpg",
|
||||
},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
mock_write = mopen().write
|
||||
|
||||
assert len(mock_write.mock_calls) == 0
|
||||
|
||||
|
||||
async def test_snapshot_service_not_allowed_path(hass: HomeAssistant) -> None:
|
||||
"""Test snapshot service with a not allowed path."""
|
||||
mock_integration(hass, MockModule(domain="test"))
|
||||
mock_platform(hass, "test.image", MockImagePlatform([MockURLImageEntity(hass)]))
|
||||
assert await async_setup_component(
|
||||
hass, image.DOMAIN, {"image": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
with pytest.raises(HomeAssistantError, match="/test/snapshot.jpg"):
|
||||
await hass.services.async_call(
|
||||
image.DOMAIN,
|
||||
image.SERVICE_SNAPSHOT,
|
||||
{
|
||||
ATTR_ENTITY_ID: "image.test",
|
||||
image.ATTR_FILENAME: "/test/snapshot.jpg",
|
||||
},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
|
||||
async def test_snapshot_service_os_error(hass: HomeAssistant) -> None:
|
||||
"""Test snapshot service with os error."""
|
||||
mock_integration(hass, MockModule(domain="test"))
|
||||
mock_platform(hass, "test.image", MockImagePlatform([MockImageSyncEntity(hass)]))
|
||||
assert await async_setup_component(
|
||||
hass, image.DOMAIN, {"image": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
with (
|
||||
patch.object(hass.config, "is_allowed_path", return_value=True),
|
||||
patch("os.makedirs", side_effect=OSError),
|
||||
pytest.raises(HomeAssistantError),
|
||||
):
|
||||
await hass.services.async_call(
|
||||
image.DOMAIN,
|
||||
image.SERVICE_SNAPSHOT,
|
||||
{
|
||||
ATTR_ENTITY_ID: "image.test",
|
||||
image.ATTR_FILENAME: "/test/snapshot.jpg",
|
||||
},
|
||||
blocking=True,
|
||||
)
|
||||
45
home-assistant/tests/components/image/test_media_source.py
Normal file
45
home-assistant/tests/components/image/test_media_source.py
Normal file
@@ -0,0 +1,45 @@
|
||||
"""Test image media source."""
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components import media_source
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def setup_media_source(hass: HomeAssistant) -> None:
|
||||
"""Set up media source."""
|
||||
assert await async_setup_component(hass, "media_source", {})
|
||||
|
||||
|
||||
async def test_browsing(hass: HomeAssistant, mock_image_platform) -> None:
|
||||
"""Test browsing image media source."""
|
||||
item = await media_source.async_browse_media(hass, "media-source://image")
|
||||
assert item is not None
|
||||
assert item.title == "Image"
|
||||
assert len(item.children) == 1
|
||||
assert item.children[0].media_content_type == "image/jpeg"
|
||||
|
||||
|
||||
async def test_resolving(hass: HomeAssistant, mock_image_platform) -> None:
|
||||
"""Test resolving."""
|
||||
item = await media_source.async_resolve_media(
|
||||
hass, "media-source://image/image.test", None
|
||||
)
|
||||
assert item is not None
|
||||
assert item.url == "/api/image_proxy_stream/image.test"
|
||||
assert item.mime_type == "image/jpeg"
|
||||
|
||||
|
||||
async def test_resolving_non_existing_camera(
|
||||
hass: HomeAssistant, mock_image_platform
|
||||
) -> None:
|
||||
"""Test resolving."""
|
||||
with pytest.raises(
|
||||
media_source.Unresolvable,
|
||||
match="Could not resolve media item: image.non_existing",
|
||||
):
|
||||
await media_source.async_resolve_media(
|
||||
hass, "media-source://image/image.non_existing", None
|
||||
)
|
||||
41
home-assistant/tests/components/image/test_recorder.py
Normal file
41
home-assistant/tests/components/image/test_recorder.py
Normal file
@@ -0,0 +1,41 @@
|
||||
"""The tests for image recorder."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
from homeassistant.components.recorder import Recorder
|
||||
from homeassistant.components.recorder.history import get_significant_states
|
||||
from homeassistant.const import (
|
||||
ATTR_ATTRIBUTION,
|
||||
ATTR_ENTITY_PICTURE,
|
||||
ATTR_FRIENDLY_NAME,
|
||||
ATTR_SUPPORTED_FEATURES,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from tests.common import async_fire_time_changed
|
||||
from tests.components.recorder.common import async_wait_recording_done
|
||||
|
||||
|
||||
async def test_exclude_attributes(
|
||||
recorder_mock: Recorder, hass: HomeAssistant, mock_image_platform
|
||||
) -> None:
|
||||
"""Test camera registered attributes to be excluded."""
|
||||
now = dt_util.utcnow()
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=5))
|
||||
await hass.async_block_till_done()
|
||||
await async_wait_recording_done(hass)
|
||||
|
||||
states = await hass.async_add_executor_job(
|
||||
get_significant_states, hass, now, None, hass.states.async_entity_ids()
|
||||
)
|
||||
assert len(states) == 1
|
||||
for entity_states in states.values():
|
||||
for state in entity_states:
|
||||
assert "access_token" not in state.attributes
|
||||
assert ATTR_ENTITY_PICTURE not in state.attributes
|
||||
assert ATTR_ATTRIBUTION not in state.attributes
|
||||
assert ATTR_SUPPORTED_FEATURES not in state.attributes
|
||||
assert ATTR_FRIENDLY_NAME in state.attributes
|
||||
Reference in New Issue
Block a user