init home-assistant
This commit is contained in:
1
home-assistant/tests/components/camera/__init__.py
Normal file
1
home-assistant/tests/components/camera/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""The tests for camera platforms."""
|
||||
75
home-assistant/tests/components/camera/common.py
Normal file
75
home-assistant/tests/components/camera/common.py
Normal file
@@ -0,0 +1,75 @@
|
||||
"""Collection of helper methods.
|
||||
|
||||
All containing methods are legacy helpers that should not be used by new
|
||||
components. Instead call the service directly.
|
||||
"""
|
||||
|
||||
from unittest.mock import Mock
|
||||
|
||||
from webrtc_models import RTCIceCandidateInit
|
||||
|
||||
from homeassistant.components.camera import (
|
||||
Camera,
|
||||
CameraWebRTCProvider,
|
||||
WebRTCAnswer,
|
||||
WebRTCSendMessage,
|
||||
)
|
||||
from homeassistant.core import callback
|
||||
|
||||
EMPTY_8_6_JPEG = b"empty_8_6"
|
||||
WEBRTC_ANSWER = "a=sendonly"
|
||||
STREAM_SOURCE = "rtsp://127.0.0.1/stream"
|
||||
|
||||
|
||||
def mock_turbo_jpeg(
|
||||
first_width=None, second_width=None, first_height=None, second_height=None
|
||||
):
|
||||
"""Mock a TurboJPEG instance."""
|
||||
mocked_turbo_jpeg = Mock()
|
||||
mocked_turbo_jpeg.decode_header.side_effect = [
|
||||
(first_width, first_height, 0, 0),
|
||||
(second_width, second_height, 0, 0),
|
||||
]
|
||||
mocked_turbo_jpeg.scale_with_quality.return_value = EMPTY_8_6_JPEG
|
||||
mocked_turbo_jpeg.encode.return_value = EMPTY_8_6_JPEG
|
||||
return mocked_turbo_jpeg
|
||||
|
||||
|
||||
class SomeTestProvider(CameraWebRTCProvider):
|
||||
"""Test provider."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Initialize the provider."""
|
||||
self._is_supported = True
|
||||
|
||||
@property
|
||||
def domain(self) -> str:
|
||||
"""Return the integration domain of the provider."""
|
||||
return "some_test"
|
||||
|
||||
@callback
|
||||
def async_is_supported(self, stream_source: str) -> bool:
|
||||
"""Determine if the provider supports the stream source."""
|
||||
return self._is_supported
|
||||
|
||||
async def async_handle_async_webrtc_offer(
|
||||
self,
|
||||
camera: Camera,
|
||||
offer_sdp: str,
|
||||
session_id: str,
|
||||
send_message: WebRTCSendMessage,
|
||||
) -> None:
|
||||
"""Handle the WebRTC offer and return the answer via the provided callback.
|
||||
|
||||
Return value determines if the offer was handled successfully.
|
||||
"""
|
||||
send_message(WebRTCAnswer(answer="answer"))
|
||||
|
||||
async def async_on_webrtc_candidate(
|
||||
self, session_id: str, candidate: RTCIceCandidateInit
|
||||
) -> None:
|
||||
"""Handle the WebRTC candidate."""
|
||||
|
||||
@callback
|
||||
def async_close_session(self, session_id: str) -> None:
|
||||
"""Close the session."""
|
||||
244
home-assistant/tests/components/camera/conftest.py
Normal file
244
home-assistant/tests/components/camera/conftest.py
Normal file
@@ -0,0 +1,244 @@
|
||||
"""Test helpers for camera."""
|
||||
|
||||
from collections.abc import AsyncGenerator, Generator
|
||||
from unittest.mock import AsyncMock, Mock, PropertyMock, patch
|
||||
|
||||
import pytest
|
||||
from webrtc_models import RTCIceCandidateInit
|
||||
|
||||
from homeassistant.components import camera
|
||||
from homeassistant.components.camera.const import StreamType
|
||||
from homeassistant.components.camera.webrtc import WebRTCAnswer, WebRTCSendMessage
|
||||
from homeassistant.config_entries import ConfigEntry, ConfigFlow
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from .common import STREAM_SOURCE, WEBRTC_ANSWER, SomeTestProvider
|
||||
|
||||
from tests.common import (
|
||||
MockConfigEntry,
|
||||
MockModule,
|
||||
mock_config_flow,
|
||||
mock_integration,
|
||||
mock_platform,
|
||||
setup_test_component_platform,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def setup_homeassistant(hass: HomeAssistant) -> None:
|
||||
"""Set up the homeassistant integration."""
|
||||
await async_setup_component(hass, "homeassistant", {})
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def camera_only() -> Generator[None]:
|
||||
"""Enable only the camera platform."""
|
||||
with patch(
|
||||
"homeassistant.components.demo.COMPONENTS_WITH_CONFIG_ENTRY_DEMO_PLATFORM",
|
||||
[Platform.CAMERA],
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="mock_camera")
|
||||
async def mock_camera_fixture(hass: HomeAssistant) -> AsyncGenerator[None]:
|
||||
"""Initialize a demo camera platform."""
|
||||
assert await async_setup_component(
|
||||
hass, "camera", {camera.DOMAIN: {"platform": "demo"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.demo.camera.Path.read_bytes",
|
||||
return_value=b"Test",
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="mock_camera_hls")
|
||||
def mock_camera_hls_fixture(mock_camera: None) -> Generator[None]:
|
||||
"""Initialize a demo camera platform with HLS."""
|
||||
with patch(
|
||||
"homeassistant.components.camera.Camera.camera_capabilities",
|
||||
new_callable=PropertyMock(
|
||||
return_value=camera.CameraCapabilities({StreamType.HLS})
|
||||
),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def mock_camera_webrtc(
|
||||
mock_camera: None,
|
||||
) -> AsyncGenerator[None]:
|
||||
"""Initialize a demo camera platform with WebRTC."""
|
||||
|
||||
async def async_handle_async_webrtc_offer(
|
||||
offer_sdp: str, session_id: str, send_message: WebRTCSendMessage
|
||||
) -> None:
|
||||
send_message(WebRTCAnswer(WEBRTC_ANSWER))
|
||||
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.camera.Camera.async_handle_async_webrtc_offer",
|
||||
side_effect=async_handle_async_webrtc_offer,
|
||||
),
|
||||
patch(
|
||||
"homeassistant.components.camera.Camera.camera_capabilities",
|
||||
new_callable=PropertyMock(
|
||||
return_value=camera.CameraCapabilities({StreamType.WEB_RTC})
|
||||
),
|
||||
),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="mock_camera_with_device")
|
||||
def mock_camera_with_device_fixture() -> Generator[None]:
|
||||
"""Initialize a demo camera platform with a device."""
|
||||
dev_info = DeviceInfo(
|
||||
identifiers={("camera", "test_unique_id")},
|
||||
name="Test Camera Device",
|
||||
)
|
||||
|
||||
class UniqueIdMock(PropertyMock):
|
||||
def __get__(self, obj, obj_type=None):
|
||||
return obj.name
|
||||
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.camera.Camera.has_entity_name",
|
||||
new_callable=PropertyMock(return_value=True),
|
||||
),
|
||||
patch("homeassistant.components.camera.Camera.unique_id", new=UniqueIdMock()),
|
||||
patch(
|
||||
"homeassistant.components.camera.Camera.device_info",
|
||||
new_callable=PropertyMock(return_value=dev_info),
|
||||
),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="mock_camera_with_no_name")
|
||||
def mock_camera_with_no_name_fixture(mock_camera_with_device: None) -> Generator[None]:
|
||||
"""Initialize a demo camera platform with a device and no name."""
|
||||
with patch(
|
||||
"homeassistant.components.camera.Camera._attr_name",
|
||||
new_callable=PropertyMock(return_value=None),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="mock_stream")
|
||||
async def mock_stream_fixture(hass: HomeAssistant) -> None:
|
||||
"""Initialize a demo camera platform with streaming."""
|
||||
assert await async_setup_component(hass, "stream", {"stream": {}})
|
||||
|
||||
|
||||
@pytest.fixture(name="mock_stream_source")
|
||||
def mock_stream_source_fixture() -> Generator[AsyncMock]:
|
||||
"""Fixture to create an RTSP stream source."""
|
||||
with patch(
|
||||
"homeassistant.components.camera.Camera.stream_source",
|
||||
return_value=STREAM_SOURCE,
|
||||
) as mock_stream_source:
|
||||
yield mock_stream_source
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def mock_test_webrtc_cameras(hass: HomeAssistant) -> None:
|
||||
"""Initialize test WebRTC cameras with native RTC support."""
|
||||
|
||||
# Cannot use the fixture mock_camera_web_rtc as it's mocking Camera.async_handle_web_rtc_offer
|
||||
# and native support is checked by verify the function "async_handle_web_rtc_offer" was
|
||||
# overwritten(implemented) or not
|
||||
class BaseCamera(camera.Camera):
|
||||
"""Base Camera."""
|
||||
|
||||
_attr_supported_features: camera.CameraEntityFeature = (
|
||||
camera.CameraEntityFeature.STREAM
|
||||
)
|
||||
|
||||
async def stream_source(self) -> str | None:
|
||||
return STREAM_SOURCE
|
||||
|
||||
class SyncCamera(BaseCamera):
|
||||
"""Mock Camera with native sync WebRTC support."""
|
||||
|
||||
_attr_name = "Sync"
|
||||
|
||||
async def async_handle_web_rtc_offer(self, offer_sdp: str) -> str | None:
|
||||
return WEBRTC_ANSWER
|
||||
|
||||
class AsyncCamera(BaseCamera):
|
||||
"""Mock Camera with native async WebRTC support."""
|
||||
|
||||
_attr_name = "Async"
|
||||
|
||||
async def async_handle_async_webrtc_offer(
|
||||
self, offer_sdp: str, session_id: str, send_message: WebRTCSendMessage
|
||||
) -> None:
|
||||
send_message(WebRTCAnswer(WEBRTC_ANSWER))
|
||||
|
||||
async def async_on_webrtc_candidate(
|
||||
self, session_id: str, candidate: RTCIceCandidateInit
|
||||
) -> None:
|
||||
"""Handle a WebRTC candidate."""
|
||||
# Do nothing
|
||||
|
||||
domain = "test"
|
||||
|
||||
entry = MockConfigEntry(domain=domain)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
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, [camera.DOMAIN]
|
||||
)
|
||||
return True
|
||||
|
||||
async def async_unload_entry_init(
|
||||
hass: HomeAssistant, config_entry: ConfigEntry
|
||||
) -> bool:
|
||||
"""Unload test config entry."""
|
||||
await hass.config_entries.async_forward_entry_unload(
|
||||
config_entry, camera.DOMAIN
|
||||
)
|
||||
return True
|
||||
|
||||
mock_integration(
|
||||
hass,
|
||||
MockModule(
|
||||
domain,
|
||||
async_setup_entry=async_setup_entry_init,
|
||||
async_unload_entry=async_unload_entry_init,
|
||||
),
|
||||
)
|
||||
setup_test_component_platform(
|
||||
hass, camera.DOMAIN, [SyncCamera(), AsyncCamera()], from_config_entry=True
|
||||
)
|
||||
mock_platform(hass, f"{domain}.config_flow", Mock())
|
||||
|
||||
with mock_config_flow(domain, ConfigFlow):
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def register_test_provider(
|
||||
hass: HomeAssistant,
|
||||
) -> AsyncGenerator[SomeTestProvider]:
|
||||
"""Add WebRTC test provider."""
|
||||
await async_setup_component(hass, "camera", {})
|
||||
|
||||
provider = SomeTestProvider()
|
||||
unsub = camera.async_register_webrtc_provider(hass, provider)
|
||||
await hass.async_block_till_done()
|
||||
yield provider
|
||||
unsub()
|
||||
127
home-assistant/tests/components/camera/snapshots/test_init.ambr
Normal file
127
home-assistant/tests/components/camera/snapshots/test_init.ambr
Normal file
@@ -0,0 +1,127 @@
|
||||
# serializer version: 1
|
||||
# name: test_record_service[/test/recording_{{ entity_id }}.mpg-/test/recording_<entity camera.demo_camera=streaming>.mpg-expected_issues1]
|
||||
IssueRegistryItemSnapshot({
|
||||
'active': True,
|
||||
'breaks_in_ha_version': '2025.6.0',
|
||||
'created': <ANY>,
|
||||
'data': None,
|
||||
'dismissed_version': None,
|
||||
'domain': 'camera',
|
||||
'is_fixable': True,
|
||||
'is_persistent': False,
|
||||
'issue_domain': None,
|
||||
'issue_id': 'deprecated_filename_template_camera.demo_camera_record',
|
||||
'learn_more_url': None,
|
||||
'severity': <IssueSeverity.WARNING: 'warning'>,
|
||||
'translation_key': 'deprecated_filename_template',
|
||||
'translation_placeholders': dict({
|
||||
'entity_id': 'camera.demo_camera',
|
||||
'service': 'camera.record',
|
||||
}),
|
||||
})
|
||||
# ---
|
||||
# name: test_record_service[/test/recording_{{ entity_id.entity_id }}.mpg-/test/recording_camera.demo_camera.mpg-expected_issues3]
|
||||
IssueRegistryItemSnapshot({
|
||||
'active': True,
|
||||
'breaks_in_ha_version': '2025.6.0',
|
||||
'created': <ANY>,
|
||||
'data': None,
|
||||
'dismissed_version': None,
|
||||
'domain': 'camera',
|
||||
'is_fixable': True,
|
||||
'is_persistent': False,
|
||||
'issue_domain': None,
|
||||
'issue_id': 'deprecated_filename_template_camera.demo_camera_record',
|
||||
'learn_more_url': None,
|
||||
'severity': <IssueSeverity.WARNING: 'warning'>,
|
||||
'translation_key': 'deprecated_filename_template',
|
||||
'translation_placeholders': dict({
|
||||
'entity_id': 'camera.demo_camera',
|
||||
'service': 'camera.record',
|
||||
}),
|
||||
})
|
||||
# ---
|
||||
# name: test_record_service[/test/recording_{{ entity_id.name }}.mpg-/test/recording_Demo camera.mpg-expected_issues2]
|
||||
IssueRegistryItemSnapshot({
|
||||
'active': True,
|
||||
'breaks_in_ha_version': '2025.6.0',
|
||||
'created': <ANY>,
|
||||
'data': None,
|
||||
'dismissed_version': None,
|
||||
'domain': 'camera',
|
||||
'is_fixable': True,
|
||||
'is_persistent': False,
|
||||
'issue_domain': None,
|
||||
'issue_id': 'deprecated_filename_template_camera.demo_camera_record',
|
||||
'learn_more_url': None,
|
||||
'severity': <IssueSeverity.WARNING: 'warning'>,
|
||||
'translation_key': 'deprecated_filename_template',
|
||||
'translation_placeholders': dict({
|
||||
'entity_id': 'camera.demo_camera',
|
||||
'service': 'camera.record',
|
||||
}),
|
||||
})
|
||||
# ---
|
||||
# name: test_snapshot_service[/test/snapshot_{{ entity_id }}.jpg-/test/snapshot_<entity camera.demo_camera=streaming>.jpg-expected_issues1]
|
||||
IssueRegistryItemSnapshot({
|
||||
'active': True,
|
||||
'breaks_in_ha_version': '2025.6.0',
|
||||
'created': <ANY>,
|
||||
'data': None,
|
||||
'dismissed_version': None,
|
||||
'domain': 'camera',
|
||||
'is_fixable': True,
|
||||
'is_persistent': False,
|
||||
'issue_domain': None,
|
||||
'issue_id': 'deprecated_filename_template_camera.demo_camera_snapshot',
|
||||
'learn_more_url': None,
|
||||
'severity': <IssueSeverity.WARNING: 'warning'>,
|
||||
'translation_key': 'deprecated_filename_template',
|
||||
'translation_placeholders': dict({
|
||||
'entity_id': 'camera.demo_camera',
|
||||
'service': 'camera.snapshot',
|
||||
}),
|
||||
})
|
||||
# ---
|
||||
# name: test_snapshot_service[/test/snapshot_{{ entity_id.entity_id }}.jpg-/test/snapshot_camera.demo_camera.jpg-expected_issues3]
|
||||
IssueRegistryItemSnapshot({
|
||||
'active': True,
|
||||
'breaks_in_ha_version': '2025.6.0',
|
||||
'created': <ANY>,
|
||||
'data': None,
|
||||
'dismissed_version': None,
|
||||
'domain': 'camera',
|
||||
'is_fixable': True,
|
||||
'is_persistent': False,
|
||||
'issue_domain': None,
|
||||
'issue_id': 'deprecated_filename_template_camera.demo_camera_snapshot',
|
||||
'learn_more_url': None,
|
||||
'severity': <IssueSeverity.WARNING: 'warning'>,
|
||||
'translation_key': 'deprecated_filename_template',
|
||||
'translation_placeholders': dict({
|
||||
'entity_id': 'camera.demo_camera',
|
||||
'service': 'camera.snapshot',
|
||||
}),
|
||||
})
|
||||
# ---
|
||||
# name: test_snapshot_service[/test/snapshot_{{ entity_id.name }}.jpg-/test/snapshot_Demo camera.jpg-expected_issues2]
|
||||
IssueRegistryItemSnapshot({
|
||||
'active': True,
|
||||
'breaks_in_ha_version': '2025.6.0',
|
||||
'created': <ANY>,
|
||||
'data': None,
|
||||
'dismissed_version': None,
|
||||
'domain': 'camera',
|
||||
'is_fixable': True,
|
||||
'is_persistent': False,
|
||||
'issue_domain': None,
|
||||
'issue_id': 'deprecated_filename_template_camera.demo_camera_snapshot',
|
||||
'learn_more_url': None,
|
||||
'severity': <IssueSeverity.WARNING: 'warning'>,
|
||||
'translation_key': 'deprecated_filename_template',
|
||||
'translation_placeholders': dict({
|
||||
'entity_id': 'camera.demo_camera',
|
||||
'service': 'camera.snapshot',
|
||||
}),
|
||||
})
|
||||
# ---
|
||||
131
home-assistant/tests/components/camera/test_img_util.py
Normal file
131
home-assistant/tests/components/camera/test_img_util.py
Normal file
@@ -0,0 +1,131 @@
|
||||
"""Test img_util module."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from turbojpeg import TurboJPEG
|
||||
|
||||
from homeassistant.components.camera import Image
|
||||
from homeassistant.components.camera.img_util import (
|
||||
TurboJPEGSingleton,
|
||||
find_supported_scaling_factor,
|
||||
scale_jpeg_camera_image,
|
||||
)
|
||||
|
||||
from .common import EMPTY_8_6_JPEG, mock_turbo_jpeg
|
||||
|
||||
EMPTY_16_12_JPEG = b"empty_16_12"
|
||||
|
||||
|
||||
def _clear_turbojpeg_singleton():
|
||||
TurboJPEGSingleton.__instance = None
|
||||
|
||||
|
||||
def _reset_turbojpeg_singleton():
|
||||
TurboJPEGSingleton.__instance = TurboJPEG()
|
||||
|
||||
|
||||
def test_turbojpeg_singleton() -> None:
|
||||
"""Verify the instance always gives back the same."""
|
||||
_clear_turbojpeg_singleton()
|
||||
assert TurboJPEGSingleton.instance() == TurboJPEGSingleton.instance()
|
||||
|
||||
|
||||
def test_scale_jpeg_camera_image() -> None:
|
||||
"""Test we can scale a jpeg image."""
|
||||
_clear_turbojpeg_singleton()
|
||||
|
||||
camera_image = Image("image/jpeg", EMPTY_16_12_JPEG)
|
||||
|
||||
turbo_jpeg = mock_turbo_jpeg(first_width=16, first_height=12)
|
||||
with patch(
|
||||
"homeassistant.components.camera.img_util.TurboJPEG", return_value=False
|
||||
):
|
||||
TurboJPEGSingleton()
|
||||
assert scale_jpeg_camera_image(camera_image, 16, 12) == camera_image.content
|
||||
|
||||
turbo_jpeg = mock_turbo_jpeg(first_width=16, first_height=12)
|
||||
turbo_jpeg.decode_header.side_effect = OSError
|
||||
with patch(
|
||||
"homeassistant.components.camera.img_util.TurboJPEG", return_value=turbo_jpeg
|
||||
):
|
||||
TurboJPEGSingleton()
|
||||
assert scale_jpeg_camera_image(camera_image, 16, 12) == camera_image.content
|
||||
|
||||
turbo_jpeg = mock_turbo_jpeg(first_width=16, first_height=12)
|
||||
with patch(
|
||||
"homeassistant.components.camera.img_util.TurboJPEG", return_value=turbo_jpeg
|
||||
):
|
||||
TurboJPEGSingleton()
|
||||
assert scale_jpeg_camera_image(camera_image, 16, 12) == EMPTY_16_12_JPEG
|
||||
|
||||
turbo_jpeg = mock_turbo_jpeg(
|
||||
first_width=16, first_height=12, second_width=8, second_height=6
|
||||
)
|
||||
with patch(
|
||||
"homeassistant.components.camera.img_util.TurboJPEG", return_value=turbo_jpeg
|
||||
):
|
||||
TurboJPEGSingleton()
|
||||
jpeg_bytes = scale_jpeg_camera_image(camera_image, 8, 6)
|
||||
|
||||
assert jpeg_bytes == EMPTY_8_6_JPEG
|
||||
|
||||
turbo_jpeg = mock_turbo_jpeg(
|
||||
first_width=640, first_height=480, second_width=640, second_height=480
|
||||
)
|
||||
with patch(
|
||||
"homeassistant.components.camera.img_util.TurboJPEG", return_value=turbo_jpeg
|
||||
):
|
||||
TurboJPEGSingleton()
|
||||
jpeg_bytes = scale_jpeg_camera_image(camera_image, 320, 480)
|
||||
|
||||
assert jpeg_bytes == EMPTY_16_12_JPEG
|
||||
|
||||
|
||||
def test_turbojpeg_load_failure() -> None:
|
||||
"""Handle libjpegturbo not being installed."""
|
||||
_clear_turbojpeg_singleton()
|
||||
with patch(
|
||||
"homeassistant.components.camera.img_util.TurboJPEG", side_effect=Exception
|
||||
):
|
||||
TurboJPEGSingleton()
|
||||
assert TurboJPEGSingleton.instance() is False
|
||||
|
||||
_clear_turbojpeg_singleton()
|
||||
TurboJPEGSingleton()
|
||||
assert TurboJPEGSingleton.instance() is not None
|
||||
|
||||
|
||||
SCALE_TEST_EXPECTED = [
|
||||
(5782, 3946, 640, 480, (1, 8)), # Maximum scale
|
||||
(1600, 1200, 640, 480, (1, 2)), # Equal scale for width and height
|
||||
(1600, 1200, 1400, 1050, (7, 8)), # Equal scale for width and height
|
||||
(1600, 1200, 1200, 900, (3, 4)), # Equal scale for width and height
|
||||
(1600, 1200, 1000, 750, (5, 8)), # Equal scale for width and height
|
||||
(1600, 1200, 600, 450, (3, 8)), # Equal scale for width and height
|
||||
(1600, 1200, 400, 300, (1, 4)), # Equal scale for width and height
|
||||
(1600, 1200, 401, 300, (3, 8)), # Width is just a little to big, next size up
|
||||
(640, 480, 330, 200, (5, 8)), # Preserve width clarity
|
||||
(640, 480, 300, 260, (5, 8)), # Preserve height clarity
|
||||
(640, 480, 1200, 480, None), # Request larger width - no scaling
|
||||
(640, 480, 640, 480, None), # Request same - no scaling
|
||||
(640, 480, 640, 270, None), # Request smaller height - no scaling
|
||||
(640, 480, 320, 480, None), # Request smaller width - no scaling
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("image_width", "image_height", "input_width", "input_height", "scaling_factor"),
|
||||
SCALE_TEST_EXPECTED,
|
||||
)
|
||||
def test_find_supported_scaling_factor(
|
||||
image_width, image_height, input_width, input_height, scaling_factor
|
||||
) -> None:
|
||||
"""Test we always get an image of at least the size we ask if its big enough."""
|
||||
|
||||
assert (
|
||||
find_supported_scaling_factor(
|
||||
image_width, image_height, input_width, input_height
|
||||
)
|
||||
== scaling_factor
|
||||
)
|
||||
1048
home-assistant/tests/components/camera/test_init.py
Normal file
1048
home-assistant/tests/components/camera/test_init.py
Normal file
File diff suppressed because it is too large
Load Diff
151
home-assistant/tests/components/camera/test_media_source.py
Normal file
151
home-assistant/tests/components/camera/test_media_source.py
Normal file
@@ -0,0 +1,151 @@
|
||||
"""Test camera media source."""
|
||||
|
||||
from unittest.mock import PropertyMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components import media_source
|
||||
from homeassistant.components.camera import CameraCapabilities
|
||||
from homeassistant.components.camera.const import StreamType
|
||||
from homeassistant.components.stream import FORMAT_CONTENT_TYPE
|
||||
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", {})
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_camera_with_device", "mock_camera")
|
||||
async def test_device_with_device(hass: HomeAssistant) -> None:
|
||||
"""Test browsing when camera has a device and a name."""
|
||||
item = await media_source.async_browse_media(hass, "media-source://camera")
|
||||
assert item.not_shown == 2
|
||||
assert len(item.children) == 1
|
||||
assert item.children[0].title == "Test Camera Device Demo camera without stream"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_camera_with_no_name", "mock_camera")
|
||||
async def test_device_with_no_name(hass: HomeAssistant) -> None:
|
||||
"""Test browsing when camera has device and name == None."""
|
||||
item = await media_source.async_browse_media(hass, "media-source://camera")
|
||||
assert item.not_shown == 2
|
||||
assert len(item.children) == 1
|
||||
assert item.children[0].title == "Test Camera Device Demo camera without stream"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_camera_hls")
|
||||
async def test_browsing_hls(hass: HomeAssistant) -> None:
|
||||
"""Test browsing HLS camera media source."""
|
||||
item = await media_source.async_browse_media(hass, "media-source://camera")
|
||||
assert item is not None
|
||||
assert item.title == "Camera"
|
||||
assert len(item.children) == 0
|
||||
assert item.not_shown == 3
|
||||
|
||||
# Adding stream enables HLS camera
|
||||
hass.config.components.add("stream")
|
||||
|
||||
item = await media_source.async_browse_media(hass, "media-source://camera")
|
||||
assert item.not_shown == 0
|
||||
assert len(item.children) == 3
|
||||
assert item.children[0].media_content_type == FORMAT_CONTENT_TYPE["hls"]
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_camera")
|
||||
async def test_browsing_mjpeg(hass: HomeAssistant) -> None:
|
||||
"""Test browsing MJPEG camera media source."""
|
||||
item = await media_source.async_browse_media(hass, "media-source://camera")
|
||||
assert item is not None
|
||||
assert item.title == "Camera"
|
||||
assert len(item.children) == 1
|
||||
assert item.not_shown == 2
|
||||
assert item.children[0].media_content_type == "image/jpg"
|
||||
assert item.children[0].title == "Demo camera without stream"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_camera_webrtc")
|
||||
async def test_browsing_webrtc(hass: HomeAssistant) -> None:
|
||||
"""Test browsing WebRTC camera media source."""
|
||||
# 3 cameras:
|
||||
# one only supports WebRTC (no stream source)
|
||||
# one raises when getting the source
|
||||
# One has a stream source, and should be the only browsable one
|
||||
with patch(
|
||||
"homeassistant.components.camera.Camera.stream_source",
|
||||
side_effect=["test", None, Exception],
|
||||
):
|
||||
item = await media_source.async_browse_media(hass, "media-source://camera")
|
||||
assert item is not None
|
||||
assert item.title == "Camera"
|
||||
assert len(item.children) == 0
|
||||
assert item.not_shown == 3
|
||||
|
||||
# Adding stream enables HLS camera
|
||||
hass.config.components.add("stream")
|
||||
|
||||
item = await media_source.async_browse_media(hass, "media-source://camera")
|
||||
assert item.not_shown == 2
|
||||
assert len(item.children) == 1
|
||||
assert item.children[0].media_content_type == FORMAT_CONTENT_TYPE["hls"]
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_camera")
|
||||
async def test_resolving(hass: HomeAssistant) -> None:
|
||||
"""Test resolving."""
|
||||
# Adding stream enables HLS camera
|
||||
hass.config.components.add("stream")
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.camera.media_source._async_stream_endpoint_url",
|
||||
return_value="http://example.com/stream",
|
||||
):
|
||||
item = await media_source.async_resolve_media(
|
||||
hass, "media-source://camera/camera.demo_camera", None
|
||||
)
|
||||
assert item is not None
|
||||
assert item.url == "http://example.com/stream"
|
||||
assert item.mime_type == FORMAT_CONTENT_TYPE["hls"]
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_camera")
|
||||
async def test_resolving_errors(hass: HomeAssistant) -> None:
|
||||
"""Test resolving."""
|
||||
|
||||
with pytest.raises(media_source.Unresolvable) as exc_info:
|
||||
await media_source.async_resolve_media(
|
||||
hass, "media-source://camera/camera.demo_camera", None
|
||||
)
|
||||
assert str(exc_info.value) == "Stream integration not loaded"
|
||||
|
||||
hass.config.components.add("stream")
|
||||
|
||||
with pytest.raises(media_source.Unresolvable) as exc_info:
|
||||
await media_source.async_resolve_media(
|
||||
hass, "media-source://camera/camera.non_existing", None
|
||||
)
|
||||
assert str(exc_info.value) == "Could not resolve media item: camera.non_existing"
|
||||
|
||||
with (
|
||||
pytest.raises(media_source.Unresolvable) as exc_info,
|
||||
patch(
|
||||
"homeassistant.components.camera.Camera.camera_capabilities",
|
||||
new_callable=PropertyMock(
|
||||
return_value=CameraCapabilities({StreamType.WEB_RTC})
|
||||
),
|
||||
),
|
||||
):
|
||||
await media_source.async_resolve_media(
|
||||
hass, "media-source://camera/camera.demo_camera", None
|
||||
)
|
||||
assert str(exc_info.value) == "Camera does not support MJPEG or HLS streaming."
|
||||
|
||||
with pytest.raises(media_source.Unresolvable) as exc_info:
|
||||
await media_source.async_resolve_media(
|
||||
hass, "media-source://camera/camera.demo_camera", None
|
||||
)
|
||||
assert (
|
||||
str(exc_info.value) == "camera.demo_camera does not support play stream service"
|
||||
)
|
||||
53
home-assistant/tests/components/camera/test_recorder.py
Normal file
53
home-assistant/tests/components/camera/test_recorder.py
Normal file
@@ -0,0 +1,53 @@
|
||||
"""The tests for camera recorder."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components import camera
|
||||
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.setup import async_setup_component
|
||||
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
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def setup_homeassistant():
|
||||
"""Override the fixture in calendar.conftest."""
|
||||
|
||||
|
||||
async def test_exclude_attributes(recorder_mock: Recorder, hass: HomeAssistant) -> None:
|
||||
"""Test camera registered attributes to be excluded."""
|
||||
now = dt_util.utcnow()
|
||||
await async_setup_component(hass, "homeassistant", {})
|
||||
await async_setup_component(
|
||||
hass, camera.DOMAIN, {camera.DOMAIN: {"platform": "demo"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
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
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Test the Camera significant change platform."""
|
||||
|
||||
from homeassistant.components.camera import CameraState
|
||||
from homeassistant.components.camera.significant_change import (
|
||||
async_check_significant_change,
|
||||
)
|
||||
|
||||
|
||||
async def test_significant_change() -> None:
|
||||
"""Detect Camera significant changes."""
|
||||
attrs = {}
|
||||
assert not async_check_significant_change(
|
||||
None, CameraState.IDLE, attrs, CameraState.IDLE, attrs
|
||||
)
|
||||
assert not async_check_significant_change(
|
||||
None, CameraState.IDLE, attrs, CameraState.IDLE, {"dummy": "dummy"}
|
||||
)
|
||||
assert async_check_significant_change(
|
||||
None, CameraState.IDLE, attrs, CameraState.RECORDING, attrs
|
||||
)
|
||||
1302
home-assistant/tests/components/camera/test_webrtc.py
Normal file
1302
home-assistant/tests/components/camera/test_webrtc.py
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user