response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Patch Bond API device properties endpoint.
def patch_bond_device_properties(return_value=None): """Patch Bond API device properties endpoint.""" if return_value is None: return_value = {} return patch( "homeassistant.components.bond.Bond.device_properties", return_value=return_value, )
Patch Bond API device state endpoint.
def patch_bond_device_state(return_value=None, side_effect=None): """Patch Bond API device state endpoint.""" if return_value is None: return_value = {} return patch( "homeassistant.components.bond.Bond.device_state", return_value=return_value, side_effect=side_effect, )
Create a ceiling fan with given name.
def ceiling_fan(name: str): """Create a ceiling fan with given name.""" return { "name": name, "type": DeviceType.CEILING_FAN, "actions": ["SetSpeed", "SetDirection"], }
Create a ceiling fan with given name.
def ceiling_fan(name: str): """Create a ceiling fan with given name.""" return { "name": name, "type": DeviceType.CEILING_FAN, "actions": [Action.SET_SPEED, Action.SET_DIRECTION, Action.STOP], }
Create a light that can only increase or decrease brightness.
def light_brightness_increase_decrease_only(name: str): """Create a light that can only increase or decrease brightness.""" return { "name": name, "type": DeviceType.LIGHT, "actions": [ Action.TURN_LIGHT_ON, Action.TURN_LIGHT_OFF, Action.START_DIMMER, Action.START_INCREASING_BRIGHTNESS, Action.START_DECREASING_BRIGHTNESS, Action.STOP, ], }
Create a fireplace that can only increase or decrease flame.
def fireplace_increase_decrease_only(name: str): """Create a fireplace that can only increase or decrease flame.""" return { "name": name, "type": DeviceType.LIGHT, "actions": [ Action.INCREASE_FLAME, Action.DECREASE_FLAME, ], }
Create a light with a given name.
def light(name: str): """Create a light with a given name.""" return { "name": name, "type": DeviceType.LIGHT, "actions": [Action.TURN_LIGHT_ON, Action.TURN_LIGHT_OFF, Action.SET_BRIGHTNESS], }
Create motorized shades with given name.
def shades(name: str): """Create motorized shades with given name.""" return { "name": name, "type": DeviceType.MOTORIZED_SHADES, "actions": ["Open", "Close", "Hold"], }
Create motorized shades that supports set position.
def shades_with_position(name: str): """Create motorized shades that supports set position.""" return { "name": name, "type": DeviceType.MOTORIZED_SHADES, "actions": [Action.OPEN, Action.CLOSE, Action.HOLD, Action.SET_POSITION], }
Create motorized shades that only tilt.
def tilt_only_shades(name: str): """Create motorized shades that only tilt.""" return { "name": name, "type": DeviceType.MOTORIZED_SHADES, "actions": ["TiltOpen", "TiltClose", "Hold"], }
Create motorized shades with given name that can also tilt.
def tilt_shades(name: str): """Create motorized shades with given name that can also tilt.""" return { "name": name, "type": DeviceType.MOTORIZED_SHADES, "actions": ["Open", "Close", "Hold", "TiltOpen", "TiltClose", "Hold"], }
Create a ceiling fan with given name.
def ceiling_fan(name: str): """Create a ceiling fan with given name.""" return { "name": name, "type": DeviceType.CEILING_FAN, "actions": ["SetSpeed", "SetDirection"], }
Create a ceiling fan with given name with breeze support.
def ceiling_fan_with_breeze(name: str): """Create a ceiling fan with given name with breeze support.""" return { "name": name, "type": DeviceType.CEILING_FAN, "actions": ["SetSpeed", "SetDirection", "BreezeOn"], }
Create a light with a given name.
def light(name: str): """Create a light with a given name.""" return { "name": name, "type": DeviceType.LIGHT, "actions": [Action.TURN_LIGHT_ON, Action.TURN_LIGHT_OFF, Action.SET_BRIGHTNESS], }
Create a light with a given name.
def light_no_brightness(name: str): """Create a light with a given name.""" return { "name": name, "type": DeviceType.LIGHT, "actions": [Action.TURN_LIGHT_ON, Action.TURN_LIGHT_OFF], }
Create a ceiling fan (that has built-in light) with given name.
def ceiling_fan(name: str): """Create a ceiling fan (that has built-in light) with given name.""" return { "name": name, "type": DeviceType.CEILING_FAN, "actions": [Action.TURN_LIGHT_ON, Action.TURN_LIGHT_OFF], }
Create a ceiling fan (that has built-in light) with given name.
def dimmable_ceiling_fan(name: str): """Create a ceiling fan (that has built-in light) with given name.""" return { "name": name, "type": DeviceType.CEILING_FAN, "actions": [Action.TURN_LIGHT_ON, Action.TURN_LIGHT_OFF, Action.SET_BRIGHTNESS], }
Create a ceiling fan (that has built-in down light) with given name.
def down_light_ceiling_fan(name: str): """Create a ceiling fan (that has built-in down light) with given name.""" return { "name": name, "type": DeviceType.CEILING_FAN, "actions": [Action.TURN_DOWN_LIGHT_ON, Action.TURN_DOWN_LIGHT_OFF], }
Create a ceiling fan (that has built-in down light) with given name.
def up_light_ceiling_fan(name: str): """Create a ceiling fan (that has built-in down light) with given name.""" return { "name": name, "type": DeviceType.CEILING_FAN, "actions": [Action.TURN_UP_LIGHT_ON, Action.TURN_UP_LIGHT_OFF], }
Create a fireplace with given name.
def fireplace(name: str): """Create a fireplace with given name.""" return { "name": name, "type": DeviceType.FIREPLACE, "actions": [Action.TURN_ON, Action.TURN_OFF], }
Create a fireplace with given name.
def fireplace_with_light(name: str): """Create a fireplace with given name.""" return { "name": name, "type": DeviceType.FIREPLACE, "actions": [ Action.TURN_ON, Action.TURN_OFF, Action.TURN_LIGHT_ON, Action.TURN_LIGHT_OFF, ], }
Create a fireplace with given name.
def fireplace_with_light_supports_brightness(name: str): """Create a fireplace with given name.""" return { "name": name, "type": DeviceType.FIREPLACE, "actions": [ Action.TURN_ON, Action.TURN_OFF, Action.TURN_LIGHT_ON, Action.TURN_LIGHT_OFF, Action.SET_BRIGHTNESS, ], }
Create a light that can only increase or decrease brightness.
def light_brightness_increase_decrease_only(name: str): """Create a light that can only increase or decrease brightness.""" return { "name": name, "type": DeviceType.LIGHT, "actions": [ Action.TURN_LIGHT_ON, Action.TURN_LIGHT_OFF, Action.START_INCREASING_BRIGHTNESS, Action.START_DECREASING_BRIGHTNESS, Action.STOP, ], }
Create a generic device with given name.
def generic_device(name: str): """Create a generic device with given name.""" return {"name": name, "type": DeviceType.GENERIC_DEVICE}
Auto mock zeroconf.
def bosch_shc_mock_async_zeroconf(mock_async_zeroconf): """Auto mock zeroconf."""
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.braviatv.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.bring.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock a Bring client.
def mock_bring_client() -> Generator[AsyncMock, None, None]: """Mock a Bring client.""" with ( patch( "homeassistant.components.bring.Bring", autospec=True, ) as mock_client, patch( "homeassistant.components.bring.config_flow.Bring", new=mock_client, ), ): client = mock_client.return_value client.uuid = UUID client.login.return_value = True client.load_lists.return_value = {"lists": []} yield client
Mock bring configuration entry.
def mock_bring_config_entry() -> MockConfigEntry: """Mock bring configuration entry.""" return MockConfigEntry( domain=DOMAIN, data={CONF_EMAIL: EMAIL, CONF_PASSWORD: PASSWORD}, unique_id=UUID )
Mock broadlink heartbeat.
def mock_heartbeat(): """Mock broadlink heartbeat.""" with patch("homeassistant.components.broadlink.heartbeat.blk.ping"): yield
Mock broadlink entry setup.
def broadlink_setup_fixture(): """Mock broadlink entry setup.""" with ( patch("homeassistant.components.broadlink.async_setup", return_value=True), patch( "homeassistant.components.broadlink.async_setup_entry", return_value=True ), ): yield
Get a device by name.
def get_device(name): """Get a device by name.""" return BroadlinkDevice(name, *BROADLINK_DEVICES[name])
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.brother.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.brottsplatskartan.async_setup_entry", return_value=True, ) as mock_setup_entry: yield mock_setup_entry
Generate uuid for app-id.
def uuid_generator() -> Generator[AsyncMock, None, None]: """Generate uuid for app-id.""" with patch( "homeassistant.components.brottsplatskartan.config_flow.uuid.getnode", return_value="1234567890", ) as uuid_generator: yield uuid_generator
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.brunt.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="BSBLAN Setup", domain=DOMAIN, data={ CONF_HOST: "127.0.0.1", CONF_PORT: 80, CONF_PASSKEY: "1234", CONF_USERNAME: "admin", CONF_PASSWORD: "admin1234", }, unique_id="00:80:41:19:69:90", )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.bsblan.async_setup_entry", return_value=True ) as mock_setup: yield mock_setup
Return a mocked BSBLAN client.
def mock_bsblan(request: pytest.FixtureRequest) -> Generator[None, MagicMock, None]: """Return a mocked BSBLAN client.""" with ( patch("homeassistant.components.bsblan.BSBLAN", autospec=True) as bsblan_mock, patch("homeassistant.components.bsblan.config_flow.BSBLAN", new=bsblan_mock), ): bsblan = bsblan_mock.return_value bsblan.info.return_value = Info.parse_raw(load_fixture("info.json", DOMAIN)) bsblan.device.return_value = Device.parse_raw( load_fixture("device.json", DOMAIN) ) bsblan.state.return_value = State.parse_raw(load_fixture("state.json", DOMAIN)) yield bsblan
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Get device registry identifier for bthome_ble.
def get_device_id(mac: str) -> tuple[str, str]: """Get device registry identifier for bthome_ble.""" return (BLUETOOTH_DOMAIN, mac)
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Make a dummy advertisement.
def make_bthome_v1_adv(address: str, payload: bytes) -> BluetoothServiceInfoBleak: """Make a dummy advertisement.""" return BluetoothServiceInfoBleak( name="Test Device", address=address, device=generate_ble_device(address, None), rssi=-56, manufacturer_data={}, service_data={ "0000181c-0000-1000-8000-00805f9b34fb": payload, }, service_uuids=["0000181c-0000-1000-8000-00805f9b34fb"], source="local", advertisement=generate_advertisement_data(local_name="Test Device"), time=0, connectable=False, )
Make a dummy encrypted advertisement.
def make_encrypted_bthome_v1_adv( address: str, payload: bytes ) -> BluetoothServiceInfoBleak: """Make a dummy encrypted advertisement.""" return BluetoothServiceInfoBleak( name="ATC 8F80A5", address=address, device=generate_ble_device(address, None), rssi=-56, manufacturer_data={}, service_data={ "0000181e-0000-1000-8000-00805f9b34fb": payload, }, service_uuids=["0000181e-0000-1000-8000-00805f9b34fb"], source="local", advertisement=generate_advertisement_data(local_name="ATC 8F80A5"), time=0, connectable=False, )
Make a dummy advertisement.
def make_bthome_v2_adv(address: str, payload: bytes) -> BluetoothServiceInfoBleak: """Make a dummy advertisement.""" return BluetoothServiceInfoBleak( name="Test Device", address=address, device=generate_ble_device(address, None), rssi=-56, manufacturer_data={}, service_data={ "0000fcd2-0000-1000-8000-00805f9b34fb": payload, }, service_uuids=["0000fcd2-0000-1000-8000-00805f9b34fb"], source="local", advertisement=generate_advertisement_data(local_name="Test Device"), time=0, connectable=False, )
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.buienradar.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Build map URL.
def radar_map_url(country_code: str = "NL") -> str: """Build map URL.""" return f"https://api.buienradar.nl/image/1.0/RadarMap{country_code}?w=700&h=700"
Track calls to a mock service.
def calls(hass: HomeAssistant) -> list[ServiceCall]: """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Mock config flow.
def config_flow_fixture(hass: HomeAssistant) -> Generator[None, None, None]: """Mock config flow.""" mock_platform(hass, f"{TEST_DOMAIN}.config_flow") with mock_config_flow(TEST_DOMAIN, MockFlow): yield
Fixture to specify platforms to test.
def mock_platforms() -> list[Platform]: """Fixture to specify platforms to test.""" return []
Fixture to provide calendars returned by CalDAV client.
def mock_calendars() -> list[Mock]: """Fixture to provide calendars returned by CalDAV client.""" return []
Fixture to mock the DAVClient.
def mock_dav_client(calendars: list[Mock]) -> Mock: """Fixture to mock the DAVClient.""" with patch( "homeassistant.components.caldav.calendar.caldav.DAVClient" ) as mock_client: mock_client.return_value.principal.return_value.calendars.return_value = ( calendars ) yield mock_client
Fixture for a config entry.
def mock_config_entry() -> MockConfigEntry: """Fixture for a config entry.""" return MockConfigEntry( domain=DOMAIN, data={ CONF_URL: TEST_URL, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_VERIFY_SSL: True, }, )
Fixture to set up config entry platforms.
def platforms() -> list[Platform]: """Fixture to set up config entry platforms.""" return [Platform.CALENDAR]
Fixture to specify the Home Assistant timezone to use during the test.
def mock_tz() -> str | None: """Fixture to specify the Home Assistant timezone to use during the test.""" return None
Fixture to set the default TZ to the one requested.
def set_tz(hass: HomeAssistant, tz: str | None) -> None: """Fixture to set the default TZ to the one requested.""" if tz is not None: hass.config.set_time_zone(tz)
Mock the http component.
def mock_http(hass: HomeAssistant) -> None: """Mock the http component.""" hass.http = Mock()
Fixture to provide calendars returned by CalDAV client.
def mock_calendar_names() -> list[str]: """Fixture to provide calendars returned by CalDAV client.""" return ["Example"]
Fixture to provide calendars returned by CalDAV client.
def mock_calendars(calendar_names: list[str]) -> list[Mock]: """Fixture to provide calendars returned by CalDAV client.""" return [_mock_calendar(name) for name in calendar_names]
Fixture to return events for a specific calendar using the API.
def get_api_events( hass_client: ClientSessionGenerator, ) -> Callable[[str], Awaitable[dict[str, Any]]]: """Fixture to return events for a specific calendar using the API.""" async def api_call(entity_id: str) -> dict[str, Any]: client = await hass_client() response = await client.get( # The start/end times are arbitrary since they are ignored by `_mock_calendar` # which just returns all events for the calendar. f"/api/calendars/{entity_id}?start=2022-01-01&end=2022-01-01" ) assert response.status == HTTPStatus.OK return await response.json() return api_call
Build a datetime object for testing in the correct timezone.
def _local_datetime(hours: int, minutes: int) -> datetime.datetime: """Build a datetime object for testing in the correct timezone.""" return dt_util.as_local(datetime.datetime(2017, 11, 27, hours, minutes, 0))
Fixture to provide calendar configuration.yaml.
def mock_config() -> dict[str, Any]: """Fixture to provide calendar configuration.yaml.""" return {}
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( f"homeassistant.components.{DOMAIN}.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Fixture to set up config entry platforms.
def platforms() -> list[Platform]: """Fixture to set up config entry platforms.""" return [Platform.TODO]
Fixture to set timezone with fixed offset year round.
def set_tz(hass: HomeAssistant) -> None: """Fixture to set timezone with fixed offset year round.""" hass.config.set_time_zone("America/Regina")
Fixture to return VTODO objects for the calendar.
def mock_todos() -> list[str]: """Fixture to return VTODO objects for the calendar.""" return []
Fixture to set supported components of the calendar.
def mock_supported_components() -> list[str]: """Fixture to set supported components of the calendar.""" return ["VTODO"]
Fixture to create the primary calendar for the test.
def mock_calendar(supported_components: list[str]) -> Mock: """Fixture to create the primary calendar for the test.""" calendar = Mock() calendar.search = MagicMock(return_value=[]) calendar.name = CALENDAR_NAME calendar.get_supported_components = MagicMock(return_value=supported_components) return calendar
Create a caldav Todo object.
def create_todo(calendar: Mock, idx: str, ics: str) -> Todo: """Create a caldav Todo object.""" return Todo(client=None, url=f"{idx}.ics", data=ics, parent=calendar, id=idx)
Fixture to add search results to the test calendar.
def mock_search_items(calendar: Mock, todos: list[str]) -> None: """Fixture to add search results to the test calendar.""" calendar.search.return_value = [ create_todo(calendar, str(idx), item) for idx, item in enumerate(todos) ]
Fixture to create calendars for the test.
def mock_calendars(calendar: Mock) -> list[Mock]: """Fixture to create calendars for the test.""" return [calendar]
Pull out parts of the rfc5545 content useful for assertions in tests.
def compact_ics(ics: str) -> list[str]: """Pull out parts of the rfc5545 content useful for assertions in tests.""" return [ line for line in ics.split("\n") if line and not any(filter(line.startswith, IGNORE_COMPONENTS)) ]
Set the time zone for the tests.
def set_time_zone(hass: HomeAssistant) -> None: """Set the time zone for the tests.""" # Set our timezone to CST/Regina so we can check calculations # This keeps UTC-6 all year round hass.config.set_time_zone("America/Regina")
Mock config flow.
def config_flow_fixture(hass: HomeAssistant) -> Generator[None, None, None]: """Mock config flow.""" mock_platform(hass, f"{TEST_DOMAIN}.config_flow") with mock_config_flow(TEST_DOMAIN, MockFlow): yield
Fixture to set up a mock integration.
def mock_setup_integration( hass: HomeAssistant, config_flow_fixture: None, test_entities: list[CalendarEntity], ) -> None: """Fixture to set up a mock integration.""" async def async_setup_entry_init( hass: HomeAssistant, config_entry: ConfigEntry ) -> bool: """Set up test config entry.""" await hass.config_entries.async_forward_entry_setup(config_entry, DOMAIN) return True async def async_unload_entry_init( hass: HomeAssistant, config_entry: ConfigEntry, ) -> bool: await hass.config_entries.async_unload_platforms( config_entry, [Platform.CALENDAR] ) return True mock_platform(hass, f"{TEST_DOMAIN}.config_flow") mock_integration( hass, MockModule( TEST_DOMAIN, async_setup_entry=async_setup_entry_init, async_unload_entry=async_unload_entry_init, ), ) async def async_setup_entry_platform( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up test event platform via config entry.""" new_entities = create_test_entities() test_entities.clear() test_entities.extend(new_entities) async_add_entities(test_entities) mock_platform( hass, f"{TEST_DOMAIN}.{DOMAIN}", MockPlatform(async_setup_entry=async_setup_entry_platform), )
Fixture that holdes the fake entities created during the test.
def mock_test_entities() -> list[MockCalendarEntity]: """Fixture that holdes the fake entities created during the test.""" return []
Create test entities used during the test.
def create_test_entities() -> list[MockCalendarEntity]: """Create test entities used during the test.""" half_hour_from_now = dt_util.now() + datetime.timedelta(minutes=30) entity1 = MockCalendarEntity( "Calendar 1", [ CalendarEvent( start=half_hour_from_now, end=half_hour_from_now + datetime.timedelta(minutes=60), summary="Future Event", description="Future Description", location="Future Location", ) ], ) entity1.async_get_events = AsyncMock(wraps=entity1.async_get_events) middle_of_event = dt_util.now() - datetime.timedelta(minutes=30) entity2 = MockCalendarEntity( "Calendar 2", [ CalendarEvent( start=middle_of_event, end=middle_of_event + datetime.timedelta(minutes=60), summary="Current Event", ) ], ) entity2.async_get_events = AsyncMock(wraps=entity2.async_get_events) return [entity1, entity2]
Fixture to set a frozen time used in tests. This is needed so that it can run before other fixtures.
def mock_frozen_time() -> None: """Fixture to set a frozen time used in tests. This is needed so that it can run before other fixtures. """ return None
Fixture to freeze time that also can work for other fixtures.
def mock_set_frozen_time(frozen_time: Any) -> Generator[None, None, None]: """Fixture to freeze time that also can work for other fixtures.""" if not frozen_time: yield else: with freeze_time(frozen_time): yield
Fixture that tests can use to make fake events.
def fake_schedule( hass: HomeAssistant, freezer: FrozenDateTimeFactory ) -> Generator[FakeSchedule, None, None]: """Fixture that tests can use to make fake events.""" # Setup start time for all tests freezer.move_to("2022-04-19 10:31:02+00:00") return FakeSchedule(hass, freezer)
Fixture to expose the calendar entity used in tests.
def mock_test_entity(test_entities: list[MockCalendarEntity]) -> MockCalendarEntity: """Fixture to expose the calendar entity used in tests.""" return test_entities[1]
Fixture to return payload data for automation calls.
def calls(hass: HomeAssistant) -> Callable[[], list[dict[str, Any]]]: """Fixture to return payload data for automation calls.""" service_calls = async_mock_service(hass, "test", "automation") def get_trigger_data() -> list[dict[str, Any]]: return [c.data for c in service_calls] return get_trigger_data
Fixture to override the update interval for refreshing events.
def mock_update_interval() -> Generator[None, None, None]: """Fixture to override the update interval for refreshing events.""" with patch( "homeassistant.components.calendar.trigger.UPDATE_INTERVAL", new=TEST_UPDATE_INTERVAL, ): yield
Mock a TurboJPEG instance.
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
Verify the instance always gives back the same.
def test_turbojpeg_singleton() -> None: """Verify the instance always gives back the same.""" _clear_turbojpeg_singleton() assert TurboJPEGSingleton.instance() == TurboJPEGSingleton.instance()
Test we can scale a jpeg image.
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
Handle libjpegturbo not being installed.
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
Test we always get an image of at least the size we ask if its big enough.
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 )
Initialize a demo camera platform with streaming.
def mock_stream_fixture(hass): """Initialize a demo camera platform with streaming.""" assert hass.loop.run_until_complete( async_setup_component(hass, "stream", {"stream": {}}) )
Test module.__all__ is correctly set.
def test_all(module: ModuleType) -> None: """Test module.__all__ is correctly set.""" help_test_all(module)
Test deprecated stream type constants.
def test_deprecated_stream_type_constants( caplog: pytest.LogCaptureFixture, enum: camera.const.StreamType, module: ModuleType, ) -> None: """Test deprecated stream type constants.""" import_and_test_deprecated_constant_enum( caplog, module, enum, "STREAM_TYPE_", "2025.1" )
Test deprecated support constants.
def test_deprecated_support_constants( caplog: pytest.LogCaptureFixture, entity_feature: camera.CameraEntityFeature, ) -> None: """Test deprecated support constants.""" import_and_test_deprecated_constant_enum( caplog, camera, entity_feature, "SUPPORT_", "2025.1" )
Test deprecated supported features ints.
def test_deprecated_supported_features_ints(caplog: pytest.LogCaptureFixture) -> None: """Test deprecated supported features ints.""" class MockCamera(camera.Camera): @property def supported_features(self) -> int: """Return supported features.""" return 1 entity = MockCamera() assert entity.supported_features_compat is camera.CameraEntityFeature(1) assert "MockCamera" in caplog.text assert "is using deprecated supported features values" in caplog.text assert "Instead it should use" in caplog.text assert "CameraEntityFeature.ON_OFF" in caplog.text caplog.clear() assert entity.supported_features_compat is camera.CameraEntityFeature(1) assert "is using deprecated supported features values" not in caplog.text
Mock ffmpeg is loaded.
def mock_ffmpeg(hass): """Mock ffmpeg is loaded.""" hass.config.components.add("ffmpeg")
Mock the CanaryApi for easier testing.
def canary(hass): """Mock the CanaryApi for easier testing.""" with ( patch.object(Api, "login", return_value=True), patch("homeassistant.components.canary.Api") as mock_canary, ): instance = mock_canary.return_value = Api( "test-username", "test-password", 1, ) instance.login = MagicMock(return_value=True) instance.get_entries = MagicMock(return_value=[]) instance.get_locations = MagicMock(return_value=[]) instance.get_location = MagicMock(return_value=None) instance.get_modes = MagicMock(return_value=[]) instance.get_readings = MagicMock(return_value=[]) instance.get_latest_readings = MagicMock(return_value=[]) instance.set_location_mode = MagicMock(return_value=None) yield mock_canary
Mock the CanaryApi for easier config flow testing.
def canary_config_flow(hass): """Mock the CanaryApi for easier config flow testing.""" with ( patch.object(Api, "login", return_value=True), patch("homeassistant.components.canary.config_flow.Api") as mock_canary, ): instance = mock_canary.return_value = Api( "test-username", "test-password", 1, ) instance.login = MagicMock(return_value=True) instance.get_entries = MagicMock(return_value=[]) instance.get_locations = MagicMock(return_value=[]) instance.get_location = MagicMock(return_value=None) instance.get_modes = MagicMock(return_value=[]) instance.get_readings = MagicMock(return_value=[]) instance.get_latest_readings = MagicMock(return_value=[]) instance.set_location_mode = MagicMock(return_value=None) yield mock_canary
Mock Canary Device class.
def mock_device(device_id, name, is_online=True, device_type_name=None): """Mock Canary Device class.""" device = MagicMock() type(device).device_id = PropertyMock(return_value=device_id) type(device).name = PropertyMock(return_value=name) type(device).is_online = PropertyMock(return_value=is_online) type(device).device_type = PropertyMock( return_value={"id": 1, "name": device_type_name} ) return device
Mock Canary Location class.
def mock_location( location_id, name, is_celsius=True, devices=None, mode=None, is_private=False ): """Mock Canary Location class.""" location = MagicMock() type(location).location_id = PropertyMock(return_value=location_id) type(location).name = PropertyMock(return_value=name) type(location).is_celsius = PropertyMock(return_value=is_celsius) type(location).is_private = PropertyMock(return_value=is_private) type(location).devices = PropertyMock(return_value=devices or []) type(location).mode = PropertyMock(return_value=mode) return location
Mock Canary Mode class.
def mock_mode(mode_id, name): """Mock Canary Mode class.""" mode = MagicMock() type(mode).mode_id = PropertyMock(return_value=mode_id) type(mode).name = PropertyMock(return_value=name) type(mode).resource_url = PropertyMock(return_value=f"/v1/modes/{mode_id}") return mode
Mock Canary Reading class.
def mock_reading(sensor_type, sensor_value): """Mock Canary Reading class.""" reading = MagicMock() type(reading).sensor_type = SensorType(sensor_type) type(reading).value = PropertyMock(return_value=sensor_value) return reading