async def test_setup_websocket(hass, remotews, mock_now): """Test setup of platform.""" with patch("homeassistant.components.samsungtv.bridge.SamsungTVWS") as remote_class: enter = Mock() type(enter).token = PropertyMock(return_value="987654321") remote = Mock() remote.__enter__ = Mock(return_value=enter) remote.__exit__ = Mock() remote_class.return_value = remote await setup_samsungtv(hass, MOCK_CONFIGWS) assert remote_class.call_count == 1 assert remote_class.call_args_list == [call(**MOCK_CALLS_WS)] assert hass.states.get(ENTITY_ID)
async def test_yaml_updates_update_config_entry_for_name(hass): """Test async_setup with imported config.""" entry = MockConfigEntry( domain=DOMAIN, source=SOURCE_IMPORT, data={ CONF_NAME: BRIDGE_NAME, CONF_PORT: DEFAULT_PORT }, options={}, ) entry.add_to_hass(hass) with patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit: mock_homekit.return_value = homekit = Mock() type(homekit).async_start = AsyncMock() type(homekit).async_setup_zeroconf = AsyncMock() assert await async_setup_component( hass, "homekit", {"homekit": { CONF_NAME: BRIDGE_NAME, CONF_PORT: 12345 }}) await hass.async_block_till_done() mock_homekit.assert_any_call( hass, BRIDGE_NAME, 12345, None, ANY, {}, DEFAULT_SAFE_MODE, None, None, entry.entry_id, ) assert mock_homekit().setup.called is True # Test auto start enabled mock_homekit.reset_mock() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() mock_homekit().async_start.assert_called()
async def test_refresh_weather_forecast_exception() -> None: """Test any exception.""" hass = Mock() weather = weather_smhi.SmhiWeather("name", "17.0022", "62.0022") weather.hass = hass with patch.object(hass.helpers.event, "async_call_later") as call_later, patch.object( weather, "get_weather_forecast", side_effect=SmhiForecastException(), ): await weather.async_update() assert len(call_later.mock_calls) == 1 # Assert we are going to wait RETRY_TIMEOUT seconds assert call_later.mock_calls[0][1][0] == weather_smhi.RETRY_TIMEOUT
async def test_setup_failed_connect(hass): """Test setup when connection error occurs.""" respx.get("http://localhost", content=httpx.RequestError(message="any", request=Mock())) assert await async_setup_component( hass, binary_sensor.DOMAIN, { "binary_sensor": { "platform": "rest", "resource": "http://localhost", "method": "GET", } }, ) await hass.async_block_till_done() assert len(hass.states.async_all()) == 0
def remote_fixture(): """Patch the samsungctl Remote.""" with patch( "homeassistant.components.samsungtv.bridge.Remote" ) as remote_class, patch( "homeassistant.components.samsungtv.config_flow.socket" ) as socket_class: remote = Mock() remote.__enter__ = Mock() remote.__exit__ = Mock() remote_class.return_value = remote socket = Mock() socket_class.return_value = socket socket_class.gethostbyname.return_value = "FAKE_IP_ADDRESS" yield remote
async def test_zeroconf_flow(hass): """Test that zeroconf discovery for new devices work.""" with patch.object(axis, "get_device", return_value=Mock()): result = await hass.config_entries.flow.async_init( config_flow.DOMAIN, data={ config_flow.CONF_HOST: "1.2.3.4", config_flow.CONF_PORT: 80, "hostname": "name", "properties": { "macaddress": MAC }, }, context={"source": "zeroconf"}, ) assert result["type"] == "form" assert result["step_id"] == "user" with patch("axis.AxisDevice") as mock_device: setup_mock_axis_device(mock_device) result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={ config_flow.CONF_HOST: "1.2.3.4", config_flow.CONF_USERNAME: "******", config_flow.CONF_PASSWORD: "******", config_flow.CONF_PORT: 80, }, ) assert result["type"] == "create_entry" assert result["title"] == f"prodnbr - {MAC}" assert result["data"] == { config_flow.CONF_HOST: "1.2.3.4", config_flow.CONF_USERNAME: "******", config_flow.CONF_PASSWORD: "******", config_flow.CONF_PORT: 80, config_flow.CONF_MAC: MAC, config_flow.CONF_MODEL: "prodnbr", config_flow.CONF_NAME: "prodnbr 0", } assert result["data"][config_flow.CONF_NAME] == "prodnbr 0"
async def test_configure_service_with_faulty_entity(hass): """Test that service invokes pydeconz with the correct path and data.""" await setup_deconz_integration(hass) data = { deconz.services.SERVICE_ENTITY: "light.nonexisting", deconz.services.SERVICE_DATA: {}, } with patch("pydeconz.DeconzSession.request", return_value=Mock(True)) as put_state: await hass.services.async_call( deconz.DOMAIN, deconz.services.SERVICE_CONFIGURE_DEVICE, service_data=data) await hass.async_block_till_done() put_state.assert_not_called()
async def test_setup_entry_platform_not_ready(hass, caplog): """Test when an entry is not ready yet.""" async_setup_entry = Mock(side_effect=PlatformNotReady) platform = MockPlatform(async_setup_entry=async_setup_entry) config_entry = MockConfigEntry() ent_platform = MockEntityPlatform(hass, platform_name=config_entry.domain, platform=platform) with patch.object(entity_platform, "async_call_later") as mock_call_later: assert not await ent_platform.async_setup_entry(config_entry) full_name = f"{ent_platform.domain}.{config_entry.domain}" assert full_name not in hass.config.components assert len(async_setup_entry.mock_calls) == 1 assert "Platform test not ready yet" in caplog.text assert len(mock_call_later.mock_calls) == 1
async def test_unknown_failed(hass: HomeAssistantType, service: MagicMock): """Test when we have an unknown error.""" service.return_value.login = Mock( side_effect=SynologyDSMException(None, None)) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={ CONF_HOST: HOST, CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"}
async def test_delete_blueprint(hass, aioclient_mock, hass_ws_client): """Test deleting blueprints.""" with patch("pathlib.Path.unlink", return_value=Mock()) as unlink_mock: client = await hass_ws_client(hass) await client.send_json({ "id": 9, "type": "blueprint/delete", "path": "test_delete", "domain": "automation", }) msg = await client.receive_json() assert unlink_mock.mock_calls assert msg["id"] == 9 assert msg["success"]
def remotews_fixture(): """Patch the samsungtvws SamsungTVWS.""" with patch("homeassistant.components.samsungtv.bridge.SamsungTVWS" ) as remotews_class, patch( "homeassistant.components.samsungtv.config_flow.socket" ) as socket_class: remotews = Mock() remotews.__enter__ = Mock() remotews.__exit__ = Mock() remotews_class.return_value = remotews remotews_class().__enter__().token = "FAKE_TOKEN" socket = Mock() socket_class.return_value = socket socket_class.gethostbyname.return_value = "FAKE_IP_ADDRESS" yield remotews
def test_update_with_no_template(self): """Test update when there is no value template.""" self.rest.update = Mock( "rest.RestData.update", side_effect=self.update_side_effect("true") ) self.binary_sensor = rest.RestBinarySensor( self.hass, self.rest, self.name, self.device_class, None, self.force_update, self.resource_template, ) self.binary_sensor.update() assert STATE_ON == self.binary_sensor.state assert self.binary_sensor.available
async def test_connection_failed(hass: HomeAssistantType, service: MagicMock): """Test when we have errors during connection.""" service.return_value.login = Mock( side_effect=SynologyDSMRequestException(IOError("arg"))) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={ CONF_HOST: HOST, CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {CONF_HOST: "cannot_connect"}
def get_mock_remote( host="1.2.3.4", authorize_error=None, encrypted=False, app_id=None, encryption_key=None, name=DEFAULT_NAME, manufacturer="mock-manufacturer", model_number="mock-model-number", unique_id="mock-unique-id", ): """Return a mock remote.""" mock_remote = Mock() mock_remote.type = TV_TYPE_ENCRYPTED if encrypted else TV_TYPE_NONENCRYPTED mock_remote.app_id = app_id mock_remote.enc_key = encryption_key def request_pin_code(name=None): return mock_remote.request_pin_code = request_pin_code def authorize_pin_code(pincode): if pincode == "1234": return if authorize_error is not None: raise authorize_error mock_remote.authorize_pin_code = authorize_pin_code def get_device_info(): return { ATTR_FRIENDLY_NAME: name, ATTR_MANUFACTURER: manufacturer, ATTR_MODEL_NUMBER: model_number, ATTR_UDN: unique_id, } mock_remote.get_device_info = get_device_info return mock_remote
def device_factory_fixture(): """Fixture for creating mock devices.""" api = Mock(Api) api.post_device_command.return_value = { "results": [{ "status": "ACCEPTED" }] } def _factory(label, capabilities, status: dict = None): device_data = { "deviceId": str(uuid4()), "name": "Device Type Handler Name", "label": label, "deviceManufacturerCode": "9135fc86-0929-4436-bf73-5d75f523d9db", "locationId": "fcd829e9-82f4-45b9-acfd-62fda029af80", "components": [{ "id": "main", "capabilities": [{ "id": capability, "version": 1 } for capability in capabilities], }], "dth": { "deviceTypeId": "b678b29d-2726-4e4f-9c3f-7aa05bd08964", "deviceTypeName": "Switch", "deviceNetworkType": "ZWAVE", }, "type": "DTH", } device = DeviceEntity(api, data=device_data) if status: for attribute, value in status.items(): device.status.apply_attribute_update("main", "", attribute, value) return device return _factory
async def test_setup_reload_service(hass): """Test setting up a reload service.""" component_setup = Mock(return_value=True) setup_called = [] async def setup_platform(*args): setup_called.append(args) mock_integration(hass, MockModule(DOMAIN, setup=component_setup)) mock_integration(hass, MockModule(PLATFORM, dependencies=[DOMAIN])) mock_platform = MockPlatform(async_setup_platform=setup_platform) mock_entity_platform(hass, f"{DOMAIN}.{PLATFORM}", mock_platform) component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_setup( {DOMAIN: { "platform": PLATFORM, "sensors": None }}) await hass.async_block_till_done() assert component_setup.called assert f"{DOMAIN}.{PLATFORM}" in hass.config.components assert len(setup_called) == 1 await async_setup_reload_service(hass, PLATFORM, [DOMAIN]) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "helpers/reload_configuration.yaml", ) with patch.object(config, "YAML_CONFIG_FILE", yaml_path): await hass.services.async_call( PLATFORM, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert len(setup_called) == 2
async def test_send_key_connection_closed_retry_succeed(hass, remote): """Test retry on connection closed.""" await setup_samsungtv(hass, MOCK_CONFIG) remote.control = Mock(side_effect=[ exceptions.ConnectionClosed("Boom"), DEFAULT_MOCK, DEFAULT_MOCK ]) assert await hass.services.async_call(DOMAIN, SERVICE_VOLUME_UP, {ATTR_ENTITY_ID: ENTITY_ID}, True) state = hass.states.get(ENTITY_ID) # key because of retry two times and update called assert remote.control.call_count == 2 assert remote.control.call_args_list == [ call("KEY_VOLUP"), call("KEY_VOLUP"), ] assert remote.close.call_count == 1 assert remote.close.call_args_list == [call()] assert state.state == STATE_ON
async def test_call_with_required_features(hass, mock_entities): """Test service calls invoked only if entity has required features.""" test_service_mock = AsyncMock(return_value=None) await service.entity_service_call( hass, [Mock(entities=mock_entities)], test_service_mock, ha.ServiceCall("test_domain", "test_service", {"entity_id": "all"}), required_features=[SUPPORT_A], ) assert test_service_mock.call_count == 2 expected = [ mock_entities["light.kitchen"], mock_entities["light.bedroom"], ] actual = [call[0][0] for call in test_service_mock.call_args_list] assert all(entity in actual for entity in expected)
async def get_client(aiohttp_client, validator): """Generate a client that hits a view decorated with validator.""" app = web.Application() app["hass"] = Mock(is_running=True) class TestView(HomeAssistantView): url = "/" name = "test" requires_auth = False @validator async def post(self, request, data): """Test method.""" return b"" TestView().register(app, app.router) client = await aiohttp_client(app) return client
def mock_gateway(): """Mock a Tradfri gateway.""" def get_devices(): """Return mock devices.""" return gateway.mock_devices def get_groups(): """Return mock groups.""" return gateway.mock_groups gateway = Mock( get_devices=get_devices, get_groups=get_groups, mock_devices=[], mock_groups=[], mock_responses=[], ) return gateway
def test_air_quality_sensor_with_normal_reading(self): """Test air quality sensor.""" device = mock_device(10, "Family Room", "Canary Pro") location = mock_location("Home") data = Mock() data.get_reading.return_value = 1.0 sensor = CanarySensor(data, SENSOR_TYPES[2], location, device) sensor.update() assert sensor.name == "Home Family Room Air Quality" assert sensor.unit_of_measurement is None assert sensor.state == 1.0 assert sensor.icon == "mdi:weather-windy" air_quality = sensor.device_state_attributes[ATTR_AIR_QUALITY] assert air_quality == STATE_AIR_QUALITY_NORMAL
async def test_configure_service_with_field(hass): """Test that service invokes pydeconz with the correct path and data.""" await setup_deconz_integration(hass) data = { deconz.services.SERVICE_FIELD: "/light/2", CONF_BRIDGE_ID: BRIDGEID, deconz.services.SERVICE_DATA: {"on": True, "attr1": 10, "attr2": 20}, } with patch("pydeconz.DeconzSession.request", return_value=Mock(True)) as put_state: await hass.services.async_call( deconz.DOMAIN, deconz.services.SERVICE_CONFIGURE_DEVICE, service_data=data ) await hass.async_block_till_done() put_state.assert_called_with( "put", "/light/2", json={"on": True, "attr1": 10, "attr2": 20} )
def test_setup_scanner_timeout(): """Test setup_scanner failure from timeout.""" hass = get_test_home_assistant() hass.start() config = { "username": TEST_CALLSIGN, "password": TEST_PASSWORD, "host": "localhost", "timeout": 0.01, "callsigns": ["XX0FOO*", "YY0BAR-1"], } see = Mock() try: assert not device_tracker.setup_scanner(hass, config, see) finally: hass.stop()
async def test_configure_service_with_entity(hass): """Test that service invokes pydeconz with the correct path and data.""" gateway = await setup_deconz_integration(hass) gateway.deconz_ids["light.test"] = "/light/1" data = { deconz.services.SERVICE_ENTITY: "light.test", deconz.services.SERVICE_DATA: {"on": True, "attr1": 10, "attr2": 20}, } with patch("pydeconz.DeconzSession.request", return_value=Mock(True)) as put_state: await hass.services.async_call( deconz.DOMAIN, deconz.services.SERVICE_CONFIGURE_DEVICE, service_data=data ) await hass.async_block_till_done() put_state.assert_called_with( "put", "/light/1", json={"on": True, "attr1": 10, "attr2": 20} )
def cast_mock(): """Mock pychromecast.""" pycast_mock = MagicMock() pycast_mock.start_discovery.return_value = (None, Mock()) dial_mock = MagicMock(name="XXX") dial_mock.get_device_status.return_value.uuid = "fake_uuid" dial_mock.get_device_status.return_value.manufacturer = "fake_manufacturer" dial_mock.get_device_status.return_value.model_name = "fake_model_name" dial_mock.get_device_status.return_value.friendly_name = "fake_friendly_name" with patch( "homeassistant.components.cast.media_player.pychromecast", pycast_mock ), patch("homeassistant.components.cast.discovery.pychromecast", pycast_mock), patch( "homeassistant.components.cast.media_player.MultizoneManager", MagicMock()): yield
async def test_async_setup_entry_handles_auth_error(hass: HomeAssistant): """Test that configuring entry handles Plum Cloud authentication error.""" config_entry = MockConfigEntry( domain=DOMAIN, data={"username": "******", "password": "******"}, ) config_entry.add_to_hass(hass) with patch( "homeassistant.components.plum_lightpad.utils.Plum.loadCloudData", side_effect=ContentTypeError(Mock(), None), ), patch( "homeassistant.components.plum_lightpad.light.async_setup_entry" ) as mock_light_async_setup_entry: result = await hass.config_entries.async_setup(config_entry.entry_id) assert result is False assert len(mock_light_async_setup_entry.mock_calls) == 0
def test_id_map(self): """Test the hass to rtm task is mapping.""" hass_id = "hass-id-1234" list_id = "mylist" timeseries_id = "my_timeseries" rtm_id = "rtm-id-4567" with patch("builtins.open", mock_open()), patch( "os.path.isfile", Mock(return_value=False) ), patch.object(rtm.RememberTheMilkConfiguration, "save_config"): config = rtm.RememberTheMilkConfiguration(self.hass) assert config.get_rtm_id(self.profile, hass_id) is None config.set_rtm_id(self.profile, hass_id, list_id, timeseries_id, rtm_id) assert (list_id, timeseries_id, rtm_id) == config.get_rtm_id( self.profile, hass_id ) config.delete_rtm_id(self.profile, hass_id) assert config.get_rtm_id(self.profile, hass_id) is None
async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER}) assert result["type"] == "form" assert result["errors"] == {} with patch( "aioshelly.get_info", return_value={ "mac": "test-mac", "type": "SHSW-1", "auth": False }, ), patch( "aioshelly.Device.create", new=AsyncMock(return_value=Mock( shutdown=AsyncMock(), settings={ "name": "Test name", "device": { "mac": "test-mac" } }, )), ), patch("homeassistant.components.shelly.async_setup", return_value=True) as mock_setup, patch( "homeassistant.components.shelly.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], {"host": "1.1.1.1"}, ) assert result2["type"] == "create_entry" assert result2["title"] == "Test name" assert result2["data"] == { "host": "1.1.1.1", } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_zeroconf(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) with patch( "aioshelly.get_info", return_value={ "mac": "test-mac", "type": "SHSW-1", "auth": False }, ): result = await hass.config_entries.flow.async_init( DOMAIN, data=DISCOVERY_INFO, context={"source": config_entries.SOURCE_ZEROCONF}, ) assert result["type"] == "form" assert result["errors"] == {} context = next(flow["context"] for flow in hass.config_entries.flow.async_progress() if flow["flow_id"] == result["flow_id"]) assert context["title_placeholders"]["name"] == "shelly1pm-12345" with patch( "aioshelly.Device.create", new=AsyncMock(return_value=Mock(settings=MOCK_SETTINGS, )), ), patch("homeassistant.components.shelly.async_setup", return_value=True) as mock_setup, patch( "homeassistant.components.shelly.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], {}, ) await hass.async_block_till_done() assert result2["type"] == "create_entry" assert result2["title"] == "Test name" assert result2["data"] == { "host": "1.1.1.1", } assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_update_existing_device(mock_write, hass): """Test updating an existing device.""" yaml_file = { 1234: { "name": "test device 1" }, 5678: { "name": "test device 2" } } written_devices = [] def fake_write(_out, device): """Fake write_device.""" written_devices.append(device) mock_write.side_effect = fake_write with patch( "homeassistant.components.apns.notify.load_yaml_config_file", Mock(return_value=yaml_file), ): await _setup_notify(hass) assert await hass.services.async_call( apns.DOMAIN, "apns_test_app", { "push_id": "1234", "name": "updated device 1" }, blocking=True, ) devices = {dev.push_id: dev for dev in written_devices} test_device_1 = devices.get("1234") test_device_2 = devices.get("5678") assert test_device_1 is not None assert test_device_2 is not None assert "updated device 1" == test_device_1.name