response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.aftership.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.agent_dvr.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Add config entry in Home Assistant.
def create_entry(hass: HomeAssistant): """Add config entry in Home Assistant.""" entry = MockConfigEntry( domain=DOMAIN, unique_id="c0715bba-c2d0-48ef-9e3e-bc81c9ea4447", data=CONF_DATA, ) entry.add_to_hass(hass) return entry
Define a config entry fixture.
def config_entry_fixture(hass, config, options): """Define a config entry fixture.""" entry = MockConfigEntry( domain=DOMAIN, version=2, entry_id="3bd2acb0e4f0476d40865546d0d91921", unique_id=f"{config[CONF_LATITUDE]}-{config[CONF_LONGITUDE]}", data=config, options=options, ) entry.add_to_hass(hass) return entry
Define a config entry data fixture.
def config_fixture(hass): """Define a config entry data fixture.""" return { CONF_API_KEY: "abc123", CONF_LATITUDE: 34.053718, CONF_LONGITUDE: -118.244842, }
Define a config options data fixture.
def options_fixture(hass): """Define a config options data fixture.""" return { CONF_RADIUS: 150, }
Define a fixture for response data.
def data_fixture(): """Define a fixture for response data.""" return json.loads(load_fixture("response.json", "airnow"))
Define a fixture for a mock "get" coroutine function.
def mock_api_get_fixture(data): """Define a fixture for a mock "get" coroutine function.""" return AsyncMock(return_value=data)
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.airq.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Patch async setup entry to return True.
def patch_async_setup_entry(return_value=True): """Patch async setup entry to return True.""" return patch( "homeassistant.components.airthings_ble.async_setup_entry", return_value=return_value, )
Patch async ble device from address to return a given value.
def patch_async_ble_device_from_address(return_value: BluetoothServiceInfoBleak | None): """Patch async ble device from address to return a given value.""" return patch( "homeassistant.components.bluetooth.async_ble_device_from_address", return_value=return_value, )
Patch airthings-ble device fetcher with given values and effects.
def patch_airthings_ble(return_value=AirthingsDevice, side_effect=None): """Patch airthings-ble device fetcher with given values and effects.""" return patch.object( AirthingsBluetoothDeviceData, "update_device", return_value=return_value, side_effect=side_effect, )
Patch airthings-ble device.
def patch_airthings_device_update(): """Patch airthings-ble device.""" return patch( "homeassistant.components.airthings_ble.AirthingsBluetoothDeviceData.update_device", return_value=WAVE_DEVICE_INFO, )
Create a config entry.
def create_entry(hass): """Create a config entry.""" entry = MockConfigEntry( domain=DOMAIN, unique_id=WAVE_SERVICE_INFO.address, title="Airthings Wave Plus (123456)", ) entry.add_to_hass(hass) return entry
Create a device for the given entry.
def create_device(entry: ConfigEntry, device_registry: DeviceRegistry): """Create a device for the given entry.""" return device_registry.async_get_or_create( config_entry_id=entry.entry_id, connections={(CONNECTION_BLUETOOTH, WAVE_SERVICE_INFO.address)}, manufacturer="Airthings AS", name="Airthings Wave Plus (123456)", model="Wave Plus", )
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.airtouch5.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Define a mock CloudAPI object.
def cloud_api_fixture(data_cloud): """Define a mock CloudAPI object.""" return Mock( air_quality=Mock( city=AsyncMock(return_value=data_cloud), nearest_city=AsyncMock(return_value=data_cloud), ) )
Define a config entry fixture.
def config_entry_fixture(hass, config, config_entry_version, integration_type): """Define a config entry fixture.""" entry = MockConfigEntry( domain=DOMAIN, entry_id="3bd2acb0e4f0476d40865546d0d91921", unique_id=async_get_geography_id(config), data={**config, CONF_INTEGRATION_TYPE: integration_type}, options={CONF_SHOW_ON_MAP: True}, version=config_entry_version, ) entry.add_to_hass(hass) return entry
Define a config entry version fixture.
def config_entry_version_fixture(): """Define a config entry version fixture.""" return 2
Define a config entry data fixture.
def config_fixture(): """Define a config entry data fixture.""" return COORDS_CONFIG
Define an update coordinator data example.
def data_cloud_fixture(): """Define an update coordinator data example.""" return json.loads(load_fixture("data.json", "airvisual"))
Define an update coordinator data example for the Pro.
def data_pro_fixture(): """Define an update coordinator data example for the Pro.""" return json.loads(load_fixture("data.json", "airvisual_pro"))
Define an integration type.
def integration_type_fixture(): """Define an integration type.""" return INTEGRATION_TYPE_GEOGRAPHY_COORDS
Define a mock NodeSamba object.
def node_samba_fixture(data_pro): """Define a mock NodeSamba object.""" return Mock( async_connect=AsyncMock(), async_disconnect=AsyncMock(), async_get_latest_measurements=AsyncMock(return_value=data_pro), )
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.airvisual.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.airvisual_pro.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Define a config entry fixture.
def config_entry_fixture(hass, config): """Define a config entry fixture.""" entry = MockConfigEntry( domain=DOMAIN, entry_id="6a2b3770e53c28dc1eeb2515e906b0ce", unique_id="XXXXXXX", data=config, ) entry.add_to_hass(hass) return entry
Define a config entry data fixture.
def config_fixture(hass): """Define a config entry data fixture.""" return { CONF_IP_ADDRESS: "192.168.1.101", CONF_PASSWORD: "password123", }
Define a mocked async_connect method.
def connect_fixture(): """Define a mocked async_connect method.""" return AsyncMock(return_value=True)
Define a mocked async_connect method.
def disconnect_fixture(): """Define a mocked async_connect method.""" return AsyncMock()
Define an update coordinator data example.
def data_fixture(): """Define an update coordinator data example.""" return json.loads(load_fixture("data.json", "airvisual_pro"))
Define a mocked NodeSamba object.
def pro_fixture(connect, data, disconnect): """Define a mocked NodeSamba object.""" return Mock( async_connect=connect, async_disconnect=disconnect, async_get_latest_measurements=AsyncMock(return_value=data), )
Fixture to completely disable Airzone Cloud WebSockets.
def airzone_cloud_no_websockets(): """Fixture to completely disable Airzone Cloud WebSockets.""" with ( patch( "homeassistant.components.airzone_cloud.AirzoneCloudApi._update_websockets", return_value=False, ), patch( "homeassistant.components.airzone_cloud.AirzoneCloudApi.connect_installation_websockets", return_value=None, ), ): yield
Mock API device status.
def mock_get_device_status(device: Device) -> dict[str, Any]: """Mock API device status.""" if device.get_id() == "aidoo1": return { API_ACTIVE: False, API_ERRORS: [], API_MODE: OperationMode.HEATING.value, API_MODE_AVAIL: [ OperationMode.AUTO.value, OperationMode.COOLING.value, OperationMode.HEATING.value, OperationMode.VENTILATION.value, OperationMode.DRY.value, ], API_SP_AIR_AUTO: {API_CELSIUS: 22, API_FAH: 72}, API_SP_AIR_COOL: {API_CELSIUS: 22, API_FAH: 72}, API_SP_AIR_HEAT: {API_CELSIUS: 22, API_FAH: 72}, API_RANGE_MAX_AIR: {API_CELSIUS: 30, API_FAH: 86}, API_RANGE_SP_MAX_AUTO_AIR: {API_CELSIUS: 30, API_FAH: 86}, API_RANGE_SP_MAX_COOL_AIR: {API_CELSIUS: 30, API_FAH: 86}, API_RANGE_SP_MAX_HOT_AIR: {API_CELSIUS: 30, API_FAH: 86}, API_RANGE_MIN_AIR: {API_CELSIUS: 15, API_FAH: 59}, API_RANGE_SP_MIN_AUTO_AIR: {API_CELSIUS: 18, API_FAH: 64}, API_RANGE_SP_MIN_COOL_AIR: {API_CELSIUS: 18, API_FAH: 64}, API_RANGE_SP_MIN_HOT_AIR: {API_CELSIUS: 16, API_FAH: 61}, API_POWER: False, API_SPEED_CONF: 6, API_SPEED_VALUES: [2, 4, 6], API_SPEED_TYPE: 0, API_IS_CONNECTED: True, API_WS_CONNECTED: True, API_LOCAL_TEMP: {API_CELSIUS: 21, API_FAH: 70}, API_WARNINGS: [], } if device.get_id() == "aidoo_pro": return { API_ACTIVE: True, API_DOUBLE_SET_POINT: True, API_ERRORS: [], API_MODE: OperationMode.COOLING.value, API_MODE_AVAIL: [ OperationMode.AUTO.value, OperationMode.COOLING.value, OperationMode.HEATING.value, OperationMode.VENTILATION.value, OperationMode.DRY.value, ], API_SP_AIR_AUTO: {API_CELSIUS: 22, API_FAH: 72}, API_SP_AIR_COOL: {API_CELSIUS: 22, API_FAH: 72}, API_SP_AIR_HEAT: {API_CELSIUS: 18, API_FAH: 64}, API_RANGE_MAX_AIR: {API_CELSIUS: 30, API_FAH: 86}, API_RANGE_SP_MAX_AUTO_AIR: {API_CELSIUS: 30, API_FAH: 86}, API_RANGE_SP_MAX_COOL_AIR: {API_CELSIUS: 30, API_FAH: 86}, API_RANGE_SP_MAX_HOT_AIR: {API_CELSIUS: 30, API_FAH: 86}, API_RANGE_MIN_AIR: {API_CELSIUS: 15, API_FAH: 59}, API_RANGE_SP_MIN_AUTO_AIR: {API_CELSIUS: 18, API_FAH: 64}, API_RANGE_SP_MIN_COOL_AIR: {API_CELSIUS: 18, API_FAH: 64}, API_RANGE_SP_MIN_HOT_AIR: {API_CELSIUS: 16, API_FAH: 61}, API_POWER: True, API_SPEED_CONF: 3, API_SPEED_VALUES: [0, 1, 2, 3, 4, 5], API_SPEED_TYPE: 0, API_IS_CONNECTED: True, API_WS_CONNECTED: True, API_LOCAL_TEMP: {API_CELSIUS: 20, API_FAH: 68}, API_WARNINGS: [], } if device.get_id() == "dhw1": return { API_ACTIVE: False, API_ERRORS: [], API_POWER: False, API_POWERFUL_MODE: False, API_SETPOINT: {API_CELSIUS: 48, API_FAH: 118}, API_RANGE_SP_MAX_ACS: {API_CELSIUS: 60, API_FAH: 140}, API_RANGE_SP_MIN_ACS: {API_CELSIUS: 40, API_FAH: 104}, API_STEP: {API_CELSIUS: 1, API_FAH: 1}, API_TANK_TEMP: {API_CELSIUS: 45.5, API_FAH: 114}, API_IS_CONNECTED: True, API_WS_CONNECTED: True, API_WARNINGS: [], } if device.get_id() == "system1": return { API_AQ_MODE_VALUES: ["off", "on", "auto"], API_AQ_PM_1: 3, API_AQ_PM_2P5: 4, API_AQ_PM_10: 3, API_AQ_PRESENT: True, API_AQ_QUALITY: "good", API_ERRORS: [ { API_OLD_ID: "error-id", }, ], API_MODE: OperationMode.COOLING.value, API_MODE_AVAIL: [ OperationMode.COOLING.value, OperationMode.HEATING.value, OperationMode.VENTILATION.value, OperationMode.DRY.value, ], API_IS_CONNECTED: True, API_WS_CONNECTED: True, API_WARNINGS: [], } if device.get_id() == "zone1": return { API_ACTIVE: True, API_AQ_ACTIVE: False, API_AQ_MODE_CONF: "auto", API_AQ_MODE_VALUES: ["off", "on", "auto"], API_AQ_PM_1: 3, API_AQ_PM_2P5: 4, API_AQ_PM_10: 3, API_AQ_PRESENT: True, API_AQ_QUALITY: "good", API_DOUBLE_SET_POINT: False, API_HUMIDITY: 30, API_MODE: OperationMode.COOLING.value, API_MODE_AVAIL: [ OperationMode.COOLING.value, OperationMode.HEATING.value, OperationMode.VENTILATION.value, OperationMode.DRY.value, ], API_RANGE_MAX_AIR: {API_CELSIUS: 30, API_FAH: 86}, API_RANGE_SP_MAX_COOL_AIR: {API_FAH: 86, API_CELSIUS: 30}, API_RANGE_SP_MAX_DRY_AIR: {API_FAH: 86, API_CELSIUS: 30}, API_RANGE_SP_MAX_EMERHEAT_AIR: {API_CELSIUS: 30, API_FAH: 86}, API_RANGE_SP_MAX_HOT_AIR: {API_CELSIUS: 30, API_FAH: 86}, API_RANGE_SP_MAX_STOP_AIR: {API_FAH: 86, API_CELSIUS: 30}, API_RANGE_SP_MAX_VENT_AIR: {API_FAH: 86, API_CELSIUS: 30}, API_RANGE_MIN_AIR: {API_CELSIUS: 15, API_FAH: 59}, API_RANGE_SP_MIN_COOL_AIR: {API_CELSIUS: 18, API_FAH: 64}, API_RANGE_SP_MIN_DRY_AIR: {API_CELSIUS: 18, API_FAH: 64}, API_RANGE_SP_MIN_EMERHEAT_AIR: {API_FAH: 59, API_CELSIUS: 15}, API_RANGE_SP_MIN_HOT_AIR: {API_FAH: 59, API_CELSIUS: 15}, API_RANGE_SP_MIN_STOP_AIR: {API_FAH: 59, API_CELSIUS: 15}, API_RANGE_SP_MIN_VENT_AIR: {API_FAH: 59, API_CELSIUS: 15}, API_SP_AIR_COOL: {API_CELSIUS: 24, API_FAH: 75}, API_SP_AIR_DRY: {API_CELSIUS: 24, API_FAH: 75}, API_SP_AIR_HEAT: {API_CELSIUS: 20, API_FAH: 68}, API_SP_AIR_VENT: {API_CELSIUS: 24, API_FAH: 75}, API_SP_AIR_STOP: {API_CELSIUS: 24, API_FAH: 75}, API_POWER: True, API_IS_CONNECTED: True, API_WS_CONNECTED: True, API_LOCAL_TEMP: {API_FAH: 68, API_CELSIUS: 20}, API_WARNINGS: [], } if device.get_id() == "zone2": return { API_ACTIVE: False, API_AQ_ACTIVE: False, API_AQ_MODE_CONF: "auto", API_AQ_MODE_VALUES: ["off", "on", "auto"], API_AQ_PM_1: 3, API_AQ_PM_2P5: 4, API_AQ_PM_10: 3, API_AQ_PRESENT: True, API_AQ_QUALITY: "good", API_DOUBLE_SET_POINT: False, API_HUMIDITY: 24, API_MODE: OperationMode.COOLING.value, API_MODE_AVAIL: [], API_RANGE_MAX_AIR: {API_CELSIUS: 30, API_FAH: 86}, API_RANGE_SP_MAX_COOL_AIR: {API_FAH: 86, API_CELSIUS: 30}, API_RANGE_SP_MAX_DRY_AIR: {API_FAH: 86, API_CELSIUS: 30}, API_RANGE_SP_MAX_EMERHEAT_AIR: {API_CELSIUS: 30, API_FAH: 86}, API_RANGE_SP_MAX_HOT_AIR: {API_CELSIUS: 30, API_FAH: 86}, API_RANGE_SP_MAX_STOP_AIR: {API_FAH: 86, API_CELSIUS: 30}, API_RANGE_SP_MAX_VENT_AIR: {API_FAH: 86, API_CELSIUS: 30}, API_RANGE_MIN_AIR: {API_CELSIUS: 15, API_FAH: 59}, API_RANGE_SP_MIN_COOL_AIR: {API_CELSIUS: 18, API_FAH: 64}, API_RANGE_SP_MIN_DRY_AIR: {API_CELSIUS: 18, API_FAH: 64}, API_RANGE_SP_MIN_EMERHEAT_AIR: {API_FAH: 59, API_CELSIUS: 15}, API_RANGE_SP_MIN_HOT_AIR: {API_FAH: 59, API_CELSIUS: 15}, API_RANGE_SP_MIN_STOP_AIR: {API_FAH: 59, API_CELSIUS: 15}, API_RANGE_SP_MIN_VENT_AIR: {API_FAH: 59, API_CELSIUS: 15}, API_SP_AIR_COOL: {API_CELSIUS: 24, API_FAH: 75}, API_SP_AIR_DRY: {API_CELSIUS: 24, API_FAH: 75}, API_SP_AIR_HEAT: {API_CELSIUS: 20, API_FAH: 68}, API_SP_AIR_VENT: {API_CELSIUS: 24, API_FAH: 75}, API_SP_AIR_STOP: {API_CELSIUS: 24, API_FAH: 75}, API_POWER: False, API_IS_CONNECTED: True, API_WS_CONNECTED: True, API_LOCAL_TEMP: {API_FAH: 77, API_CELSIUS: 25}, API_WARNINGS: [], } return {}
Mock API get webserver.
def mock_get_webserver(webserver: WebServer, devices: bool) -> dict[str, Any]: """Mock API get webserver.""" if webserver.get_id() == WS_ID: return GET_WEBSERVER_MOCK if webserver.get_id() == WS_ID_AIDOO: return GET_WEBSERVER_MOCK_AIDOO if webserver.get_id() == WS_ID_AIDOO_PRO: return GET_WEBSERVER_MOCK_AIDOO_PRO return {}
Set up aladdin connect API fixture.
def fixture_mock_aladdinconnect_api(): """Set up aladdin connect API fixture.""" with mock.patch( "homeassistant.components.aladdin_connect.AladdinConnectClient" ) as mock_opener: mock_opener.login = AsyncMock(return_value=True) mock_opener.close = AsyncMock(return_value=True) mock_opener.async_get_door_status = AsyncMock(return_value="open") mock_opener.get_door_status.return_value = "open" mock_opener.async_get_door_link_status = AsyncMock(return_value="connected") mock_opener.get_door_link_status.return_value = "connected" mock_opener.async_get_battery_status = AsyncMock(return_value="99") mock_opener.get_battery_status.return_value = "99" mock_opener.async_get_rssi_status = AsyncMock(return_value="-55") mock_opener.get_rssi_status.return_value = "-55" mock_opener.async_get_ble_strength = AsyncMock(return_value="-45") mock_opener.get_ble_strength.return_value = "-45" mock_opener.get_doors = AsyncMock(return_value=[DEVICE_CONFIG_OPEN]) mock_opener.doors = [DEVICE_CONFIG_OPEN] mock_opener.register_callback = mock.Mock(return_value=True) mock_opener.open_door = AsyncMock(return_value=True) mock_opener.close_door = AsyncMock(return_value=True) return mock_opener
Mock Alarm control panel class.
def mock_alarm_control_panel_entities() -> dict[str, MockAlarm]: """Mock Alarm control panel class.""" return { "arm_code": MockAlarm( name="Alarm arm code", code_arm_required=True, unique_id="unique_arm_code", ), "no_arm_code": MockAlarm( name="Alarm no arm code", code_arm_required=False, unique_id="unique_no_arm_code", ), }
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: HomeAssistant) -> list[ServiceCall]: """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: HomeAssistant) -> list[ServiceCall]: """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 format constants.
def test_deprecated_constant_code_format( caplog: pytest.LogCaptureFixture, code_format: alarm_control_panel.CodeFormat, module: ModuleType, ) -> None: """Test deprecated format constants.""" import_and_test_deprecated_constant_enum( caplog, module, code_format, "FORMAT_", "2025.1" )
Test deprecated support alarm constants.
def test_deprecated_support_alarm_constants( caplog: pytest.LogCaptureFixture, entity_feature: alarm_control_panel.AlarmControlPanelEntityFeature, module: ModuleType, ) -> None: """Test deprecated support alarm constants.""" import_and_test_deprecated_constant_enum( caplog, module, entity_feature, "SUPPORT_ALARM_", "2025.1" )
Test deprecated supported features ints.
def test_deprecated_supported_features_ints(caplog: pytest.LogCaptureFixture) -> None: """Test deprecated supported features ints.""" class MockAlarmControlPanelEntity(alarm_control_panel.AlarmControlPanelEntity): _attr_supported_features = 1 entity = MockAlarmControlPanelEntity() assert ( entity.supported_features is alarm_control_panel.AlarmControlPanelEntityFeature(1) ) assert "MockAlarmControlPanelEntity" in caplog.text assert "is using deprecated supported features values" in caplog.text assert "Instead it should use" in caplog.text assert "AlarmControlPanelEntityFeature.ARM_HOME" in caplog.text caplog.clear() assert ( entity.supported_features is alarm_control_panel.AlarmControlPanelEntityFeature(1) ) assert "is using deprecated supported features values" not in caplog.text
Mock for notifier.
def mock_notifier(hass: HomeAssistant) -> list[ServiceCall]: """Mock for notifier.""" return async_mock_service(hass, notify.DOMAIN, NOTIFIER)
Return a MockConfig instance.
def get_default_config(hass): """Return a MockConfig instance.""" return MockConfig(hass)
Generate a new API message.
def get_new_request(namespace, name, endpoint=None): """Generate a new API message.""" raw_msg = { "directive": { "header": { "namespace": namespace, "name": name, "messageId": str(uuid4()), "correlationToken": str(uuid4()), "payloadVersion": "3", }, "endpoint": { "scope": {"type": "BearerToken", "token": str(uuid4())}, "endpointId": endpoint, }, "payload": {}, } } if not endpoint: raw_msg["directive"].pop("endpoint") return raw_msg
Initialize a Home Assistant server for testing this module.
def alexa_client(event_loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" loop = event_loop @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": { "flash_briefings": { "password": "pass/abc", "weather": [ { "title": "Weekly forecast", "text": "This week it will be sunny.", }, { "title": "Current conditions", "text": "Currently it is 80 degrees fahrenheit.", }, ], "news_audio": { "title": "NPR", "audio": NPR_NEWS_MP3_URL, "display_url": "https://npr.org", "uid": "uuid", }, } }, }, ) ) return loop.run_until_complete(hass_client())
Initialize a Home Assistant server for testing this module.
def alexa_client(event_loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" loop = event_loop @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "GetZodiacHoroscopeIDIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign_Id }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, APPLICATION_ID_SESSION_OPEN: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", }, "reprompt": { "type": "plain", "text": "LaunchRequest has been received.", }, }, } }, ) ) return loop.run_until_complete(hass_client())
Fixture that catches alexa events.
def events(hass: HomeAssistant) -> list[Event]: """Fixture that catches alexa events.""" return async_capture_events(hass, smart_home.EVENT_ALEXA_SMART_HOME)
Create an API message response of a request with defaults.
def test_create_api_message_defaults(hass: HomeAssistant) -> None: """Create an API message response of a request with defaults.""" request = get_new_request("Alexa.PowerController", "TurnOn", "switch#xy") directive_header = request["directive"]["header"] directive = state_report.AlexaDirective(request) msg = directive.response(payload={"test": 3})._response assert "event" in msg msg = msg["event"] assert msg["header"]["messageId"] is not None assert msg["header"]["messageId"] != directive_header["messageId"] assert msg["header"]["correlationToken"] == directive_header["correlationToken"] assert msg["header"]["name"] == "Response" assert msg["header"]["namespace"] == "Alexa" assert msg["header"]["payloadVersion"] == "3" assert "test" in msg["payload"] assert msg["payload"]["test"] == 3 assert msg["endpoint"] == request["directive"]["endpoint"] assert msg["endpoint"] is not request["directive"]["endpoint"]
Create an API message response of a request with non defaults.
def test_create_api_message_special() -> None: """Create an API message response of a request with non defaults.""" request = get_new_request("Alexa.PowerController", "TurnOn") directive_header = request["directive"]["header"] directive_header.pop("correlationToken") directive = state_report.AlexaDirective(request) msg = directive.response("testName", "testNameSpace")._response assert "event" in msg msg = msg["event"] assert msg["header"]["messageId"] is not None assert msg["header"]["messageId"] != directive_header["messageId"] assert "correlationToken" not in msg["header"] assert msg["header"]["name"] == "testName" assert msg["header"]["namespace"] == "testNameSpace" assert msg["header"]["payloadVersion"] == "3" assert msg["payload"] == {} assert "endpoint" not in msg
Search a set of capabilities for a specific one.
def get_capability(capabilities, capability_name, instance=None): """Search a set of capabilities for a specific one.""" for capability in capabilities: if instance and capability.get("instance") == instance: return capability if not instance and capability["interface"] == capability_name: return capability return None
Assert the endpoint supports the given interfaces. Returns a set of capabilities, in case you want to assert more things about them.
def assert_endpoint_capabilities(endpoint, *interfaces): """Assert the endpoint supports the given interfaces. Returns a set of capabilities, in case you want to assert more things about them. """ capabilities = endpoint["capabilities"] supported = {feature["interface"] for feature in capabilities} assert supported == {interface for interface in interfaces if interface is not None} return capabilities
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.amberelectric.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Generate a mock actual interval.
def generate_actual_interval( channel_type: ChannelType, end_time: datetime ) -> ActualInterval: """Generate a mock actual interval.""" start_time = end_time - timedelta(minutes=30) return ActualInterval( duration=30, spot_per_kwh=1.0, per_kwh=8.0, date=start_time.date(), nem_time=end_time, start_time=start_time, end_time=end_time, renewables=50, channel_type=channel_type.value, spike_status=SpikeStatus.NO_SPIKE.value, descriptor=Descriptor.LOW.value, )
Generate a mock current price.
def generate_current_interval( channel_type: ChannelType, end_time: datetime ) -> CurrentInterval: """Generate a mock current price.""" start_time = end_time - timedelta(minutes=30) return CurrentInterval( duration=30, spot_per_kwh=1.0, per_kwh=8.0, date=start_time.date(), nem_time=end_time, start_time=start_time, end_time=end_time, renewables=50.6, channel_type=channel_type.value, spike_status=SpikeStatus.NO_SPIKE.value, descriptor=Descriptor.EXTREMELY_LOW.value, estimate=True, )
Generate a mock forecast interval.
def generate_forecast_interval( channel_type: ChannelType, end_time: datetime ) -> ForecastInterval: """Generate a mock forecast interval.""" start_time = end_time - timedelta(minutes=30) return ForecastInterval( duration=30, spot_per_kwh=1.1, per_kwh=8.8, date=start_time.date(), nem_time=end_time, start_time=start_time, end_time=end_time, renewables=50, channel_type=channel_type.value, spike_status=SpikeStatus.NO_SPIKE.value, descriptor=Descriptor.VERY_LOW.value, estimate=True, )
Testing the creation of the Amber renewables sensor.
def test_no_spike_sensor(hass: HomeAssistant, setup_no_spike) -> None: """Testing the creation of the Amber renewables sensor.""" assert len(hass.states.async_all()) == 5 sensor = hass.states.get("binary_sensor.mock_title_price_spike") assert sensor assert sensor.state == "off" assert sensor.attributes["icon"] == "mdi:power-plug" assert sensor.attributes["spike_status"] == "none"
Testing the creation of the Amber renewables sensor.
def test_potential_spike_sensor(hass: HomeAssistant, setup_potential_spike) -> None: """Testing the creation of the Amber renewables sensor.""" assert len(hass.states.async_all()) == 5 sensor = hass.states.get("binary_sensor.mock_title_price_spike") assert sensor assert sensor.state == "off" assert sensor.attributes["icon"] == "mdi:power-plug-outline" assert sensor.attributes["spike_status"] == "potential"
Testing the creation of the Amber renewables sensor.
def test_spike_sensor(hass: HomeAssistant, setup_spike) -> None: """Testing the creation of the Amber renewables sensor.""" assert len(hass.states.async_all()) == 5 sensor = hass.states.get("binary_sensor.mock_title_price_spike") assert sensor assert sensor.state == "on" assert sensor.attributes["icon"] == "mdi:power-plug-off" assert sensor.attributes["spike_status"] == "spike"
Return an authentication error.
def mock_invalid_key_api() -> Generator: """Return an authentication error.""" with patch("amberelectric.api.AmberApi.create") as mock: mock.return_value.get_sites.side_effect = ApiException(status=403) yield mock
Return an authentication error.
def mock_api_error() -> Generator: """Return an authentication error.""" with patch("amberelectric.api.AmberApi.create") as mock: mock.return_value.get_sites.side_effect = ApiException(status=500) yield mock
Return a single site.
def mock_single_site_api() -> Generator: """Return a single site.""" site = Site( "01FG0AGP818PXK0DWHXJRRT2DH", "11111111111", [], "Jemena", SiteStatus.ACTIVE, date(2002, 1, 1), None, ) with patch("amberelectric.api.AmberApi.create") as mock: mock.return_value.get_sites.return_value = [site] yield mock
Return a single site.
def mock_single_site_pending_api() -> Generator: """Return a single site.""" site = Site( "01FG0AGP818PXK0DWHXJRRT2DH", "11111111111", [], "Jemena", SiteStatus.PENDING, None, None, ) with patch("amberelectric.api.AmberApi.create") as mock: mock.return_value.get_sites.return_value = [site] yield mock
Return a single site.
def mock_single_site_rejoin_api() -> Generator: """Return a single site.""" instance = Mock() site_1 = Site( "01HGD9QB72HB3DWQNJ6SSCGXGV", "11111111111", [], "Jemena", SiteStatus.CLOSED, date(2002, 1, 1), date(2002, 6, 1), ) site_2 = Site( "01FG0AGP818PXK0DWHXJRRT2DH", "11111111111", [], "Jemena", SiteStatus.ACTIVE, date(2003, 1, 1), None, ) site_3 = Site( "01FG0AGP818PXK0DWHXJRRT2DH", "11111111112", [], "Jemena", SiteStatus.CLOSED, date(2003, 1, 1), date(2003, 6, 1), ) instance.get_sites.return_value = [site_1, site_2, site_3] with patch("amberelectric.api.AmberApi.create", return_value=instance): yield instance
Return no site.
def mock_no_site_api() -> Generator: """Return no site.""" instance = Mock() instance.get_sites.return_value = [] with patch("amberelectric.api.AmberApi.create", return_value=instance): yield instance
Return an authentication error.
def mock_api_current_price() -> Generator: """Return an authentication error.""" instance = Mock() general_site = Site( GENERAL_ONLY_SITE_ID, "11111111111", [Channel(identifier="E1", type=ChannelType.GENERAL, tariff="A100")], "Jemena", SiteStatus.ACTIVE, date(2021, 1, 1), None, ) general_and_controlled_load = Site( GENERAL_AND_CONTROLLED_SITE_ID, "11111111112", [ Channel(identifier="E1", type=ChannelType.GENERAL, tariff="A100"), Channel(identifier="E2", type=ChannelType.CONTROLLED_LOAD, tariff="A180"), ], "Jemena", SiteStatus.ACTIVE, date(2021, 1, 1), None, ) general_and_feed_in = Site( GENERAL_AND_FEED_IN_SITE_ID, "11111111113", [ Channel(identifier="E1", type=ChannelType.GENERAL, tariff="A100"), Channel(identifier="E2", type=ChannelType.FEED_IN, tariff="A100"), ], "Jemena", SiteStatus.ACTIVE, date(2021, 1, 1), None, ) instance.get_sites.return_value = [ general_site, general_and_controlled_load, general_and_feed_in, ] with patch("amberelectric.api.AmberApi.create", return_value=instance): yield instance
Test normalizing descriptors works correctly.
def test_normalize_descriptor() -> None: """Test normalizing descriptors works correctly.""" assert normalize_descriptor(None) is None assert normalize_descriptor(Descriptor.NEGATIVE) == "negative" assert normalize_descriptor(Descriptor.EXTREMELY_LOW) == "extremely_low" assert normalize_descriptor(Descriptor.VERY_LOW) == "very_low" assert normalize_descriptor(Descriptor.LOW) == "low" assert normalize_descriptor(Descriptor.NEUTRAL) == "neutral" assert normalize_descriptor(Descriptor.HIGH) == "high" assert normalize_descriptor(Descriptor.SPIKE) == "spike"
Testing the creation of the Amber renewables sensor.
def test_renewable_sensor(hass: HomeAssistant, setup_general) -> None: """Testing the creation of the Amber renewables sensor.""" assert len(hass.states.async_all()) == 5 sensor = hass.states.get("sensor.mock_title_renewables") assert sensor assert sensor.state == "51"
Test the General Price Descriptor sensor.
def test_general_price_descriptor_descriptor_sensor( hass: HomeAssistant, setup_general: Mock ) -> None: """Test the General Price Descriptor sensor.""" assert len(hass.states.async_all()) == 5 price = hass.states.get("sensor.mock_title_general_price_descriptor") assert price assert price.state == "extremely_low"
Test the Controlled Price Descriptor sensor.
def test_general_and_controlled_load_price_descriptor_sensor( hass: HomeAssistant, setup_general_and_controlled_load: Mock ) -> None: """Test the Controlled Price Descriptor sensor.""" assert len(hass.states.async_all()) == 8 price = hass.states.get("sensor.mock_title_controlled_load_price_descriptor") assert price assert price.state == "extremely_low"
Test the Feed In Price Descriptor sensor.
def test_general_and_feed_in_price_descriptor_sensor( hass: HomeAssistant, setup_general_and_feed_in: Mock ) -> None: """Test the Feed In Price Descriptor sensor.""" assert len(hass.states.async_all()) == 8 price = hass.states.get("sensor.mock_title_feed_in_price_descriptor") assert price assert price.state == "extremely_low"
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.ambient_network.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Return result of OpenAPI get_devices_by_location() call.
def devices_by_location_fixture() -> list[dict[str, Any]]: """Return result of OpenAPI get_devices_by_location() call.""" return load_json_array_fixture( "devices_by_location_response.json", "ambient_network" )
Return result of OpenAPI get_device_details() call.
def mock_device_details_callable(mac_address: str) -> dict[str, Any]: """Return result of OpenAPI get_device_details() call.""" return load_json_object_fixture( f"device_details_response_{mac_address[0].lower()}.json", "ambient_network" )
Mock OpenAPI object.
def mock_open_api() -> OpenAPI: """Mock OpenAPI object.""" return Mock( get_device_details=AsyncMock(side_effect=mock_device_details_callable), )
Mock config entry.
def config_entry_fixture(request) -> MockConfigEntry: """Mock config entry.""" return MockConfigEntry( domain=ambient_network.DOMAIN, title=f"Station {request.param[0]}", data={"mac": request.param}, )
Define a mock API object.
def api_fixture(hass, data_devices): """Define a mock API object.""" return Mock(get_devices=AsyncMock(return_value=data_devices))
Define a config entry data fixture.
def config_fixture(hass): """Define a config entry data fixture.""" return { CONF_API_KEY: "12345abcde12345abcde", CONF_APP_KEY: "67890fghij67890fghij", }
Define a config entry fixture.
def config_entry_fixture(hass, config): """Define a config entry fixture.""" entry = MockConfigEntry( domain=DOMAIN, data=config, entry_id="382cf7643f016fd48b3fe52163fe8877", ) entry.add_to_hass(hass) return entry
Define devices data.
def data_devices_fixture(): """Define devices data.""" return json.loads(load_fixture("devices.json", "ambient_station"))
Define station data.
def data_station_fixture(): """Define station data.""" return json.loads(load_fixture("station_data.json", "ambient_station"))
Mock the UUID.
def uuid_mock() -> Generator[Any, Any, None]: """Mock the UUID.""" with patch("uuid.UUID.hex", new_callable=PropertyMock) as hex_mock: hex_mock.return_value = MOCK_UUID yield
Mock the core version.
def ha_version_mock() -> Generator[Any, Any, None]: """Mock the core version.""" with patch( "homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION, ): yield
Mock the async_get_system_info.
def installation_type_mock() -> Generator[Any, Any, None]: """Mock the async_get_system_info.""" with patch( "homeassistant.components.analytics.analytics.async_get_system_info", return_value={"installation_type": "Home Assistant Tests"}, ): yield
Return the payload of the last call.
def _last_call_payload(aioclient: AiohttpClientMocker) -> dict[str, Any]: """Return the payload of the last call.""" return aioclient.mock_calls[-1][2]
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.analytics_insights.async_setup_entry", return_value=True, ) as mock_setup_entry: yield mock_setup_entry
Mock a Homeassistant Analytics client.
def mock_analytics_client() -> Generator[AsyncMock, None, None]: """Mock a Homeassistant Analytics client.""" with ( patch( "homeassistant.components.analytics_insights.HomeassistantAnalyticsClient", autospec=True, ) as mock_client, patch( "homeassistant.components.analytics_insights.config_flow.HomeassistantAnalyticsClient", new=mock_client, ), ): client = mock_client.return_value client.get_current_analytics.return_value = CurrentAnalytics.from_json( load_fixture("analytics_insights/current_data.json") ) integrations = load_json_object_fixture("analytics_insights/integrations.json") client.get_integrations.return_value = { key: Integration.from_dict(value) for key, value in integrations.items() } custom_integrations = load_json_object_fixture( "analytics_insights/custom_integrations.json" ) client.get_custom_integrations.return_value = { key: CustomIntegration.from_dict(value) for key, value in custom_integrations.items() } yield client
Mock a config entry.
def mock_config_entry() -> MockConfigEntry: """Mock a config entry.""" return MockConfigEntry( domain=DOMAIN, title="Homeassistant Analytics", data={}, options={ CONF_TRACKED_INTEGRATIONS: ["youtube", "spotify", "myq"], CONF_TRACKED_CUSTOM_INTEGRATIONS: ["hacs"], }, )
Mock the `adb_shell.adb_device_async.AdbDeviceTcpAsync` and `ClientAsync` classes.
def patch_connect(success): """Mock the `adb_shell.adb_device_async.AdbDeviceTcpAsync` and `ClientAsync` classes.""" async def connect_success_python(self, *args, **kwargs): """Mock the `AdbDeviceTcpAsyncFake.connect` method when it succeeds.""" self.available = True async def connect_fail_python(self, *args, **kwargs): """Mock the `AdbDeviceTcpAsyncFake.connect` method when it fails.""" raise OSError if success: return { KEY_PYTHON: patch( f"{__name__}.{ADB_DEVICE_TCP_ASYNC_FAKE}.connect", connect_success_python, ), KEY_SERVER: patch( "androidtv.adb_manager.adb_manager_async.ClientAsync", ClientAsyncFakeSuccess, ), } return { KEY_PYTHON: patch( f"{__name__}.{ADB_DEVICE_TCP_ASYNC_FAKE}.connect", connect_fail_python ), KEY_SERVER: patch( "androidtv.adb_manager.adb_manager_async.ClientAsync", ClientAsyncFakeFail ), }
Mock the `AdbDeviceTcpAsyncFake.shell` and `DeviceAsyncFake.shell` methods.
def patch_shell(response=None, error=False, mac_eth=False, exc=None): """Mock the `AdbDeviceTcpAsyncFake.shell` and `DeviceAsyncFake.shell` methods.""" async def shell_success(self, cmd, *args, **kwargs): """Mock the `AdbDeviceTcpAsyncFake.shell` and `DeviceAsyncFake.shell` methods when they are successful.""" self.shell_cmd = cmd if cmd == CMD_DEVICE_PROPERTIES: return PROPS_DEV_INFO if cmd == CMD_MAC_WLAN0: return PROPS_DEV_MAC if cmd == CMD_MAC_ETH0: return PROPS_DEV_MAC if mac_eth else None return response async def shell_fail_python(self, cmd, *args, **kwargs): """Mock the `AdbDeviceTcpAsyncFake.shell` method when it fails.""" self.shell_cmd = cmd raise exc or ValueError async def shell_fail_server(self, cmd): """Mock the `DeviceAsyncFake.shell` method when it fails.""" self.shell_cmd = cmd raise ConnectionResetError if not error: return { KEY_PYTHON: patch( f"{__name__}.{ADB_DEVICE_TCP_ASYNC_FAKE}.shell", shell_success ), KEY_SERVER: patch(f"{__name__}.{DEVICE_ASYNC_FAKE}.shell", shell_success), } return { KEY_PYTHON: patch( f"{__name__}.{ADB_DEVICE_TCP_ASYNC_FAKE}.shell", shell_fail_python ), KEY_SERVER: patch(f"{__name__}.{DEVICE_ASYNC_FAKE}.shell", shell_fail_server), }
Patch the `AndroidTV.update()` method.
def patch_androidtv_update( state, current_app, running_apps, device, is_volume_muted, volume_level, hdmi_input, ): """Patch the `AndroidTV.update()` method.""" return { DEVICE_ANDROIDTV: patch( "androidtv.androidtv.androidtv_async.AndroidTVAsync.update", return_value=( state, current_app, running_apps, device, is_volume_muted, volume_level, hdmi_input, ), ), DEVICE_FIRETV: patch( "androidtv.firetv.firetv_async.FireTVAsync.update", return_value=(state, current_app, running_apps, hdmi_input), ), }
Mock `os.path.isfile`.
def isfile(filepath): """Mock `os.path.isfile`.""" return filepath.endswith("adbkey")
Patch ADB Device TCP.
def adb_device_tcp_fixture() -> None: """Patch ADB Device TCP.""" with patch( "androidtv.adb_manager.adb_manager_async.AdbDeviceTcpAsync", patchers.AdbDeviceTcpAsyncFake, ): yield
Patch load_adbkey.
def load_adbkey_fixture() -> None: """Patch load_adbkey.""" with patch( "homeassistant.components.androidtv.ADBPythonSync.load_adbkey", return_value="signer for testing", ): yield
Patch keygen.
def keygen_fixture() -> None: """Patch keygen.""" with patch( "homeassistant.components.androidtv.keygen", return_value=Mock(), ): yield