async def _mock_setup_august_with_api_side_effects(hass, api_call_side_effects): api_instance = MagicMock(name="Api") if api_call_side_effects["get_lock_detail"]: type(api_instance).async_get_lock_detail = AsyncMock( side_effect=api_call_side_effects["get_lock_detail"]) if api_call_side_effects["get_operable_locks"]: type(api_instance).async_get_operable_locks = AsyncMock( side_effect=api_call_side_effects["get_operable_locks"]) if api_call_side_effects["get_doorbells"]: type(api_instance).async_get_doorbells = AsyncMock( side_effect=api_call_side_effects["get_doorbells"]) if api_call_side_effects["get_doorbell_detail"]: type(api_instance).async_get_doorbell_detail = AsyncMock( side_effect=api_call_side_effects["get_doorbell_detail"]) if api_call_side_effects["get_house_activities"]: type(api_instance).async_get_house_activities = AsyncMock( side_effect=api_call_side_effects["get_house_activities"]) if api_call_side_effects["lock_return_activities"]: type(api_instance).async_lock_return_activities = AsyncMock( side_effect=api_call_side_effects["lock_return_activities"]) if api_call_side_effects["unlock_return_activities"]: type(api_instance).async_unlock_return_activities = AsyncMock( side_effect=api_call_side_effects["unlock_return_activities"]) return await _mock_setup_august(hass, api_instance)
async def test_config_entry_withings_api(hass: HomeAssistant) -> None: """Test ConfigEntryWithingsApi.""" config_entry = MockConfigEntry( data={"token": {"access_token": "mock_access_token", "expires_at": 1111111}} ) config_entry.add_to_hass(hass) implementation_mock = MagicMock(spec=AbstractOAuth2Implementation) implementation_mock.async_refresh_token.return_value = { "expires_at": 1111111, "access_token": "mock_access_token", } with requests_mock.mock() as rqmck: rqmck.get( re.compile(".*"), status_code=200, json={"status": 0, "body": {"message": "success"}}, ) api = ConfigEntryWithingsApi(hass, config_entry, implementation_mock) response = await hass.async_add_executor_job( api.request, "test", {"arg1": "val1", "arg2": "val2"} ) assert response == {"message": "success"}
async def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue(index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = "label" value.help = "help" value.type = "type" value.data = "data" value.data_items = ["item1", "item2"] value.max = "max" value.min = "min" node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = await client.get("/api/zwave/config/2") assert resp.status == 200 result = await resp.json() assert result == { "12": { "data": "data", "data_items": ["item1", "item2"], "help": "help", "label": "label", "max": "max", "min": "min", "type": "type", } }
async def test_async_setup_no_config(hass: HomeAssistant) -> None: """Test method.""" hass.async_create_task = MagicMock() await async_setup(hass, {}) hass.async_create_task.assert_not_called()
async def test_options_flow_power(hass, mock_smile) -> None: """Test config flow options DSMR environments.""" entry = MockConfigEntry( domain=DOMAIN, title=CONF_NAME, data={ CONF_HOST: TEST_HOST, CONF_PASSWORD: TEST_PASSWORD }, options={CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL}, ) hass.data[DOMAIN] = { entry.entry_id: { "api": MagicMock(smile_type="power") } } entry.add_to_hass(hass) with patch("homeassistant.components.plugwise.async_setup_entry", return_value=True): assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_SCAN_INTERVAL: 10}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"] == { CONF_SCAN_INTERVAL: 10, }
def mock_location(name, is_celsius=True, devices=None): """Mock Canary Location class.""" location = MagicMock() type(location).name = PropertyMock(return_value=name) type(location).is_celsius = PropertyMock(return_value=is_celsius) type(location).devices = PropertyMock(return_value=devices or []) return location
def mock_batch_timeout(hass, monkeypatch): """Mock the event bus listener and the batch timeout for tests.""" hass.bus.listen = MagicMock() monkeypatch.setattr( f"{INFLUX_PATH}.InfluxThread.batch_timeout", Mock(return_value=0), )
async def test_stop_discovery_called_on_stop(hass): """Test pychromecast.stop_discovery called on shutdown.""" browser = MagicMock(zc={}) with patch( "homeassistant.components.cast.discovery.pychromecast.start_discovery", return_value=browser, ) as start_discovery: # start_discovery should be called with empty config await async_setup_cast(hass, {}) assert start_discovery.call_count == 1 with patch( "homeassistant.components.cast.discovery.pychromecast.discovery.stop_discovery" ) as stop_discovery: # stop discovery should be called on shutdown hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) await hass.async_block_till_done() stop_discovery.assert_called_once_with(browser) with patch( "homeassistant.components.cast.discovery.pychromecast.start_discovery", return_value=browser, ) as start_discovery: # start_discovery should be called again on re-startup await async_setup_cast(hass) assert start_discovery.call_count == 1
async def test_connection_errors_retry(hass, dsmr_connection_fixture): """Connection should be retried on error during setup.""" (connection_factory, transport, protocol) = dsmr_connection_fixture entry_data = { "port": "/dev/ttyUSB0", "dsmr_version": "2.2", "precision": 4, "reconnect_interval": 0, "serial_id": "1234", "serial_id_gas": "5678", } # override the mock to have it fail the first time and succeed after first_fail_connection_factory = MagicMock( return_value=(transport, protocol), side_effect=chain([TimeoutError], repeat(DEFAULT)), ) mock_entry = MockConfigEntry(domain="dsmr", unique_id="/dev/ttyUSB0", data=entry_data) mock_entry.add_to_hass(hass) with patch( "homeassistant.components.dsmr.sensor.create_dsmr_reader", first_fail_connection_factory, ): await hass.config_entries.async_setup(mock_entry.entry_id) await hass.async_block_till_done() # wait for sleep to resolve await hass.async_block_till_done() assert first_fail_connection_factory.call_count >= 2, "connecting not retried"
def test_as_dict(self): """Test as dict.""" self.config.config_dir = "/test/ha-config" self.config.hass = MagicMock() type(self.config.hass.state).value = PropertyMock( return_value="RUNNING") expected = { "latitude": 0, "longitude": 0, "elevation": 0, CONF_UNIT_SYSTEM: METRIC_SYSTEM.as_dict(), "location_name": "Home", "time_zone": "UTC", "components": set(), "config_dir": "/test/ha-config", "whitelist_external_dirs": set(), "allowlist_external_dirs": set(), "allowlist_external_urls": set(), "version": __version__, "config_source": "default", "safe_mode": False, "state": "RUNNING", "external_url": None, "internal_url": None, } assert expected == self.config.as_dict()
async def test_import_fail(gogogate2api_mock, hass: HomeAssistant) -> None: """Test the failure to import.""" api = MagicMock(spec=GogoGate2Api) api.info.side_effect = ApiError(22, "Error") gogogate2api_mock.return_value = api hass_config = { HA_DOMAIN: { CONF_UNIT_SYSTEM: CONF_UNIT_SYSTEM_METRIC }, COVER_DOMAIN: [{ CONF_PLATFORM: "gogogate2", CONF_NAME: "cover0", CONF_DEVICE: DEVICE_TYPE_GOGOGATE2, CONF_IP_ADDRESS: "127.0.1.0", CONF_USERNAME: "******", CONF_PASSWORD: "******", }], } await async_process_ha_core_config(hass, hass_config[HA_DOMAIN]) assert await async_setup_component(hass, HA_DOMAIN, {}) assert await async_setup_component(hass, COVER_DOMAIN, hass_config) await hass.async_block_till_done() entity_ids = hass.states.async_entity_ids(COVER_DOMAIN) assert not entity_ids
async def test_async_setup_entry(hass): """Test the sensor.""" fake_async_add_entities = MagicMock() fake_srp_energy_client = MagicMock() fake_srp_energy_client.usage.return_value = [{1, 2, 3, 1.999, 4}] fake_config = MagicMock( data={ "name": "SRP Energy", "is_tou": False, "id": "0123456789", "username": "******", "password": "******", }) hass.data[SRP_ENERGY_DOMAIN] = fake_srp_energy_client await async_setup_entry(hass, fake_config, fake_async_add_entities)
def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() mock_kira = MagicMock() self.hass.data[kira.DOMAIN] = {kira.CONF_SENSOR: {}} self.hass.data[kira.DOMAIN][kira.CONF_SENSOR]["kira"] = mock_kira self.addCleanup(self.hass.stop)
async def test_discovery_already_configured_name(hass, mock_client): """Test discovery aborts if already configured via name.""" entry = MockConfigEntry( domain="esphome", data={ CONF_HOST: "192.168.43.183", CONF_PORT: 6053, CONF_PASSWORD: "" }, ) entry.add_to_hass(hass) mock_entry_data = MagicMock() mock_entry_data.device_info.name = "test8266" hass.data[DATA_KEY] = {entry.entry_id: mock_entry_data} service_info = { "host": "192.168.43.184", "port": 6053, "hostname": "test8266.local.", "properties": { "address": "test8266.local" }, } result = await hass.config_entries.flow.async_init( "esphome", context={"source": "zeroconf"}, data=service_info) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "already_configured" assert entry.unique_id == "test8266" assert entry.data[CONF_HOST] == "192.168.43.184"
async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION, ) value.label = "Protection Test" value.data_items = [ "Unprotected", "Protection by Sequence", "No Operation Possible", ] value.data = "Unprotected" network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( "/api/zwave/protection/18", data=json.dumps({"value_id": "123456", "selection": "Protecton by Sequence"}), ) assert resp.status == HTTP_NOT_FOUND result = await resp.json() assert not node.set_protection.called assert result == {"message": "Node not found"}
async def _patched_refresh_access_token( hass, new_token, new_token_expire_time, refresh_access_token_mock, should_refresh_mock, authenticate_mock, async_get_operable_locks_mock, ): authenticate_mock.side_effect = MagicMock( return_value=_mock_august_authentication( "original_token", 1234, AuthenticationState.AUTHENTICATED)) august_gateway = AugustGateway(hass) mocked_config = _mock_get_config() await august_gateway.async_setup(mocked_config[DOMAIN]) await august_gateway.async_authenticate() should_refresh_mock.return_value = False await august_gateway.async_refresh_access_token_if_needed() refresh_access_token_mock.assert_not_called() should_refresh_mock.return_value = True refresh_access_token_mock.return_value = _mock_august_authentication( new_token, new_token_expire_time, AuthenticationState.AUTHENTICATED) await august_gateway.async_refresh_access_token_if_needed() refresh_access_token_mock.assert_called() assert august_gateway.access_token == new_token assert august_gateway.authentication.access_token_expires == new_token_expire_time
async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION, ) value.label = "Protection Test" value.data_items = [ "Unprotected", "Protection by Sequence", "No Operation Possible", ] value.data = "Unprotected" network.nodes = {17: node} node.value = value resp = await client.get("/api/zwave/protection/18") assert resp.status == HTTP_NOT_FOUND result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {"message": "Node not found"}
def _mocked_bulb(cannot_connect=False): bulb = MagicMock() type(bulb).get_capabilities = MagicMock( return_value=None if cannot_connect else CAPABILITIES) type(bulb).get_model_specs = MagicMock(return_value=_MODEL_SPECS[MODEL]) bulb.capabilities = CAPABILITIES bulb.model = MODEL bulb.bulb_type = BulbType.Color bulb.last_properties = PROPERTIES bulb.music_mode = False return bulb
async def _async_test( bulb_type, model, target_properties, nightlight_properties=None, name=UNIQUE_NAME, entity_id=ENTITY_LIGHT, ): config_entry = MockConfigEntry( domain=DOMAIN, data={ **CONFIG_ENTRY_DATA, CONF_NIGHTLIGHT_SWITCH: False, }, ) config_entry.add_to_hass(hass) mocked_bulb.bulb_type = bulb_type model_specs = _MODEL_SPECS.get(model) type(mocked_bulb).get_model_specs = MagicMock(return_value=model_specs) await _async_setup(config_entry) state = hass.states.get(entity_id) assert state.state == "on" target_properties["friendly_name"] = name target_properties["flowing"] = False target_properties["night_light"] = True assert dict(state.attributes) == target_properties await hass.config_entries.async_unload(config_entry.entry_id) await config_entry.async_remove(hass) registry = await entity_registry.async_get_registry(hass) registry.async_clear_config_entry(config_entry.entry_id) # nightlight if nightlight_properties is None: return config_entry = MockConfigEntry( domain=DOMAIN, data={ **CONFIG_ENTRY_DATA, CONF_NIGHTLIGHT_SWITCH: True, }, ) config_entry.add_to_hass(hass) await _async_setup(config_entry) assert hass.states.get(entity_id).state == "off" state = hass.states.get(f"{entity_id}_nightlight") assert state.state == "on" nightlight_properties["friendly_name"] = f"{name} nightlight" nightlight_properties["icon"] = "mdi:weather-night" nightlight_properties["flowing"] = False nightlight_properties["night_light"] = True assert dict(state.attributes) == nightlight_properties await hass.config_entries.async_unload(config_entry.entry_id) await config_entry.async_remove(hass) registry.async_clear_config_entry(config_entry.entry_id)
async def test_unknown_path(hass, simple_queue, hass_client): """Test error logged from unknown path.""" await async_setup_component(hass, system_log.DOMAIN, BASIC_CONFIG) _LOGGER.findCaller = MagicMock(return_value=("unknown_path", 0, None, None)) _LOGGER.error("error message") await _async_block_until_queue_empty(hass, simple_queue) log = (await get_error_log(hass, hass_client, 1))[0] assert log["source"] == ["unknown_path", 0]
async def test_network_node_changed_from_notification(hass, mock_openzwave): """Test for network_node_changed.""" zwave_network = MagicMock() node = mock_zwave.MockNode() entity = node_entity.ZWaveNodeEntity(node, zwave_network) with patch.object(entity, "maybe_schedule_update") as mock: mock_zwave.notification(node_id=node.node_id) mock.assert_called_once_with()
def _partition_mock(): return MagicMock( triggered=False, arming=False, armed=False, disarmed=False, partially_armed=False, )
async def test_event_listener_component_override_measurement( hass, mock_client, config_ext, get_write_api, get_mock_call ): """Test the event listener with overridden measurements.""" config = { "component_config": { "sensor.fake_humidity": {"override_measurement": "humidity"} }, "component_config_glob": { "binary_sensor.*motion": {"override_measurement": "motion"} }, "component_config_domain": {"climate": {"override_measurement": "hvac"}}, } config.update(config_ext) handler_method = await _setup(hass, mock_client, config, get_write_api) test_components = [ {"domain": "sensor", "id": "fake_humidity", "res": "humidity"}, {"domain": "binary_sensor", "id": "fake_motion", "res": "motion"}, {"domain": "climate", "id": "fake_thermostat", "res": "hvac"}, {"domain": "other", "id": "just_fake", "res": "other.just_fake"}, ] for comp in test_components: state = MagicMock( state=1, domain=comp["domain"], entity_id=f"{comp['domain']}.{comp['id']}", object_id=comp["id"], attributes={}, ) event = MagicMock(data={"new_state": state}, time_fired=12345) body = [ { "measurement": comp["res"], "tags": {"domain": comp["domain"], "entity_id": comp["id"]}, "time": 12345, "fields": {"value": 1}, } ] handler_method(event) hass.data[influxdb.DOMAIN].block_till_done() write_api = get_write_api(mock_client) assert write_api.call_count == 1 assert write_api.call_args == get_mock_call(body) write_api.reset_mock()
def test_config_get_deprecated_new(mock_get_logger): """Test deprecated class object.""" mock_logger = MagicMock() mock_get_logger.return_value = mock_logger config = {"new_name": True} assert get_deprecated(config, "new_name", "old_name") is True assert not mock_logger.warning.called
def _mock_august_authentication(token_text, token_timestamp, state): authentication = MagicMock(name="august.authentication") type(authentication).state = PropertyMock(return_value=state) type(authentication).access_token = PropertyMock(return_value=token_text) type(authentication).access_token_expires = PropertyMock( return_value=token_timestamp ) return authentication
async def test_onboarding(hass: HomeAssistant) -> None: """Test setting up via onboarding.""" with patch(MODULE, return_value=MagicMock()): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "onboarding"}, ) assert result["type"] == RESULT_TYPE_CREATE_ENTRY
async def test_import(ismartgateapi_mock, gogogate2api_mock, hass: HomeAssistant) -> None: """Test importing of file based config.""" api0 = MagicMock(spec=GogoGate2Api) api0.info.return_value = _mocked_gogogate_open_door_response() gogogate2api_mock.return_value = api0 api1 = MagicMock(spec=ISmartGateApi) api1.info.return_value = _mocked_ismartgate_closed_door_response() ismartgateapi_mock.return_value = api1 hass_config = { HA_DOMAIN: { CONF_UNIT_SYSTEM: CONF_UNIT_SYSTEM_METRIC }, COVER_DOMAIN: [ { CONF_PLATFORM: "gogogate2", CONF_NAME: "cover0", CONF_DEVICE: DEVICE_TYPE_GOGOGATE2, CONF_IP_ADDRESS: "127.0.1.0", CONF_USERNAME: "******", CONF_PASSWORD: "******", }, { CONF_PLATFORM: "gogogate2", CONF_NAME: "cover1", CONF_DEVICE: DEVICE_TYPE_ISMARTGATE, CONF_IP_ADDRESS: "127.0.1.1", CONF_USERNAME: "******", CONF_PASSWORD: "******", }, ], } await async_process_ha_core_config(hass, hass_config[HA_DOMAIN]) assert await async_setup_component(hass, HA_DOMAIN, {}) assert await async_setup_component(hass, COVER_DOMAIN, hass_config) await hass.async_block_till_done() entity_ids = hass.states.async_entity_ids(COVER_DOMAIN) assert entity_ids is not None assert len(entity_ids) == 3 assert "cover.door1" in entity_ids assert "cover.door1_2" in entity_ids assert "cover.door2" in entity_ids
async def test_scene( hass: HomeAssistant, vera_component_factory: ComponentFactory ) -> None: """Test function.""" vera_scene = MagicMock(spec=pv.VeraScene) # type: pv.VeraScene vera_scene.scene_id = 1 vera_scene.name = "dev1" entity_id = "scene.dev1_1" await vera_component_factory.configure_component( hass=hass, controller_config=new_simple_controller_config(scenes=(vera_scene,)), ) await hass.services.async_call( "scene", "turn_on", {"entity_id": entity_id}, ) await hass.async_block_till_done()
async def _mock_setup_august(hass, api_instance, authenticate_mock, api_mock): """Set up august integration.""" authenticate_mock.side_effect = MagicMock( return_value=_mock_august_authentication("original_token", 1234)) api_mock.return_value = api_instance assert await async_setup_component(hass, DOMAIN, _mock_get_config()) await hass.async_block_till_done() return True
async def test_invalid_service_calls(hass): """Test invalid service call arguments get discarded.""" add_entities = MagicMock() await group.async_setup_platform( hass, {"entities": ["light.test1", "light.test2"]}, add_entities) await hass.async_block_till_done() await hass.async_start() await hass.async_block_till_done() assert add_entities.call_count == 1 grouped_light = add_entities.call_args[0][0][0] grouped_light.hass = hass with tests.async_mock.patch.object(hass.services, "async_call") as mock_call: await grouped_light.async_turn_on(brightness=150, four_oh_four="404") data = { ATTR_ENTITY_ID: ["light.test1", "light.test2"], ATTR_BRIGHTNESS: 150 } mock_call.assert_called_once_with(LIGHT_DOMAIN, SERVICE_TURN_ON, data, blocking=True, context=None) mock_call.reset_mock() await grouped_light.async_turn_off(transition=4, four_oh_four="404") data = { ATTR_ENTITY_ID: ["light.test1", "light.test2"], ATTR_TRANSITION: 4 } mock_call.assert_called_once_with(LIGHT_DOMAIN, SERVICE_TURN_OFF, data, blocking=True, context=None) mock_call.reset_mock() data = { ATTR_BRIGHTNESS: 150, ATTR_XY_COLOR: (0.5, 0.42), ATTR_RGB_COLOR: (80, 120, 50), ATTR_COLOR_TEMP: 1234, ATTR_WHITE_VALUE: 1, ATTR_EFFECT: "Sunshine", ATTR_TRANSITION: 4, ATTR_FLASH: "long", } await grouped_light.async_turn_on(**data) data[ATTR_ENTITY_ID] = ["light.test1", "light.test2"] data.pop(ATTR_RGB_COLOR) data.pop(ATTR_XY_COLOR) mock_call.assert_called_once_with(LIGHT_DOMAIN, SERVICE_TURN_ON, data, blocking=True, context=None)