response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Return a mocked LaMetric Cloud client.
def mock_lametric_cloud() -> Generator[MagicMock, None, None]: """Return a mocked LaMetric Cloud client.""" with patch( "homeassistant.components.lametric.config_flow.LaMetricCloud", autospec=True ) as lametric_mock: lametric = lametric_mock.return_value lametric.devices.return_value = parse_raw_as( list[CloudDevice], load_fixture("cloud_devices.json", DOMAIN) ) yield lametric
Return the device fixture for a specific device.
def device_fixture() -> str: """Return the device fixture for a specific device.""" return "device"
Return a mocked LaMetric TIME client.
def mock_lametric(request, device_fixture: str) -> Generator[MagicMock, None, None]: """Return a mocked LaMetric TIME client.""" with ( patch( "homeassistant.components.lametric.coordinator.LaMetricDevice", autospec=True, ) as lametric_mock, patch( "homeassistant.components.lametric.config_flow.LaMetricDevice", new=lametric_mock, ), ): lametric = lametric_mock.return_value lametric.api_key = "mock-api-key" lametric.host = "127.0.0.1" lametric.device.return_value = Device.parse_raw( load_fixture(f"{device_fixture}.json", DOMAIN) ) yield lametric
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.landisgyr_heat_meter.async_setup_entry", return_value=True, ) as mock_setup_entry: yield mock_setup_entry
Mock of a serial port.
def mock_serial_port(): """Mock of a serial port.""" port = serial.tools.list_ports_common.ListPortInfo("/dev/ttyUSB1234") port.serial_number = "1234" port.manufacturer = "Virtual serial port" port.device = "/dev/ttyUSB1234" port.description = "Some serial port" port.pid = 9876 port.vid = 5678 return port
Create LastFM entry in Home Assistant.
def mock_config_entry() -> MockConfigEntry: """Create LastFM entry in Home Assistant.""" return MockConfigEntry( domain=DOMAIN, data={}, options={ CONF_API_KEY: API_KEY, CONF_MAIN_USER: USERNAME_1, CONF_USERS: [USERNAME_1, USERNAME_2], }, )
Create LastFM entry in Home Assistant.
def mock_imported_config_entry() -> MockConfigEntry: """Create LastFM entry in Home Assistant.""" return MockConfigEntry( domain=DOMAIN, data={}, options={ CONF_API_KEY: API_KEY, CONF_MAIN_USER: None, CONF_USERS: [USERNAME_1, USERNAME_2], }, )
Return default mock user.
def mock_default_user() -> MockUser: """Return default mock user.""" return MockUser( now_playing_result=Track("artist", "title", MockNetwork("lastfm")), top_tracks=[Track("artist", "title", MockNetwork("lastfm"))], recent_tracks=[Track("artist", "title", MockNetwork("lastfm"))], friends=[MockUser()], )
Return default mock user without friends.
def mock_default_user_no_friends() -> MockUser: """Return default mock user without friends.""" return MockUser( now_playing_result=Track("artist", "title", MockNetwork("lastfm")), top_tracks=[Track("artist", "title", MockNetwork("lastfm"))], recent_tracks=[Track("artist", "title", MockNetwork("lastfm"))], )
Return first time mock user.
def mock_first_time_user() -> MockUser: """Return first time mock user.""" return MockUser(now_playing_result=None, top_tracks=[], recent_tracks=[])
Return not found mock user.
def mock_not_found_user() -> MockUser: """Return not found mock user.""" return MockUser(thrown_error=WSError("network", "status", "User not found"))
Patch interface.
def patch_user(user: MockUser) -> MockUser: """Patch interface.""" return patch("pylast.User", return_value=user)
Patch interface.
def patch_setup_entry() -> bool: """Patch interface.""" return patch("homeassistant.components.lastfm.async_setup_entry", return_value=True)
Mock laundrify setup entry function.
def laundrify_setup_entry_fixture(): """Mock laundrify setup entry function.""" with patch( "homeassistant.components.laundrify.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock laundrify exchange_auth_code function.
def laundrify_exchange_code_fixture(): """Mock laundrify exchange_auth_code function.""" with patch( "laundrify_aio.LaundrifyAPI.exchange_auth_code", return_value=VALID_ACCESS_TOKEN, ) as exchange_code_mock: yield exchange_code_mock
Mock laundrify validate_token function.
def laundrify_validate_token_fixture(): """Mock laundrify validate_token function.""" with patch( "laundrify_aio.LaundrifyAPI.validate_token", return_value=True, ) as validate_token_mock: yield validate_token_mock
Mock valid laundrify API responses.
def laundrify_api_fixture(laundrify_exchange_code, laundrify_validate_token): """Mock valid laundrify API responses.""" with ( patch( "laundrify_aio.LaundrifyAPI.get_account_id", return_value=VALID_ACCOUNT_ID, ), patch( "laundrify_aio.LaundrifyAPI.get_machines", return_value=json.loads(load_fixture("laundrify/machines.json")), ) as get_machines_mock, ): yield get_machines_mock
Create laundrify entry in Home Assistant.
def create_entry( hass: HomeAssistant, access_token: str = VALID_ACCESS_TOKEN ) -> MockConfigEntry: """Create laundrify entry in Home Assistant.""" entry = MockConfigEntry( domain=DOMAIN, unique_id=VALID_ACCOUNT_ID, data={CONF_ACCESS_TOKEN: access_token}, ) entry.add_to_hass(hass) return entry
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
Set up config entries with configuration data.
def create_config_entry(name): """Set up config entries with configuration data.""" fixture_filename = f"lcn/config_entry_{name}.json" entry_data = json.loads(load_fixture(fixture_filename)) options = {} title = entry_data[CONF_HOST] unique_id = fixture_filename return MockConfigEntry( domain=DOMAIN, title=title, unique_id=unique_id, data=entry_data, options=options, )
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Return one specific config entry.
def create_config_entry_pchk(): """Return one specific config entry.""" return create_config_entry("pchk")
Return one specific config entry.
def create_config_entry_myhome(): """Return one specific config entry.""" return create_config_entry("myhome")
Get LCN device for specified address.
def get_device(hass, entry, address): """Get LCN device for specified address.""" device_registry = dr.async_get(hass) identifiers = {(DOMAIN, generate_unique_id(entry.entry_id, address))} device = device_registry.async_get_device(identifiers=identifiers) assert device return device
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Set up a mock of the temescal object to craft our expected responses.
def setup_mock_temescal( hass, mock_temescal, mac_info_dev=None, product_info=None, info=None ): """Set up a mock of the temescal object to craft our expected responses.""" tmock = mock_temescal.temescal instance = tmock.return_value def create_temescal_response(msg: str, data: dict | None = None) -> dict[str, Any]: response: dict[str, Any] = {"msg": msg} if data is not None: response["data"] = data return response def temescal_side_effect( addr: str, port: int, callback: Callable[[dict[str, Any]], None] ): mac_info_response = create_temescal_response( msg="MAC_INFO_DEV", data=mac_info_dev ) product_info_response = create_temescal_response( msg="PRODUCT_INFO", data=product_info ) info_response = create_temescal_response(msg="SPK_LIST_VIEW_INFO", data=info) instance.get_mac_info.side_effect = lambda: hass.add_job( callback, mac_info_response ) instance.get_product_info.side_effect = lambda: hass.add_job( callback, product_info_response ) instance.get_info.side_effect = lambda: hass.add_job(callback, info_response) return DEFAULT tmock.side_effect = temescal_side_effect
Mock an error.
def mock_error( aioclient_mock: AiohttpClientMocker, status: HTTPStatus | None = None ) -> None: """Mock an error.""" if status: aioclient_mock.get(f"{API_URL}/queue", status=status) aioclient_mock.get(f"{API_URL}/rootfolder", status=status) aioclient_mock.get(f"{API_URL}/system/status", status=status) aioclient_mock.get(f"{API_URL}/wanted/missing", status=status) aioclient_mock.get(f"{API_URL}/queue", exc=ClientError) aioclient_mock.get(f"{API_URL}/rootfolder", exc=ClientError) aioclient_mock.get(f"{API_URL}/system/status", exc=ClientError) aioclient_mock.get(f"{API_URL}/wanted/missing", exc=ClientError)
Mock cannot connect error.
def cannot_connect(aioclient_mock: AiohttpClientMocker) -> None: """Mock cannot connect error.""" mock_error(aioclient_mock, status=HTTPStatus.INTERNAL_SERVER_ERROR)
Mock invalid authorization error.
def invalid_auth(aioclient_mock: AiohttpClientMocker) -> None: """Mock invalid authorization error.""" mock_error(aioclient_mock, status=HTTPStatus.UNAUTHORIZED)
Mock Lidarr wrong app.
def wrong_app(aioclient_mock: AiohttpClientMocker) -> None: """Mock Lidarr wrong app.""" aioclient_mock.get( f"{URL}/initialize.js", text=load_fixture("lidarr/initialize-wrong.js"), headers={"Content-Type": "application/javascript"}, )
Mock Lidarr zero configuration failure.
def zeroconf_failed(aioclient_mock: AiohttpClientMocker) -> None: """Mock Lidarr zero configuration failure.""" aioclient_mock.get( f"{URL}/initialize.js", text="login-failed", headers={"Content-Type": "application/javascript"}, )
Mock Lidarr unknown error.
def unknown(aioclient_mock: AiohttpClientMocker) -> None: """Mock Lidarr unknown error.""" aioclient_mock.get( f"{URL}/initialize.js", text="something went wrong", headers={"Content-Type": "application/javascript"}, )
Mock Lidarr connection.
def mock_connection(aioclient_mock: AiohttpClientMocker) -> None: """Mock Lidarr connection.""" aioclient_mock.get( f"{URL}/initialize.js", text=load_fixture("lidarr/initialize.js"), headers={"Content-Type": "application/javascript"}, ) aioclient_mock.get( f"{API_URL}/system/status", text=load_fixture("lidarr/system-status.json"), headers={"Content-Type": CONTENT_TYPE_JSON}, ) aioclient_mock.get( f"{API_URL}/queue", text=load_fixture("lidarr/queue.json"), headers={"Content-Type": CONTENT_TYPE_JSON}, ) aioclient_mock.get( f"{API_URL}/wanted/missing", text=load_fixture("lidarr/wanted-missing.json"), headers={"Content-Type": CONTENT_TYPE_JSON}, ) aioclient_mock.get( f"{API_URL}/rootfolder", text=load_fixture("lidarr/rootfolder-linux.json"), headers={"Content-Type": CONTENT_TYPE_JSON}, )
Create Lidarr entry in Home Assistant.
def mock_config_entry(hass: HomeAssistant) -> MockConfigEntry: """Create Lidarr entry in Home Assistant.""" return MockConfigEntry(domain=DOMAIN, data=CONF_DATA)
Mock discovery.
def mock_discovery(): """Mock discovery.""" with _patch_discovery(): yield
Mock the effect conductor.
def mock_effect_conductor(): """Mock the effect conductor.""" class MockConductor: def __init__(self, *args, **kwargs) -> None: """Mock the conductor.""" self.start = AsyncMock() self.stop = AsyncMock() def effect(self, bulb): """Mock effect.""" return MagicMock() mock_conductor = MockConductor() with patch( "homeassistant.components.lifx.manager.aiolifx_effects.Conductor", return_value=mock_conductor, ): yield mock_conductor
Mock network util's async_get_source_ip.
def lifx_mock_get_source_ip(mock_get_source_ip): """Mock network util's async_get_source_ip."""
Avoid waiting for timeouts in tests.
def lifx_no_wait_for_timeouts(): """Avoid waiting for timeouts in tests.""" with ( patch.object(util, "OVERALL_TIMEOUT", 0), patch.object(config_flow, "OVERALL_TIMEOUT", 0), patch.object(coordinator, "OVERALL_TIMEOUT", 0), patch.object(coordinator, "MAX_UPDATE_TIME", 0), ): yield
Mock network util's async_get_ipv4_broadcast_addresses.
def lifx_mock_async_get_ipv4_broadcast_addresses(): """Mock network util's async_get_ipv4_broadcast_addresses.""" with patch( "homeassistant.components.network.async_get_ipv4_broadcast_addresses", return_value=["255.255.255.255"], ): yield
Return an empty, loaded, registry.
def device_reg_fixture(hass): """Return an empty, loaded, registry.""" return mock_device_registry(hass)
Return an empty, loaded, registry.
def entity_reg_fixture(hass): """Return an empty, loaded, registry.""" return mock_registry(hass)
Mock out lifx coordinator sleeps.
def mock_lifx_coordinator_sleep(): """Mock out lifx coordinator sleeps.""" with patch("homeassistant.components.lifx.coordinator.LIFX_IDENTIFY_DELAY", 0): yield
Set asyncio.sleep for state settles to zero.
def patch_lifx_state_settle_delay(): """Set asyncio.sleep for state settles to zero.""" with patch("homeassistant.components.lifx.light.LIFX_STATE_SETTLE_DELAY", 0): yield
Patch out discovery.
def _patch_device(device: Light | None = None, no_device: bool = False): """Patch out discovery.""" class MockLifxConnecton: """Mock lifx discovery.""" def __init__(self, *args, **kwargs): """Init connection.""" if no_device: self.device = _mocked_failing_bulb() else: self.device = device or _mocked_bulb() self.device.mac_addr = TARGET_ANY async def async_setup(self): """Mock setup.""" def async_stop(self): """Mock teardown.""" @contextmanager def _patcher(): with patch("homeassistant.components.lifx.LIFXConnection", MockLifxConnecton): yield return _patcher()
Patch out discovery.
def _patch_discovery(device: Light | None = None, no_device: bool = False): """Patch out discovery.""" class MockLifxDiscovery: """Mock lifx discovery.""" def __init__(self, *args, **kwargs): """Init discovery.""" if no_device: self.lights = {} return discovered = device or _mocked_bulb() self.lights = {discovered.mac_addr: discovered} def start(self): """Mock start.""" def cleanup(self): """Mock cleanup.""" @contextmanager def _patcher(): with ( patch.object(discovery, "DEFAULT_TIMEOUT", 0), patch( "homeassistant.components.lifx.discovery.LifxDiscovery", MockLifxDiscovery, ), ): yield return _patcher()
Patch out discovery.
def _patch_config_flow_try_connect( device: Light | None = None, no_device: bool = False ): """Patch out discovery.""" class MockLifxConnection: """Mock lifx discovery.""" def __init__(self, *args, **kwargs): """Init connection.""" if no_device: self.device = _mocked_failing_bulb() else: self.device = device or _mocked_bulb() self.device.mac_addr = TARGET_ANY async def async_setup(self): """Mock setup.""" def async_stop(self): """Mock teardown.""" @contextmanager def _patcher(): with patch( "homeassistant.components.lifx.config_flow.LIFXConnection", MockLifxConnection, ): yield return _patcher()
Turn all or specified light on.
def turn_on( hass, entity_id=ENTITY_MATCH_ALL, transition=None, brightness=None, brightness_pct=None, rgb_color=None, rgbw_color=None, rgbww_color=None, xy_color=None, hs_color=None, color_temp=None, kelvin=None, profile=None, flash=None, effect=None, color_name=None, white=None, ): """Turn all or specified light on.""" hass.add_job( async_turn_on, hass, entity_id, transition, brightness, brightness_pct, rgb_color, rgbw_color, rgbww_color, xy_color, hs_color, color_temp, kelvin, profile, flash, effect, color_name, white, )
Turn all or specified light off.
def turn_off(hass, entity_id=ENTITY_MATCH_ALL, transition=None, flash=None): """Turn all or specified light off.""" hass.add_job(async_turn_off, hass, entity_id, transition, flash)
Toggle all or specified light.
def toggle( hass, entity_id=ENTITY_MATCH_ALL, transition=None, brightness=None, brightness_pct=None, rgb_color=None, xy_color=None, hs_color=None, color_temp=None, kelvin=None, profile=None, flash=None, effect=None, color_name=None, ): """Toggle all or specified light.""" hass.add_job( async_toggle, hass, entity_id, transition, brightness, brightness_pct, rgb_color, xy_color, hs_color, color_temp, kelvin, profile, flash, effect, color_name, )
Mock loading of profiles.
def mock_light_profiles(): """Mock loading of profiles.""" data = {} def mock_profiles_class(hass): profiles = Profiles(hass) profiles.data = data profiles.async_initialize = AsyncMock() return profiles with patch( "homeassistant.components.light.Profiles", side_effect=mock_profiles_class, ): yield data
Stub copying the blueprints to the config folder.
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None: """Stub copying the blueprints to the config folder."""
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Stub copying the blueprints to the config folder.
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None: """Stub copying the blueprints to the config folder."""
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Stub copying the blueprints to the config folder.
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None: """Stub copying the blueprints to the config folder."""
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Test valid_supported_color_modes.
def test_valid_supported_color_modes() -> None: """Test valid_supported_color_modes.""" supported = {light.ColorMode.HS} assert light.valid_supported_color_modes(supported) == supported # Supported color modes must not be empty supported = set() with pytest.raises(vol.Error): light.valid_supported_color_modes(supported) # ColorMode.WHITE must be combined with a color mode supporting color supported = {light.ColorMode.WHITE} with pytest.raises(vol.Error): light.valid_supported_color_modes(supported) supported = {light.ColorMode.WHITE, light.ColorMode.COLOR_TEMP} with pytest.raises(vol.Error): light.valid_supported_color_modes(supported) supported = {light.ColorMode.WHITE, light.ColorMode.HS} assert light.valid_supported_color_modes(supported) == supported # ColorMode.ONOFF must be the only supported mode supported = {light.ColorMode.ONOFF} assert light.valid_supported_color_modes(supported) == supported supported = {light.ColorMode.ONOFF, light.ColorMode.COLOR_TEMP} with pytest.raises(vol.Error): light.valid_supported_color_modes(supported) # ColorMode.BRIGHTNESS must be the only supported mode supported = {light.ColorMode.BRIGHTNESS} assert light.valid_supported_color_modes(supported) == supported supported = {light.ColorMode.BRIGHTNESS, light.ColorMode.COLOR_TEMP} with pytest.raises(vol.Error): light.valid_supported_color_modes(supported)
Test filter_supported_color_modes.
def test_filter_supported_color_modes() -> None: """Test filter_supported_color_modes.""" supported = {light.ColorMode.HS} assert light.filter_supported_color_modes(supported) == supported # Supported color modes must not be empty supported = set() with pytest.raises(HomeAssistantError): light.filter_supported_color_modes(supported) # ColorMode.WHITE must be combined with a color mode supporting color supported = {light.ColorMode.WHITE} with pytest.raises(HomeAssistantError): light.filter_supported_color_modes(supported) supported = {light.ColorMode.WHITE, light.ColorMode.COLOR_TEMP} with pytest.raises(HomeAssistantError): light.filter_supported_color_modes(supported) supported = {light.ColorMode.WHITE, light.ColorMode.HS} assert light.filter_supported_color_modes(supported) == supported # ColorMode.ONOFF will be removed if combined with other modes supported = {light.ColorMode.ONOFF} assert light.filter_supported_color_modes(supported) == supported supported = {light.ColorMode.ONOFF, light.ColorMode.COLOR_TEMP} assert light.filter_supported_color_modes(supported) == {light.ColorMode.COLOR_TEMP} # ColorMode.BRIGHTNESS will be removed if combined with other modes supported = {light.ColorMode.BRIGHTNESS} assert light.filter_supported_color_modes(supported) == supported supported = {light.ColorMode.BRIGHTNESS, light.ColorMode.COLOR_TEMP} assert light.filter_supported_color_modes(supported) == {light.ColorMode.COLOR_TEMP} # ColorMode.BRIGHTNESS has priority over ColorMode.ONOFF supported = {light.ColorMode.ONOFF, light.ColorMode.BRIGHTNESS} assert light.filter_supported_color_modes(supported) == {light.ColorMode.BRIGHTNESS}
Test deprecated supported features ints.
def test_deprecated_supported_features_ints(caplog: pytest.LogCaptureFixture) -> None: """Test deprecated supported features ints.""" class MockLightEntityEntity(light.LightEntity): @property def supported_features(self) -> int: """Return supported features.""" return 1 entity = MockLightEntityEntity() assert entity.supported_features_compat is light.LightEntityFeature(1) assert "MockLightEntityEntity" in caplog.text assert "is using deprecated supported features values" in caplog.text assert "Instead it should use" in caplog.text assert "LightEntityFeature" in caplog.text assert "and color modes" in caplog.text caplog.clear() assert entity.supported_features_compat is light.LightEntityFeature(1) assert "is using deprecated supported features values" not in caplog.text
Test a light setting no color mode.
def test_report_no_color_mode( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, color_mode: str, supported_color_modes: set[str], warning_expected: bool, ) -> None: """Test a light setting no color mode.""" class MockLightEntityEntity(light.LightEntity): _attr_color_mode = color_mode _attr_is_on = True _attr_supported_features = light.LightEntityFeature.EFFECT _attr_supported_color_modes = supported_color_modes entity = MockLightEntityEntity() entity._async_calculate_state() expected_warning = "does not report a color mode" assert (expected_warning in caplog.text) is warning_expected
Test a light setting no color mode.
def test_report_no_color_modes( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, color_mode: str, supported_color_modes: set[str], warning_expected: bool, ) -> None: """Test a light setting no color mode.""" class MockLightEntityEntity(light.LightEntity): _attr_color_mode = color_mode _attr_is_on = True _attr_supported_features = light.LightEntityFeature.EFFECT _attr_supported_color_modes = supported_color_modes entity = MockLightEntityEntity() entity._async_calculate_state() expected_warning = "does not set supported color modes" assert (expected_warning in caplog.text) is warning_expected
Test a light setting an invalid color mode.
def test_report_invalid_color_mode( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, color_mode: str, supported_color_modes: set[str], effect: str | None, warning_expected: bool, ) -> None: """Test a light setting an invalid color mode.""" class MockLightEntityEntity(light.LightEntity): _attr_color_mode = color_mode _attr_effect = effect _attr_is_on = True _attr_supported_features = light.LightEntityFeature.EFFECT _attr_supported_color_modes = supported_color_modes entity = MockLightEntityEntity() entity._async_calculate_state() expected_warning = f"set to unsupported color mode {color_mode}" assert (expected_warning in caplog.text) is warning_expected
Test a light setting an invalid color mode.
def test_report_invalid_color_modes( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, color_mode: str, supported_color_modes: set[str], platform_name: str, warning_expected: bool, ) -> None: """Test a light setting an invalid color mode.""" class MockLightEntityEntity(light.LightEntity): _attr_color_mode = color_mode _attr_is_on = True _attr_supported_features = light.LightEntityFeature.EFFECT _attr_supported_color_modes = supported_color_modes platform = MockEntityPlatform(hass, platform_name=platform_name) entity = MockLightEntityEntity() entity._async_calculate_state() expected_warning = "sets invalid supported color modes" assert (expected_warning in caplog.text) is warning_expected
Mock LiteJet system.
def mock_litejet(): """Mock LiteJet system.""" with patch("pylitejet.LiteJet") as mock_pylitejet: async def get_load_name(number): return f"Mock Load #{number}" async def get_scene_name(number): return f"Mock Scene #{number}" async def get_switch_name(number): return f"Mock Switch #{number}" def get_switch_keypad_number(number): return number + 100 def get_switch_keypad_name(number): return f"Mock Keypad #{number + 100}" mock_lj = mock_pylitejet.return_value mock_lj.switch_pressed_callbacks = {} mock_lj.switch_released_callbacks = {} mock_lj.load_activated_callbacks = {} mock_lj.load_deactivated_callbacks = {} mock_lj.connected_changed_callbacks = [] def on_switch_pressed(number, callback): mock_lj.switch_pressed_callbacks[number] = callback def on_switch_released(number, callback): mock_lj.switch_released_callbacks[number] = callback def on_load_activated(number, callback): mock_lj.load_activated_callbacks[number] = callback def on_load_deactivated(number, callback): mock_lj.load_deactivated_callbacks[number] = callback def on_connected_changed(callback): mock_lj.connected_changed_callbacks.append(callback) mock_lj.on_switch_pressed.side_effect = on_switch_pressed mock_lj.on_switch_released.side_effect = on_switch_released mock_lj.on_load_activated.side_effect = on_load_activated mock_lj.on_load_deactivated.side_effect = on_load_deactivated mock_lj.on_connected_changed.side_effect = on_connected_changed mock_lj.open = AsyncMock() mock_lj.close = AsyncMock() mock_lj.loads.return_value = range(1, 3) mock_lj.get_load_name = AsyncMock(side_effect=get_load_name) mock_lj.get_load_level = AsyncMock(return_value=0) mock_lj.activate_load = AsyncMock() mock_lj.activate_load_at = AsyncMock() mock_lj.deactivate_load = AsyncMock() mock_lj.button_switches.return_value = range(1, 3) mock_lj.all_switches.return_value = range(1, 6) mock_lj.get_switch_name = AsyncMock(side_effect=get_switch_name) mock_lj.press_switch = AsyncMock() mock_lj.release_switch = AsyncMock() mock_lj.get_switch_keypad_number = Mock(side_effect=get_switch_keypad_number) mock_lj.get_switch_keypad_name = Mock(side_effect=get_switch_keypad_name) mock_lj.scenes.return_value = range(1, 3) mock_lj.get_scene_name = AsyncMock(side_effect=get_scene_name) mock_lj.activate_scene = AsyncMock() mock_lj.deactivate_scene = AsyncMock() mock_lj.start_time = dt_util.utcnow() mock_lj.last_delta = timedelta(0) mock_lj.connected = True mock_lj.model_name = "MockJet" def connected_changed(connected: bool, reason: str) -> None: mock_lj.connected = connected for callback in mock_lj.connected_changed_callbacks: callback(connected, reason) mock_lj.connected_changed = connected_changed yield mock_lj
Stub copying the blueprints to the config folder.
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None: """Stub copying the blueprints to the config folder."""
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Create a mock Litter-Robot device.
def create_mock_robot( robot_data: dict | None, account: Account, v4: bool, feeder: bool, side_effect: Any | None = None, ) -> Robot: """Create a mock Litter-Robot device.""" if not robot_data: robot_data = {} if v4: robot = LitterRobot4(data={**ROBOT_4_DATA, **robot_data}, account=account) elif feeder: robot = FeederRobot(data={**FEEDER_ROBOT_DATA, **robot_data}, account=account) else: robot = LitterRobot3(data={**ROBOT_DATA, **robot_data}, account=account) robot.start_cleaning = AsyncMock(side_effect=side_effect) robot.set_power_status = AsyncMock(side_effect=side_effect) robot.reset_waste_drawer = AsyncMock(side_effect=side_effect) robot.set_sleep_mode = AsyncMock(side_effect=side_effect) robot.set_night_light = AsyncMock(side_effect=side_effect) robot.set_panel_lockout = AsyncMock(side_effect=side_effect) robot.set_wait_time = AsyncMock(side_effect=side_effect) robot.refresh = AsyncMock(side_effect=side_effect) return robot
Create a mock Litter-Robot account.
def create_mock_account( robot_data: dict | None = None, side_effect: Any | None = None, skip_robots: bool = False, v4: bool = False, feeder: bool = False, ) -> MagicMock: """Create a mock Litter-Robot account.""" account = MagicMock(spec=Account) account.connect = AsyncMock() account.refresh_robots = AsyncMock() account.robots = ( [] if skip_robots else [create_mock_robot(robot_data, account, v4, feeder, side_effect)] ) return account
Mock a Litter-Robot account.
def mock_account() -> MagicMock: """Mock a Litter-Robot account.""" return create_mock_account()
Mock account with Litter-Robot 4.
def mock_account_with_litterrobot_4() -> MagicMock: """Mock account with Litter-Robot 4.""" return create_mock_account(v4=True)
Mock account with Feeder-Robot.
def mock_account_with_feederrobot() -> MagicMock: """Mock account with Feeder-Robot.""" return create_mock_account(feeder=True)
Mock a Litter-Robot account.
def mock_account_with_no_robots() -> MagicMock: """Mock a Litter-Robot account.""" return create_mock_account(skip_robots=True)
Mock a Litter-Robot account with a sleeping robot.
def mock_account_with_sleeping_robot() -> MagicMock: """Mock a Litter-Robot account with a sleeping robot.""" return create_mock_account({"sleepModeActive": "102:00:00"})
Mock a Litter-Robot account with a robot that has sleep mode disabled.
def mock_account_with_sleep_disabled_robot() -> MagicMock: """Mock a Litter-Robot account with a robot that has sleep mode disabled.""" return create_mock_account({"sleepModeActive": "0"})
Mock a Litter-Robot account with error.
def mock_account_with_error() -> MagicMock: """Mock a Litter-Robot account with error.""" return create_mock_account({"unitStatus": "BR"})
Mock a Litter-Robot account with side effects.
def mock_account_with_side_effects() -> MagicMock: """Mock a Litter-Robot account with side effects.""" return create_mock_account( side_effect=InvalidCommandException("Invalid command: oops") )
Create mock for LIVISI login.
def mocked_livisi_login(): """Create mock for LIVISI login.""" return patch( "homeassistant.components.livisi.config_flow.AioLivisi.async_set_token" )
Create mock data for LIVISI controller.
def mocked_livisi_controller(): """Create mock data for LIVISI controller.""" return patch( "homeassistant.components.livisi.config_flow.AioLivisi.async_get_controller", return_value=DEVICE_CONFIG, )
Create mock for LIVISI setup entry.
def mocked_livisi_setup_entry(): """Create mock for LIVISI setup entry.""" return patch( "homeassistant.components.livisi.async_setup_entry", return_value=True, )
Fixture to allow tests to set initial ics content for the calendar store.
def mock_ics_content() -> str: """Fixture to allow tests to set initial ics content for the calendar store.""" return ""
Fixture to raise errors from the FakeStore.
def mock_store_read_side_effect() -> Any | None: """Fixture to raise errors from the FakeStore.""" return None
Test cleanup, remove any media storage persisted during the test.
def mock_store( ics_content: str, store_read_side_effect: Any | None ) -> Generator[None, None, None]: """Test cleanup, remove any media storage persisted during the test.""" stores: dict[Path, FakeStore] = {} def new_store(hass: HomeAssistant, path: Path) -> FakeStore: if path not in stores: stores[path] = FakeStore(hass, path, ics_content, store_read_side_effect) return stores[path] with patch( "homeassistant.components.local_calendar.LocalCalendarStore", new=new_store ): yield
Fixture for time zone to use in tests.
def mock_time_zone() -> str: """Fixture for time zone to use in tests.""" # Set our timezone to CST/Regina so we can check calculations # This keeps UTC-6 all year round return "America/Regina"
Set the time zone for the tests.
def set_time_zone(hass: HomeAssistant, time_zone: str): """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(time_zone)
Fixture for mock configuration entry.
def mock_config_entry() -> MockConfigEntry: """Fixture for mock configuration entry.""" return MockConfigEntry(domain=DOMAIN, data={CONF_CALENDAR_NAME: CALENDAR_NAME})
Fetch calendar events from the HTTP API.
def get_events_fixture(hass_client: ClientSessionGenerator) -> GetEventsFn: """Fetch calendar events from the HTTP API.""" async def _fetch(start: str, end: str) -> list[dict[str, Any]]: client = await hass_client() response = await client.get( f"/api/calendars/{TEST_ENTITY}?start={urllib.parse.quote(start)}&end={urllib.parse.quote(end)}" ) assert response.status == HTTPStatus.OK return await response.json() return _fetch
Filter event API response to minimum fields.
def event_fields(data: dict[str, str]) -> dict[str, str]: """Filter event API response to minimum fields.""" return { k: data[k] for k in ["summary", "start", "end", "recurrence_id", "location"] if data.get(k) }
Return a test client generator."".
def _get_test_client_generator( hass: HomeAssistant, aiohttp_client: ClientSessionGenerator, new_token: str ): """Return a test client generator."".""" async def auth_client() -> TestClient: return await aiohttp_client( hass.http.app, headers={"Authorization": f"Bearer {new_token}"} ) return auth_client
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.local_todo.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Fixture to set .ics file content.
def mock_ics_content() -> str | None: """Fixture to set .ics file content.""" return ""
Fixture to raise errors from the FakeStore.
def mock_store_read_side_effect() -> Any | None: """Fixture to raise errors from the FakeStore.""" return None
Fixture that sets up a fake local storage object.
def mock_store( ics_content: str, store_read_side_effect: Any | None ) -> Generator[None, None, None]: """Fixture that sets up a fake local storage object.""" stores: dict[Path, FakeStore] = {} def new_store(hass: HomeAssistant, path: Path) -> FakeStore: if path not in stores: stores[path] = FakeStore(hass, path, ics_content, store_read_side_effect) return stores[path] with patch("homeassistant.components.local_todo.LocalTodoListStore", new=new_store): yield
Fixture for mock configuration entry.
def mock_config_entry() -> MockConfigEntry: """Fixture for mock configuration entry.""" return MockConfigEntry( domain=DOMAIN, data={CONF_STORAGE_KEY: STORAGE_KEY, CONF_TODO_LIST_NAME: TODO_NAME}, )
Set the time zone for the tests that keesp UTC-6 all year round.
def set_time_zone(hass: HomeAssistant) -> None: """Set the time zone for the tests that keesp UTC-6 all year round.""" hass.config.set_time_zone("America/Regina")
Mock device tracker config loading.
def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading."""
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
Stub copying the blueprints to the config folder.
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None: """Stub copying the blueprints to the config folder."""