response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Mock pychromecast dial.
def get_multizone_status_mock(): """Mock pychromecast dial.""" mock = MagicMock(spec_set=pychromecast.dial.get_multizone_status) mock.return_value.dynamic_groups = [] return mock
Mock pychromecast dial.
def get_cast_type_mock(): """Mock pychromecast dial.""" return MagicMock(spec_set=pychromecast.dial.get_cast_type)
Mock pychromecast CastBrowser.
def castbrowser_mock(): """Mock pychromecast CastBrowser.""" return MagicMock(spec=pychromecast.discovery.CastBrowser)
Mock pychromecast MultizoneManager.
def mz_mock(): """Mock pychromecast MultizoneManager.""" return MagicMock(spec_set=multizone.MultizoneManager)
Mock pychromecast quick_play.
def quick_play_mock(): """Mock pychromecast quick_play.""" return MagicMock()
Mock pychromecast get_chromecast_from_cast_info.
def get_chromecast_mock(): """Mock pychromecast get_chromecast_from_cast_info.""" return MagicMock()
Mock HomeAssistantController.
def ha_controller_mock(): """Mock HomeAssistantController.""" with patch( "homeassistant.components.cast.media_player.HomeAssistantController", MagicMock(), ) as ha_controller_mock: yield ha_controller_mock
Mock pychromecast.
def cast_mock( mz_mock, quick_play_mock, castbrowser_mock, get_cast_type_mock, get_chromecast_mock, get_multizone_status_mock, ): """Mock pychromecast.""" ignore_cec_orig = list(pychromecast.IGNORE_CEC) with ( patch( "homeassistant.components.cast.discovery.pychromecast.discovery.CastBrowser", castbrowser_mock, ), patch( "homeassistant.components.cast.helpers.dial.get_cast_type", get_cast_type_mock, ), patch( "homeassistant.components.cast.helpers.dial.get_multizone_status", get_multizone_status_mock, ), patch( "homeassistant.components.cast.media_player.MultizoneManager", return_value=mz_mock, ), patch( "homeassistant.components.cast.media_player.zeroconf.async_get_instance", AsyncMock(), ), patch( "homeassistant.components.cast.media_player.quick_play", quick_play_mock, ), patch( "homeassistant.components.cast.media_player.pychromecast.get_chromecast_from_cast_info", get_chromecast_mock, ), ): yield pychromecast.IGNORE_CEC = list(ignore_cec_orig)
Get suggested value for key in voluptuous schema.
def get_suggested(schema, key): """Get suggested value for key in voluptuous schema.""" for k in schema: if k == key: if k.description is None or "suggested_value" not in k.description: return None return k.description["suggested_value"]
Generate a Fake Chromecast object with the specified arguments.
def get_fake_chromecast(info: ChromecastInfo): """Generate a Fake Chromecast object with the specified arguments.""" mock = MagicMock(uuid=info.uuid) mock.app_id = None mock.media_controller.status = None return mock
Generate a Fake ChromecastInfo with the specified arguments.
def get_fake_chromecast_info( *, host="192.168.178.42", port=8009, service=None, uuid: UUID | None = FakeUUID, cast_type=UNDEFINED, manufacturer=UNDEFINED, model_name=UNDEFINED, ): """Generate a Fake ChromecastInfo with the specified arguments.""" if service is None: service = pychromecast.discovery.HostServiceInfo(host, port) if cast_type is UNDEFINED: cast_type = CAST_TYPE_GROUP if port != 8009 else CAST_TYPE_CHROMECAST if manufacturer is UNDEFINED: manufacturer = "Nabu Casa" if model_name is UNDEFINED: model_name = "Chromecast" return ChromecastInfo( cast_info=pychromecast.models.CastInfo( services={service}, uuid=uuid, model_name=model_name, friendly_name="Speaker", host=host, port=port, cast_type=cast_type, manufacturer=manufacturer, ) )
Generate a Fake Zeroconf object with the specified arguments.
def get_fake_zconf(host="192.168.178.42", port=8009): """Generate a Fake Zeroconf object with the specified arguments.""" parsed_addresses = MagicMock() parsed_addresses.return_value = [host] service_info = MagicMock(parsed_addresses=parsed_addresses, port=port) zconf = MagicMock() zconf.get_service_info.return_value = service_info return zconf
Get registered status callbacks from the chromecast mock.
def get_status_callbacks(chromecast_mock, mz_mock=None): """Get registered status callbacks from the chromecast mock.""" status_listener = chromecast_mock.register_status_listener.call_args[0][0] cast_status_cb = status_listener.new_cast_status connection_listener = chromecast_mock.register_connection_listener.call_args[0][0] conn_status_cb = connection_listener.new_connection_status mc = chromecast_mock.socket_client.media_controller media_status_cb = mc.register_status_listener.call_args[0][0].new_media_status if not mz_mock: return cast_status_cb, conn_status_cb, media_status_cb mz_listener = mz_mock.register_listener.call_args[0][1] group_media_status_cb = mz_listener.multizone_new_media_status return cast_status_cb, conn_status_cb, media_status_cb, group_media_status_cb
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.ccm15.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock ccm15 device.
def ccm15_device() -> Generator[AsyncMock, None, None]: """Mock ccm15 device.""" ccm15_devices = { 0: CCM15SlaveDevice(bytes.fromhex("000000b0b8001b")), 1: CCM15SlaveDevice(bytes.fromhex("00000041c0001a")), } device_state = CCM15DeviceState(devices=ccm15_devices) with patch( "homeassistant.components.ccm15.coordinator.CCM15Device.get_status_async", return_value=device_state, ): yield
Mock empty set of ccm15 device.
def network_failure_ccm15_device() -> Generator[AsyncMock, None, None]: """Mock empty set of ccm15 device.""" device_state = CCM15DeviceState(devices={}) with patch( "homeassistant.components.ccm15.coordinator.CCM15Device.get_status_async", return_value=device_state, ): yield
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.cert_expiry.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Build a datetime object for testing in the correct timezone.
def static_datetime(): """Build a datetime object for testing in the correct timezone.""" return dt_util.as_utc(datetime(2020, 6, 12, 8, 0, 0))
Create timestamp object for requested days in future.
def future_timestamp(days): """Create timestamp object for requested days in future.""" delta = timedelta(days=days, minutes=1) return static_datetime() + delta
Mock Clicksend TTS notify service.
def mock_clicksend_tts_notify(): """Mock Clicksend TTS notify service.""" with patch( "homeassistant.components.clicksend_tts.notify.get_service", autospec=True ) as ns: yield ns
Set new preset mode.
def set_preset_mode(hass, preset_mode, entity_id=ENTITY_MATCH_ALL): """Set new preset mode.""" data = {ATTR_PRESET_MODE: preset_mode} if entity_id: data[ATTR_ENTITY_ID] = entity_id hass.services.call(DOMAIN, SERVICE_SET_PRESET_MODE, data)
Turn all or specified climate devices auxiliary heater on.
def set_aux_heat(hass, aux_heat, entity_id=ENTITY_MATCH_ALL): """Turn all or specified climate devices auxiliary heater on.""" data = {ATTR_AUX_HEAT: aux_heat} if entity_id: data[ATTR_ENTITY_ID] = entity_id hass.services.call(DOMAIN, SERVICE_SET_AUX_HEAT, data)
Set new target temperature.
def set_temperature( hass, temperature=None, entity_id=ENTITY_MATCH_ALL, target_temp_high=None, target_temp_low=None, hvac_mode=None, ): """Set new target temperature.""" kwargs = { key: value for key, value in [ (ATTR_TEMPERATURE, temperature), (ATTR_TARGET_TEMP_HIGH, target_temp_high), (ATTR_TARGET_TEMP_LOW, target_temp_low), (ATTR_ENTITY_ID, entity_id), (ATTR_HVAC_MODE, hvac_mode), ] if value is not None } _LOGGER.debug("set_temperature start data=%s", kwargs) hass.services.call(DOMAIN, SERVICE_SET_TEMPERATURE, kwargs)
Set new target humidity.
def set_humidity(hass, humidity, entity_id=ENTITY_MATCH_ALL): """Set new target humidity.""" data = {ATTR_HUMIDITY: humidity} if entity_id is not None: data[ATTR_ENTITY_ID] = entity_id hass.services.call(DOMAIN, SERVICE_SET_HUMIDITY, data)
Set all or specified climate devices fan mode on.
def set_fan_mode(hass, fan, entity_id=ENTITY_MATCH_ALL): """Set all or specified climate devices fan mode on.""" data = {ATTR_FAN_MODE: fan} if entity_id: data[ATTR_ENTITY_ID] = entity_id hass.services.call(DOMAIN, SERVICE_SET_FAN_MODE, data)
Set new target operation mode.
def set_operation_mode(hass, hvac_mode, entity_id=ENTITY_MATCH_ALL): """Set new target operation mode.""" data = {ATTR_HVAC_MODE: hvac_mode} if entity_id is not None: data[ATTR_ENTITY_ID] = entity_id hass.services.call(DOMAIN, SERVICE_SET_HVAC_MODE, data)
Set new target swing mode.
def set_swing_mode(hass, swing_mode, entity_id=ENTITY_MATCH_ALL): """Set new target swing mode.""" data = {ATTR_SWING_MODE: swing_mode} if entity_id is not None: data[ATTR_ENTITY_ID] = entity_id hass.services.call(DOMAIN, SERVICE_SET_SWING_MODE, data)
Mock config flow.
def config_flow_fixture(hass: HomeAssistant) -> Generator[None, None, None]: """Mock config flow.""" mock_platform(hass, "test.config_flow") with mock_config_flow("test", 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."""
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 module.__all__ is correctly set.
def test_all(module: ModuleType) -> None: """Test module.__all__ is correctly set.""" help_test_all(module)
Test deprecated constants.
def test_deprecated_constants( caplog: pytest.LogCaptureFixture, enum: Enum, constant_prefix: str, module: ModuleType, ) -> None: """Test deprecated constants.""" import_and_test_deprecated_constant_enum( caplog, module, enum, constant_prefix, "2025.1" )
Test deprecated current constants.
def test_deprecated_current_constants( caplog: pytest.LogCaptureFixture, enum: climate.HVACAction, constant_postfix: str, ) -> None: """Test deprecated current constants.""" import_and_test_deprecated_constant( caplog, climate.const, "CURRENT_HVAC_" + constant_postfix, f"{enum.__class__.__name__}.{enum.name}", enum, "2025.1", )
Test deprecated supported features ints.
def test_deprecated_supported_features_ints(caplog: pytest.LogCaptureFixture) -> None: """Test deprecated supported features ints.""" class MockClimateEntity(ClimateEntity): @property def supported_features(self) -> int: """Return supported features.""" return 1 entity = MockClimateEntity() assert entity.supported_features is ClimateEntityFeature(1) assert "MockClimateEntity" in caplog.text assert "is using deprecated supported features values" in caplog.text assert "Instead it should use" in caplog.text assert "ClimateEntityFeature.TARGET_TEMPERATURE" in caplog.text caplog.clear() assert entity.supported_features is ClimateEntityFeature(1) assert "is using deprecated supported features values" not in caplog.text
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) -> 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.TODO]) 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, ), )
Fixture for cloud component.
def set_cloud_prefs_fixture( cloud: MagicMock, ) -> Callable[[dict[str, Any]], Coroutine[Any, Any, None]]: """Fixture for cloud component.""" async def set_cloud_prefs(prefs_settings: dict[str, Any]) -> None: """Set cloud prefs.""" prefs_to_set = cloud.client.prefs.as_dict() prefs_to_set.pop(prefs.PREF_ALEXA_DEFAULT_EXPOSE) prefs_to_set.pop(prefs.PREF_GOOGLE_DEFAULT_EXPOSE) prefs_to_set.update(prefs_settings) await cloud.client.prefs.async_update(**prefs_to_set) return set_cloud_prefs
Mock the TTS cache dir with empty dir.
def mock_tts_cache_dir_autouse(mock_tts_cache_dir): """Mock the TTS cache dir with empty dir.""" return mock_tts_cache_dir
Mock writing tags.
def tts_mutagen_mock_fixture_autouse(tts_mutagen_mock): """Mock writing tags."""
Mock os module.
def mock_user_data(): """Mock os module.""" with patch("hass_nabucasa.Cloud._write_user_info") as writer: yield writer
Fixture for cloud component.
def mock_cloud_fixture(hass): """Fixture for cloud component.""" hass.loop.run_until_complete(mock_cloud(hass)) return mock_cloud_prefs(hass)
Mock cloud is logged in.
def mock_cloud_login(hass, mock_cloud_setup): """Mock cloud is logged in.""" hass.data[const.DOMAIN].id_token = jwt.encode( { "email": "[email protected]", "custom:sub-exp": "2300-01-03", "cognito:username": "abcdefghjkl", }, "test", ) with patch.object(hass.data[const.DOMAIN].auth, "async_check_token"): yield
Mock check token.
def mock_auth_fixture(): """Mock check token.""" with ( patch("hass_nabucasa.auth.CognitoAuth.async_check_token"), patch("hass_nabucasa.auth.CognitoAuth.async_renew_access_token"), ): yield
Mock cloud is logged in.
def mock_expired_cloud_login(hass, mock_cloud_setup): """Mock cloud is logged in.""" hass.data[const.DOMAIN].id_token = jwt.encode( { "email": "[email protected]", "custom:sub-exp": "2018-01-01", "cognito:username": "abcdefghjkl", }, "test", )
Return a registered config flow.
def flow_handler(hass): """Return a registered config flow.""" mock_platform(hass, f"{TEST_DOMAIN}.config_flow") class TestFlowHandler(config_entry_oauth2_flow.AbstractOAuth2FlowHandler): """Test flow handler.""" DOMAIN = TEST_DOMAIN @property def logger(self) -> logging.Logger: """Return logger.""" return logging.getLogger(__name__) with patch.dict(config_entries.HANDLERS, {TEST_DOMAIN: TestFlowHandler}): yield TestFlowHandler
Stub the cloud.
def cloud_stub(): """Stub the cloud.""" return Mock(is_logged_in=True, subscription_expired=False)
Enable exposing new entities to Alexa.
def expose_new(hass, expose_new): """Enable exposing new entities to Alexa.""" exposed_entities: ExposedEntities = hass.data[DATA_EXPOSED_ENTITIES] exposed_entities.async_set_expose_new_entities("cloud.alexa", expose_new)
Expose an entity to Alexa.
def expose_entity(hass, entity_id, should_expose): """Expose an entity to Alexa.""" async_expose_entity(hass, "cloud.alexa", entity_id, should_expose)
Patch sync helper.
def patch_sync_helper(): """Patch sync helper.""" to_update = [] to_remove = [] def sync_helper(to_upd, to_rem): to_update.extend([ent_id for ent_id in to_upd if ent_id not in to_update]) to_remove.extend([ent_id for ent_id in to_rem if ent_id not in to_remove]) return True with ( patch("homeassistant.components.cloud.alexa_config.SYNC_DELAY", 0), patch( "homeassistant.components.cloud.alexa_config.CloudAlexaConfig._sync_helper", side_effect=sync_helper, ), ): yield to_update, to_remove
Test that alexa config enabled requires a valid Cloud sub.
def test_enabled_requires_valid_sub( hass: HomeAssistant, mock_expired_cloud_login, cloud_prefs ) -> None: """Test that alexa config enabled requires a valid Cloud sub.""" assert cloud_prefs.alexa_enabled assert hass.data["cloud"].is_logged_in assert hass.data["cloud"].subscription_expired config = alexa_config.CloudAlexaConfig( hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data["cloud"] ) assert not config.enabled
Mock WAIT_UNTIL_CHANGE to execute callback immediately.
def mock_wait_until() -> Generator[None, None, None]: """Mock WAIT_UNTIL_CHANGE to execute callback immediately.""" with patch("homeassistant.components.cloud.binary_sensor.WAIT_UNTIL_CHANGE", 0): yield
Mock cloud class.
def mock_cloud_inst(): """Mock cloud class.""" return MagicMock(subscription_expired=False)
Mock Google conf.
def mock_conf(hass, cloud_prefs): """Mock Google conf.""" return CloudGoogleConfig( hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, Mock(username="abcdefghjkl"), )
Enable exposing new entities to Google.
def expose_new(hass, expose_new): """Enable exposing new entities to Google.""" exposed_entities: ExposedEntities = hass.data[DATA_EXPOSED_ENTITIES] exposed_entities.async_set_expose_new_entities("cloud.google_assistant", expose_new)
Expose an entity to Google.
def expose_entity(hass, entity_id, should_expose): """Expose an entity to Google.""" async_expose_entity(hass, "cloud.google_assistant", entity_id, should_expose)
Test that google config enabled requires a valid Cloud sub.
def test_enabled_requires_valid_sub( hass: HomeAssistant, mock_expired_cloud_login, cloud_prefs ) -> None: """Test that google config enabled requires a valid Cloud sub.""" assert cloud_prefs.google_enabled assert hass.data["cloud"].is_logged_in assert hass.data["cloud"].subscription_expired config = CloudGoogleConfig( hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data["cloud"] ) assert not config.enabled
Simulate a cloud request.
def simulate_cloud_request() -> Generator[None, None, None]: """Simulate a cloud request.""" with patch( "hass_nabucasa.remote.is_cloud_request", Mock(get=Mock(return_value=True)) ): yield
Fixture to set up a web.Application.
def app_strict_connection( hass: HomeAssistant, refresh_token: RefreshToken ) -> web.Application: """Fixture to set up a web.Application.""" async def handler(request): """Return if request was authenticated.""" return web.json_response(data={"authenticated": request[KEY_AUTHENTICATED]}) app = web.Application() app[KEY_HASS] = hass app.router.add_get("/", handler) async def set_cookie(request: web.Request) -> web.Response: hass = request.app[KEY_HASS] # Clear all sessions hass.auth.session._temp_sessions.clear() hass.auth.session._strict_connection_sessions.clear() if request.query["token"] == "refresh": await hass.auth.session.async_create_session(request, refresh_token) else: await hass.auth.session.async_create_temp_unauthorized_session(request) session = await get_session(request) return web.Response(text=session[SESSION_ID]) app.router.add_get("/test/cookie", set_cookie) return app
Test our default language exists.
def test_default_exists() -> None: """Test our default language exists.""" assert const.DEFAULT_TTS_DEFAULT_VOICE[0] in TTS_VOICES assert ( const.DEFAULT_TTS_DEFAULT_VOICE[1] in TTS_VOICES[const.DEFAULT_TTS_DEFAULT_VOICE[0]] )
Test schema.
def test_schema() -> None: """Test schema.""" assert "nl-NL" in tts.SUPPORT_LANGUAGES processed = tts.PLATFORM_SCHEMA({"platform": "cloud", "language": "nl-NL"}) assert processed["gender"] == "female" with pytest.raises(vol.Invalid): tts.PLATFORM_SCHEMA( {"platform": "cloud", "language": "non-existing", "gender": "female"} ) with pytest.raises(vol.Invalid): tts.PLATFORM_SCHEMA( {"platform": "cloud", "language": "nl-NL", "gender": "not-supported"} ) # Should not raise tts.PLATFORM_SCHEMA({"platform": "cloud", "language": "nl-NL", "gender": "female"}) tts.PLATFORM_SCHEMA({"platform": "cloud"})
Fixture for cloud component.
def mock_cloud_prefs(hass, prefs={}): """Fixture for cloud component.""" prefs_to_set = { const.PREF_ALEXA_SETTINGS_VERSION: cloud_prefs.ALEXA_SETTINGS_VERSION, const.PREF_ENABLE_ALEXA: True, const.PREF_ENABLE_GOOGLE: True, const.PREF_GOOGLE_SECURE_DEVICES_PIN: None, const.PREF_GOOGLE_SETTINGS_VERSION: cloud_prefs.GOOGLE_SETTINGS_VERSION, } prefs_to_set.update(prefs) hass.data[cloud.DOMAIN].client._prefs._prefs = prefs_to_set return hass.data[cloud.DOMAIN].client._prefs
Mock the CloudflareUpdater for easier testing.
def cfupdate(hass): """Mock the CloudflareUpdater for easier testing.""" mock_cfupdate = _get_mock_client() with patch( "homeassistant.components.cloudflare.pycfdns.Client", return_value=mock_cfupdate, ) as mock_api: yield mock_api
Mock the CloudflareUpdater for easier config flow testing.
def cfupdate_flow(hass): """Mock the CloudflareUpdater for easier config flow testing.""" mock_cfupdate = _get_mock_client() with patch( "homeassistant.components.cloudflare.pycfdns.Client", return_value=mock_cfupdate, ) as mock_api: yield mock_api
Test get_zone_id.
def test_get_zone_id(): """Test get_zone_id.""" zones = [ {"id": "1", "name": "example.com"}, {"id": "2", "name": "example.org"}, ] assert get_zone_id("example.com", zones) == "1" assert get_zone_id("example.org", zones) == "2" assert get_zone_id("example.net", zones) is None
Mock the ElectricityMaps client.
def mock_electricity_maps() -> Generator[None, MagicMock, None]: """Mock the ElectricityMaps client.""" with ( patch( "homeassistant.components.co2signal.ElectricityMaps", autospec=True, ) as electricity_maps, patch( "homeassistant.components.co2signal.config_flow.ElectricityMaps", new=electricity_maps, ), ): client = electricity_maps.return_value client.latest_carbon_intensity_by_coordinates.return_value = VALID_RESPONSE client.latest_carbon_intensity_by_country_code.return_value = VALID_RESPONSE yield client
Return simplified accounts using mock.
def mocked_get_accounts(_, **kwargs): """Return simplified accounts using mock.""" return MockGetAccounts(**kwargs)
Return a simplified mock user.
def mock_get_current_user(): """Return a simplified mock user.""" return { "id": "123456-abcdef", "name": "Test User", }
Return a heavily reduced mock list of exchange rates for testing.
def mock_get_exchange_rates(): """Return a heavily reduced mock list of exchange rates for testing.""" return { "currency": "USD", "rates": { GOOD_CURRENCY_2: "1.0", GOOD_EXCHANGE_RATE_2: "0.109", GOOD_EXCHANGE_RATE: "0.00002", }, }
Validate the given RGB value is in acceptable tolerance.
def _close_enough(actual_rgb, testing_rgb): """Validate the given RGB value is in acceptable tolerance.""" # Convert the given RGB values to hue / saturation and then back again # as it wasn't reading the same RGB value set against it. actual_hs = color_util.color_RGB_to_hs(*actual_rgb) actual_rgb = color_util.color_hs_to_RGB(*actual_hs) testing_hs = color_util.color_RGB_to_hs(*testing_rgb) testing_rgb = color_util.color_hs_to_RGB(*testing_hs) actual_red, actual_green, actual_blue = actual_rgb testing_red, testing_green, testing_blue = testing_rgb r_diff = abs(actual_red - testing_red) g_diff = abs(actual_green - testing_green) b_diff = abs(actual_blue - testing_blue) return ( r_diff <= CLOSE_THRESHOLD and g_diff <= CLOSE_THRESHOLD and b_diff <= CLOSE_THRESHOLD )
Convert file to BytesIO for testing due to PIL UnidentifiedImageError.
def _get_file_mock(file_path): """Convert file to BytesIO for testing due to PIL UnidentifiedImageError.""" _file = None with open(file_path) as file_handler: _file = io.BytesIO(file_handler.read()) _file.name = "color_extractor.jpg" _file.seek(0) return _file
Mock the bridge discover method.
def mock_bridge_discover(): """Mock the bridge discover method.""" with patch("pycomfoconnect.bridge.Bridge.discover") as mock_bridge_discover: mock_bridge_discover.return_value[0].uuid.hex.return_value = "00" yield mock_bridge_discover
Mock the ComfoConnect connect method.
def mock_comfoconnect_command(): """Mock the ComfoConnect connect method.""" with patch( "pycomfoconnect.comfoconnect.ComfoConnect._command" ) as mock_comfoconnect_command: yield mock_comfoconnect_command
Mock create_subprocess_shell.
def mock_asyncio_subprocess_run( response: bytes = b"", returncode: int = 0, exception: Exception | None = None ): """Mock create_subprocess_shell.""" class MockProcess(asyncio.subprocess.Process): @property def returncode(self): return returncode async def communicate(self): if exception: raise exception return response, b"" mock_process = MockProcess(MagicMock(), MagicMock(), MagicMock()) with patch( "homeassistant.components.command_line.utils.asyncio.create_subprocess_shell", return_value=mock_process, ) as mock: yield mock
Mock config yaml store. Data is a dict {'key': {'version': version, 'data': data}} Written data will be converted to JSON to ensure JSON parsing works.
def mock_config_store(data=None): """Mock config yaml store. Data is a dict {'key': {'version': version, 'data': data}} Written data will be converted to JSON to ensure JSON parsing works. """ if data is None: data = {} def mock_read(path): """Mock version of load.""" file_name = basename(path) _LOGGER.info("Reading data from %s: %s", file_name, data.get(file_name)) return deepcopy(data.get(file_name)) def mock_write(path, data_to_write): """Mock version of write.""" file_name = basename(path) _LOGGER.info("Writing data to %s: %s", file_name, data_to_write) raise_contains_mocks(data_to_write) # To ensure that the data can be serialized data[file_name] = json.loads(json.dumps(data_to_write)) async def mock_async_hass_config_yaml(hass: HomeAssistant) -> dict: """Mock version of async_hass_config_yaml.""" result = {} # Return a configuration.yaml with "automation" mapped to the contents of # automations.yaml and so on. for key, value in data.items(): result[key.partition(".")[0][0:-1]] = deepcopy(value) _LOGGER.info("Reading data from configuration.yaml: %s", result) return result with ( patch( "homeassistant.components.config.view._read", side_effect=mock_read, autospec=True, ), patch( "homeassistant.components.config.view._write", side_effect=mock_write, autospec=True, ), patch( "homeassistant.config.async_hass_config_yaml", side_effect=mock_async_hass_config_yaml, autospec=True, ), ): yield data
Fixture to mock config yaml store.
def hass_config_store(): """Fixture to mock config yaml store.""" with mock_config_store() as stored_data: yield stored_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."""
Clear config entry handlers.
def clear_handlers(): """Clear config entry handlers.""" with patch.dict(HANDLERS, clear=True): yield
Ensure a component called 'test' exists.
def mock_test_component(hass): """Ensure a component called 'test' exists.""" mock_integration(hass, MockModule("test"))
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."""
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."""
Mock agent.
def mock_conversation_agent_fixture_helper(hass: HomeAssistant) -> MockAgent: """Mock agent.""" entry = MockConfigEntry(entry_id="mock-entry") entry.add_to_hass(hass) agent = MockAgent(entry.entry_id, ["smurfish"]) conversation.async_set_agent(hass, entry, agent) return agent
Mock agent that supports all languages.
def mock_agent_support_all(hass: HomeAssistant): """Mock agent that supports all languages.""" entry = MockConfigEntry(entry_id="mock-entry-support-all") entry.add_to_hass(hass) agent = MockAgent(entry.entry_id, MATCH_ALL) conversation.async_set_agent(hass, entry, agent) return agent
Stub out the persistence.
def mock_shopping_list_io(): """Stub out the persistence.""" with ( patch("homeassistant.components.shopping_list.ShoppingData.save"), patch("homeassistant.components.shopping_list.ShoppingData.async_load"), ): yield
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Test the create matcher method.
def test_create_matcher() -> None: """Test the create matcher method.""" # Basic sentence pattern = create_matcher("Hello world") assert pattern.match("Hello world") is not None # Match a part pattern = create_matcher("Hello {name}") match = pattern.match("hello world") assert match is not None assert match.groupdict()["name"] == "world" no_match = pattern.match("Hello world, how are you?") assert no_match is None # Optional and matching part pattern = create_matcher("Turn on [the] {name}") match = pattern.match("turn on the kitchen lights") assert match is not None assert match.groupdict()["name"] == "kitchen lights" match = pattern.match("turn on kitchen lights") assert match is not None assert match.groupdict()["name"] == "kitchen lights" match = pattern.match("turn off kitchen lights") assert match is None # Two different optional parts, 1 matching part pattern = create_matcher("Turn on [the] [a] {name}") match = pattern.match("turn on the kitchen lights") assert match is not None assert match.groupdict()["name"] == "kitchen lights" match = pattern.match("turn on kitchen lights") assert match is not None assert match.groupdict()["name"] == "kitchen lights" match = pattern.match("turn on a kitchen light") assert match is not None assert match.groupdict()["name"] == "kitchen light" # Strip plural pattern = create_matcher("Turn {name}[s] on") match = pattern.match("turn kitchen lights on") assert match is not None assert match.groupdict()["name"] == "kitchen light" # Optional 2 words pattern = create_matcher("Turn [the great] {name} on") match = pattern.match("turn the great kitchen lights on") assert match is not None assert match.groupdict()["name"] == "kitchen lights" match = pattern.match("turn kitchen lights on") assert match is not None assert match.groupdict()["name"] == "kitchen lights"
Enable exposing new entities to the default agent.
def expose_new(hass: HomeAssistant, expose_new: bool): """Enable exposing new entities to the default agent.""" exposed_entities: ExposedEntities = hass.data[DATA_EXPOSED_ENTITIES] exposed_entities.async_set_expose_new_entities(conversation.DOMAIN, expose_new)
Expose an entity to the default agent.
def expose_entity(hass: HomeAssistant, entity_id: str, should_expose: bool): """Expose an entity to the default agent.""" async_expose_entity(hass, conversation.DOMAIN, entity_id, should_expose)
Increment a counter.
def async_increment(hass, entity_id): """Increment a counter.""" hass.async_create_task( hass.services.async_call(DOMAIN, SERVICE_INCREMENT, {ATTR_ENTITY_ID: entity_id}) )
Decrement a counter.
def async_decrement(hass, entity_id): """Decrement a counter.""" hass.async_create_task( hass.services.async_call(DOMAIN, SERVICE_DECREMENT, {ATTR_ENTITY_ID: entity_id}) )
Reset a counter.
def async_reset(hass, entity_id): """Reset a counter.""" hass.async_create_task( hass.services.async_call(DOMAIN, SERVICE_RESET, {ATTR_ENTITY_ID: entity_id}) )
Storage setup.
def storage_setup(hass, hass_storage): """Storage setup.""" async def _storage(items=None, config=None): if items is None: hass_storage[DOMAIN] = { "key": DOMAIN, "version": 1, "data": { "items": [ { "id": "from_storage", "initial": 10, "name": "from storage", "maximum": 100, "minimum": 3, "step": 2, "restore": False, } ] }, } else: hass_storage[DOMAIN] = { "key": DOMAIN, "version": 1, "data": {"items": items}, } if config is None: config = {DOMAIN: {}} return await async_setup_component(hass, DOMAIN, config) return _storage
Return a list of MockCover instances.
def mock_cover_entities() -> list[MockCover]: """Return a list of MockCover instances.""" return [ MockCover( name="Simple cover", unique_id="unique_cover", supported_features=CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE, ), MockCover( name="Set position cover", unique_id="unique_set_pos_cover", current_cover_position=50, supported_features=CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE | CoverEntityFeature.STOP | CoverEntityFeature.SET_POSITION, ), MockCover( name="Simple tilt cover", unique_id="unique_tilt_cover", supported_features=CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE | CoverEntityFeature.OPEN_TILT | CoverEntityFeature.CLOSE_TILT, ), MockCover( name="Set tilt position cover", unique_id="unique_set_pos_tilt_cover", current_cover_tilt_position=50, supported_features=CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE | CoverEntityFeature.OPEN_TILT | CoverEntityFeature.CLOSE_TILT | CoverEntityFeature.STOP_TILT | CoverEntityFeature.SET_TILT_POSITION, ), MockCover( name="All functions cover", unique_id="unique_all_functions_cover", current_cover_position=50, current_cover_tilt_position=50, supported_features=CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE | CoverEntityFeature.STOP | CoverEntityFeature.SET_POSITION | CoverEntityFeature.OPEN_TILT | CoverEntityFeature.CLOSE_TILT | CoverEntityFeature.STOP_TILT | CoverEntityFeature.SET_TILT_POSITION, ), MockCover( name="Simple with opening/closing cover", unique_id="unique_opening_closing_cover", supported_features=CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE, reports_opening_closing=True, ), ]
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."""
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")