async def test_get_translations_loads_config_flows(hass, mock_config_flows): """Test the get translations helper loads config flow translations.""" mock_config_flows.append("component1") integration = Mock(file_path=pathlib.Path(__file__)) integration.name = "Component 1" with patch.object( translation, "component_translation_path", return_value="bla.json"), patch.object( translation, "load_translations_files", return_value={"component1": { "hello": "world" }}, ), patch( "homeassistant.helpers.translation.async_get_integration", return_value=integration, ): translations = await translation.async_get_translations( hass, "en", "hello", config_flow=True) assert translations == { "component.component1.hello": "world", } assert "component1" not in hass.config.components
async def test_smartapp_update_configures_flow(hass): """Test update event continues an existing flow.""" # Arrange flow_id = str(uuid4()) flows = [{"flow_id": flow_id, "handler": DOMAIN}] app = Mock() app.app_id = uuid4() request = Mock() request.installed_app_id = str(uuid4()) request.auth_token = str(uuid4()) request.location_id = str(uuid4()) request.refresh_token = str(uuid4()) # Act with patch.object( hass.config_entries.flow, "async_progress", return_value=flows ), patch.object(hass.config_entries.flow, "async_configure") as configure_mock: await smartapp.smartapp_update(hass, request, None, app) configure_mock.assert_called_once_with( flow_id, { CONF_INSTALLED_APP_ID: request.installed_app_id, CONF_LOCATION_ID: request.location_id, CONF_REFRESH_TOKEN: request.refresh_token, }, )
async def test_step_pat_app_created_cloudhook(hass, app, app_oauth_client, location, smartthings_mock): """Test SmartApp is created with a cloudhook and shows location form.""" hass.config.components.add("cloud") # Unload the endpoint so we can reload it under the cloud. await smartapp.unload_smartapp_endpoint(hass) with patch.object(hass.components.cloud, "async_active_subscription", return_value=True), patch.object( hass.components.cloud, "async_create_cloudhook", return_value=mock_coro("http://cloud.test"), ) as mock_create_cloudhook: await smartapp.setup_smartapp_endpoint(hass) flow = SmartThingsFlowHandler() flow.hass = hass smartthings_mock.apps.return_value = [] smartthings_mock.create_app.return_value = (app, app_oauth_client) smartthings_mock.locations.return_value = [location] token = str(uuid4()) result = await flow.async_step_pat({CONF_ACCESS_TOKEN: token}) assert flow.access_token == token assert flow.app_id == app.app_id assert flow.oauth_client_secret == app_oauth_client.client_secret assert flow.oauth_client_id == app_oauth_client.client_id assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "select_location" assert mock_create_cloudhook.call_count == 1
async def test_cloudhook_app_created_then_show_wait_form( hass, app, app_oauth_client, smartthings_mock): """Test SmartApp is created with a cloudhoko and shows wait form.""" hass.config.components.add("cloud") # Unload the endpoint so we can reload it under the cloud. await smartapp.unload_smartapp_endpoint(hass) with patch.object( cloud, "async_active_subscription", return_value=True), patch.object( cloud, "async_create_cloudhook", return_value="http://cloud.test") as mock_create_cloudhook: await smartapp.setup_smartapp_endpoint(hass) flow = SmartThingsFlowHandler() flow.hass = hass smartthings_mock.apps.return_value = [] smartthings_mock.create_app.return_value = (app, app_oauth_client) result = await flow.async_step_user({"access_token": str(uuid4())}) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "wait_install" assert mock_create_cloudhook.call_count == 1
async def test_debouncer(self): """Test debouncer behavior.""" hass = self.hass entry = MockConfigEntry( domain=DOMAIN, data=DEFAULT_DATA, options=DEFAULT_OPTIONS, unique_id=DEFAULT_DATA["server_id"], ) mock_plex_server = MockPlexServer(config_entry=entry) with patch("plexapi.server.PlexServer", return_value=mock_plex_server), patch( "homeassistant.components.plex.PlexWebsocket.listen"): entry.add_to_hass(hass) assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() server_id = mock_plex_server.machineIdentifier with patch.object( mock_plex_server, "clients", return_value=[]), patch.object(mock_plex_server, "sessions", return_value=[]) as mock_update: # Called immediately async_dispatcher_send( hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) await hass.async_block_till_done() assert mock_update.call_count == 1 # Throttled async_dispatcher_send( hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) await hass.async_block_till_done() assert mock_update.call_count == 1 # Throttled async_dispatcher_send( hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) await hass.async_block_till_done() assert mock_update.call_count == 1 # Called from scheduler await self.advance(DEBOUNCE_TIMEOUT) await hass.async_block_till_done() assert mock_update.call_count == 2 # Throttled async_dispatcher_send( hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) await hass.async_block_till_done() assert mock_update.call_count == 2 # Called from scheduler await self.advance(DEBOUNCE_TIMEOUT) await hass.async_block_till_done() assert mock_update.call_count == 3
async def test_failed_update_successful_login(hass): """Running update can login when requested.""" controller = await setup_unifi_integration( hass, ENTRY_CONFIG, options={ unifi.CONF_BLOCK_CLIENT: ["random mac"], unifi.const.CONF_TRACK_CLIENTS: False, unifi.const.CONF_TRACK_DEVICES: False, }, sites=SITES, clients_response=[], devices_response=[], clients_all_response=[], ) assert len(controller.mock_requests) == 3 assert len(hass.states.async_all()) == 2 with patch.object(controller.api.clients, "update", side_effect=aiounifi.LoginRequired), patch.object( controller.api, "login", return_value=Mock(True)): await controller.async_update() await hass.async_block_till_done() assert controller.available is True
async def test_005_stop(self): with patch.object(self.nyuki._services, 'stop') as mock: # Do not really close the loop as it would break other tests with patch.object(self.nyuki, '_stop_loop'): await self.nyuki.stop() mock.assert_called_once_with() assert_true(self.nyuki.is_stopping)
async def test_upload_from_url(url): async with MediaPeonyClient("", "") as dummy_peony_client: async with MediaRequest(url) as media_request: async def dummy_get(get_url): assert get_url == url return media_request async def dummy_request(url, method, future, data=None, skip_params=None): assert url == dummy_peony_client.upload.media.upload.url() assert method.lower() == 'post' assert data['media'] == media_request.content assert skip_params future.set_result(None) with patch.object(dummy_peony_client, '_session') as session: session.get = dummy_get with patch.object(dummy_peony_client, 'request', side_effect=dummy_request): await dummy_peony_client.upload_media(url, chunked=False)
async def test_get_translations_while_loading_components(hass): """Test the get translations helper loads config flow translations.""" integration = Mock(file_path=pathlib.Path(__file__)) integration.name = "Component 1" hass.config.components.add("component1") async def mock_load_translation_files(files): """Mock load translation files.""" # Mimic race condition by loading a component during setup await async_setup_component(hass, "persistent_notification", {}) return {"component1": {"hello": "world"}} with patch.object( translation, "component_translation_path", return_value="bla.json"), patch.object( translation, "load_translations_files", side_effect=mock_load_translation_files, ), patch( "homeassistant.helpers.translation.async_get_integration", return_value=integration, ): translations = await translation.async_get_translations( hass, "en", "hello") assert translations == { "component.component1.hello": "world", }
async def test_setup_with_config_entry(hass): """Test setup component with config.""" mock_plex_server = MockPlexServer() entry = MockConfigEntry( domain=const.DOMAIN, data=DEFAULT_DATA, options=DEFAULT_OPTIONS, unique_id=DEFAULT_DATA["server_id"], ) with patch("plexapi.server.PlexServer", return_value=mock_plex_server), patch( "homeassistant.components.plex.PlexWebsocket.listen" ) as mock_listen: entry.add_to_hass(hass) assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() assert mock_listen.called assert len(hass.config_entries.async_entries(const.DOMAIN)) == 1 assert entry.state == ENTRY_STATE_LOADED server_id = mock_plex_server.machineIdentifier loaded_server = hass.data[const.DOMAIN][const.SERVERS][server_id] assert loaded_server.plex_server == mock_plex_server assert server_id in hass.data[const.DOMAIN][const.DISPATCHERS] assert server_id in hass.data[const.DOMAIN][const.WEBSOCKETS] assert (hass.data[const.DOMAIN][const.PLATFORMS_COMPLETED][server_id] == const.PLATFORMS) async_dispatcher_send(hass, const.PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) await hass.async_block_till_done() sensor = hass.states.get("sensor.plex_plex_server_1") assert sensor.state == str(len(mock_plex_server.accounts)) async_dispatcher_send(hass, const.PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) await hass.async_block_till_done() with patch.object(mock_plex_server, "clients", side_effect=plexapi.exceptions.BadRequest): async_dispatcher_send( hass, const.PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) await hass.async_block_till_done() with patch.object(mock_plex_server, "clients", side_effect=requests.exceptions.RequestException): async_dispatcher_send( hass, const.PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) await hass.async_block_till_done()
async def setup_entry(hass, entry): """Test that setup entry works.""" with patch.object( deconz.DeconzGateway, "async_setup", return_value=True ), patch.object( deconz.DeconzGateway, "async_update_device_registry", return_value=True ): assert await deconz.async_setup_entry(hass, entry) is True
async def test_try_connection(dyn_bridge): """Test that try connection works.""" # successful with patch.object(dyn_bridge.dynalite_devices, "connected", True): assert await dyn_bridge.try_connection() # unsuccessful with patch.object(dyn_bridge.dynalite_devices, "connected", False), patch( "homeassistant.components.dynalite.bridge.CONNECT_INTERVAL", 0): assert not await dyn_bridge.try_connection()
async def test_002_destroy_server(self): with patch.object(self._api, '_handler') as i_handler: i_handler.shutdown.return_value = make_future([]) with patch.object(self._api, '_server') as i_server: i_server.wait_closed.return_value = make_future([]) with patch.object(self._api._server, 'close') as call_close: await self._api.stop() eq_(call_close.call_count, 1) eq_(i_server.wait_closed.call_count, 1)
async def test_002_destroy_server(self): with patch.object(self._api, '_handler') as i_handler: i_handler.finish_connections.return_value = make_future([]) with patch.object(self._api, '_server') as i_server: i_server.wait_closed.return_value = make_future([]) with patch.object(self._api._server, 'close') as call_close: await self._api.destroy() eq_(call_close.call_count, 1) eq_(i_server.wait_closed.call_count, 1)
async def test_it_returns_a_dummy_task_if_logging_isnt_enabled_for_level( self): logger = Logger.with_default_handlers() self.assertIsNone(logger._dummy_task) with patch.object(logger, "isEnabledFor", return_value=False) as isEnabledFor, patch.object( logger, "_dummy_task") as _dummy_task: log_task = logger.info("im disabled") isEnabledFor.assert_called_once_with(logging.INFO) self.assertEqual(log_task, _dummy_task)
async def test_failed_update_successful_login(hass): """Running update can login when requested.""" controller = await setup_unifi_integration(hass) with patch.object(controller.api.clients, "update", side_effect=aiounifi.LoginRequired), patch.object( controller.api, "login", return_value=Mock(True)): await controller.async_update() await hass.async_block_till_done() assert controller.available is True
async def test_auth_auth_check_and_register_with_exception(hass): """Test auth client registration.""" config = {HMIPC_HAPID: "ABC123", HMIPC_PIN: "123", HMIPC_NAME: "hmip"} hmip_auth = HomematicipAuth(hass, config) hmip_auth.auth = Mock(spec=AsyncAuth) with patch.object( hmip_auth.auth, "isRequestAcknowledged", side_effect=HmipConnectionError ), patch.object( hmip_auth.auth, "requestAuthToken", side_effect=HmipConnectionError ): assert not await hmip_auth.async_checkbutton() assert await hmip_auth.async_register() is False
async def test_get_by_reset_password_code(user_service): with patch.object( PostgreSQLUserStore, "find_by_reset_password_code", side_effect=DoesNotExistException ): with pytest.raises(UserNotExistError): await user_service.get_by_reset_password_code("token") with patch.object(PostgreSQLUserStore, "find_by_reset_password_code") as p: user = gen_user() p.return_value = user u = await user_service.get_by_reset_password_code("token") assert u == user
async def test_failed_update_failed_login(hass): """Running update can handle a failed login.""" controller = await setup_unifi_integration(hass) with patch.object(controller.api.clients, "update", side_effect=aiounifi.LoginRequired), patch.object( controller.api, "login", side_effect=aiounifi.AiounifiException): await controller.async_update() await hass.async_block_till_done() assert controller.available is False
async def test_auth_auth_check_and_register(hass): """Test auth client registration.""" config = {HMIPC_HAPID: "ABC123", HMIPC_PIN: "123", HMIPC_NAME: "hmip"} hmip_auth = HomematicipAuth(hass, config) hmip_auth.auth = Mock(spec=AsyncAuth) with patch.object(hmip_auth.auth, "isRequestAcknowledged", return_value=True), patch.object( hmip_auth.auth, "requestAuthToken", return_value="ABC"), patch.object( hmip_auth.auth, "confirmAuthToken"): assert await hmip_auth.async_checkbutton() assert await hmip_auth.async_register() == "ABC"
async def test_register(user_service): with patch.object(PostgreSQLUserStore, "exist_by_email", return_value=True): with pytest.raises(UserExistError): await user_service.register(gen_reg_form()) with patch.object(PostgreSQLUserStore, "exist_by_email", return_value=False): with patch.object(PostgreSQLUserStore, "add") as add: form = gen_reg_form() def side_effect_check(user): assert user.email == form.email return user add.side_effect = side_effect_check await user_service.register(form)
async def test_bridge_import_flow(hass): """Test a bridge entry gets created and set up during the import flow.""" entry_mock_data = { CONF_HOST: "1.1.1.1", CONF_KEYFILE: "", CONF_CERTFILE: "", CONF_CA_CERTS: "", } with patch( "homeassistant.components.lutron_caseta.async_setup_entry", return_value=True, ) as mock_setup_entry, patch.object(Smartbridge, "create_tls") as create_tls: create_tls.return_value = MockBridge(can_connect=True) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=entry_mock_data, ) assert result["type"] == "create_entry" assert result["title"] == CasetaConfigFlow.ENTRY_DEFAULT_TITLE assert result["data"] == entry_mock_data await hass.async_block_till_done() assert len(mock_setup_entry.mock_calls) == 1
async def test_security_vuln_check(hass): """Test that we report security vulnerabilities.""" assert await async_setup_component(hass, "persistent_notification", {}) entry = MockConfigEntry(domain=hue.DOMAIN, data={"host": "0.0.0.0"}) entry.add_to_hass(hass) config = Mock(bridgeid="", mac="", modelid="BSB002", swversion="1935144020") config.name = "Hue" with patch.object( hue, "HueBridge", Mock(return_value=Mock(async_setup=CoroutineMock( return_value=True), api=Mock(config=config))), ): assert await async_setup_component(hass, "hue", {}) await hass.async_block_till_done() state = hass.states.get("persistent_notification.hue_hub_firmware") assert state is not None assert "CVE-2020-6007" in state.attributes["message"]
async def test_003d_publish_unknown_topic(self, send_mock): self.bus._connected.set() with patch.object(self.bus._mucs, 'joinMUC') as join_mock: asyncio.ensure_future(self.bus.publish({'test': 'message'}, 'unknown/topic')) await exhaust_callbacks(self.loop) join_mock.assert_called_once_with('*****@*****.**', 'test') eq_(send_mock.call_count, 1)
async def test_bridge_cannot_connect(hass): """Test checking for connection and cannot_connect error.""" entry_mock_data = { CONF_HOST: "not.a.valid.host", CONF_KEYFILE: "", CONF_CERTFILE: "", CONF_CA_CERTS: "", } with patch( "homeassistant.components.lutron_caseta.async_setup_entry", return_value=True, ) as mock_setup_entry, patch.object(Smartbridge, "create_tls") as create_tls: create_tls.return_value = MockBridge(can_connect=False) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=entry_mock_data, ) assert result["type"] == "form" assert result["step_id"] == STEP_IMPORT_FAILED assert result["errors"] == {"base": ERROR_CANNOT_CONNECT} # validate setup_entry was not called assert len(mock_setup_entry.mock_calls) == 0
async def test_config_entry_loads_unconnected_cloud( hass, config_entry, app, installed_app, device, smartthings_mock, subscription_factory, scene, ): """Test entry loads during startup when cloud isn't connected.""" config_entry.add_to_hass(hass) hass.data[DOMAIN][CONF_CLOUDHOOK_URL] = "https://test.cloud" hass.config.api.base_url = "http://0.0.0.0" smartthings_mock.app.return_value = app smartthings_mock.installed_app.return_value = installed_app smartthings_mock.devices.return_value = [device] smartthings_mock.scenes.return_value = [scene] mock_token = Mock() mock_token.access_token.return_value = str(uuid4()) mock_token.refresh_token.return_value = str(uuid4()) smartthings_mock.generate_tokens.return_value = mock_token subscriptions = [ subscription_factory(capability) for capability in device.capabilities ] smartthings_mock.subscriptions.return_value = subscriptions with patch.object(hass.config_entries, "async_forward_entry_setup") as forward_mock: assert await smartthings.async_setup_entry(hass, config_entry) await hass.async_block_till_done() assert forward_mock.call_count == len(SUPPORTED_PLATFORMS)
async def test_scenes_unauthorized_loads_platforms( hass, config_entry, app, installed_app, device, smartthings_mock, subscription_factory, ): """Test if scenes are unauthorized we continue to load platforms.""" config_entry.add_to_hass(hass) request_info = Mock(real_url="http://example.com") smartthings_mock.app.return_value = app smartthings_mock.installed_app.return_value = installed_app smartthings_mock.devices.return_value = [device] smartthings_mock.scenes.side_effect = ClientResponseError( request_info=request_info, history=None, status=403) mock_token = Mock() mock_token.access_token.return_value = str(uuid4()) mock_token.refresh_token.return_value = str(uuid4()) smartthings_mock.generate_tokens.return_value = mock_token subscriptions = [ subscription_factory(capability) for capability in device.capabilities ] smartthings_mock.subscriptions.return_value = subscriptions with patch.object(hass.config_entries, "async_forward_entry_setup") as forward_mock: assert await smartthings.async_setup_entry(hass, config_entry) # Assert platforms loaded await hass.async_block_till_done() assert forward_mock.call_count == len(SUPPORTED_PLATFORMS)
async def test_config_entry_loads_platforms( hass, config_entry, app, installed_app, device, smartthings_mock, subscription_factory, scene, ): """Test config entry loads properly and proxies to platforms.""" config_entry.add_to_hass(hass) smartthings_mock.app.return_value = app smartthings_mock.installed_app.return_value = installed_app smartthings_mock.devices.return_value = [device] smartthings_mock.scenes.return_value = [scene] mock_token = Mock() mock_token.access_token.return_value = str(uuid4()) mock_token.refresh_token.return_value = str(uuid4()) smartthings_mock.generate_tokens.return_value = mock_token subscriptions = [ subscription_factory(capability) for capability in device.capabilities ] smartthings_mock.subscriptions.return_value = subscriptions with patch.object(hass.config_entries, "async_forward_entry_setup") as forward_mock: assert await smartthings.async_setup_entry(hass, config_entry) # Assert platforms loaded await hass.async_block_till_done() assert forward_mock.call_count == len(SUPPORTED_PLATFORMS)
async def test_controller_unknown_error(hass): """Unknown errors are handled.""" with patch.object(unifi.controller, "get_controller", side_effect=Exception): await setup_unifi_integration(hass) assert hass.data[unifi.DOMAIN] == {}
async def test_config_passed_to_config_entry(hass): """Test that configured options for a host are loaded via config entry.""" entry = MockConfigEntry( domain=konnected.DOMAIN, data={ config_flow.CONF_ID: "aabbccddeeff", config_flow.CONF_HOST: "0.0.0.0" }, ) entry.add_to_hass(hass) with patch.object(konnected, "AlarmPanel", autospec=True) as mock_int: assert (await async_setup_component( hass, konnected.DOMAIN, { konnected.DOMAIN: { konnected.CONF_ACCESS_TOKEN: "abcdefgh", konnected.CONF_DEVICES: [{ konnected.CONF_ID: "aabbccddeeff" }], } }, ) is True) assert len(mock_int.mock_calls) == 3 p_hass, p_entry = mock_int.mock_calls[0][1] assert p_hass is hass assert p_entry is entry
async def test_controller_not_accessible(hass): """Retry to login gets scheduled when connection fails.""" with patch.object(unifi.controller, "get_controller", side_effect=unifi.errors.CannotConnect): await setup_unifi_integration(hass) assert hass.data[unifi.DOMAIN] == {}
async def test_empty_update(hass): """Test updating with no state from monoprice.""" monoprice = MockMonoprice() await _setup_monoprice(hass, monoprice) # Changing media player to new state await _call_media_player_service(hass, SERVICE_VOLUME_SET, { "entity_id": ZONE_1_ID, "volume_level": 0.0 }) await _call_media_player_service(hass, SERVICE_SELECT_SOURCE, { "entity_id": ZONE_1_ID, "source": "one" }) monoprice.set_source(11, 3) monoprice.set_volume(11, 38) with patch.object(MockMonoprice, "zone_status", return_value=None): await async_update_entity(hass, ZONE_1_ID) await hass.async_block_till_done() state = hass.states.get(ZONE_1_ID) assert state.attributes[ATTR_MEDIA_VOLUME_LEVEL] == 0.0 assert state.attributes[ATTR_INPUT_SOURCE] == "one"
async def test_002_on_event(self): cb = CoroutineMock() with patch.object(self.bus._mucs, 'joinMUC') as join_mock: self.bus._connected.set() await self.bus.subscribe('other', cb) join_mock.assert_called_once_with('*****@*****.**', 'login') msg = self.bus.client.Message() msg['type'] = 'groupchat' msg['from'] = JID('other@localhost') msg['body'] = '{"key": "value"}' await self.bus._on_event(msg) cb.assert_called_once_with({'key': 'value'})
def test_001c_request_error(self): error = { 'endpoint': 'http://localhost:8080/None/api/url', 'error': 'ClientOSError()', 'data': {'message': 'text'} } with patch('aiohttp.request', side_effect=ClientOSError): with patch.object(self.bus, 'publish') as publish: exc = self.loop.run_until_complete(self.bus.request( None, 'url', 'get', data={'message': 'text'} )) publish.assert_called_once_with(error) ok_(isinstance(exc, ClientOSError))
async def test_001_store_replay(self): await self.bus.publish({'something': 'something'}) await self.bus.publish({'another': 'event'}) # Backend received the events await self.bus._persistence._empty_last_events() eq_(len(self.backend.events), 2) eq_(self.backend.events[0]['status'], EventStatus.FAILED.value) # Check replay send the same event event_0_uid = self.backend.events[0]['id'] event_1_uid = self.backend.events[1]['id'] with patch.object(self.bus, 'publish') as pub: await self.bus.replay() pub.assert_has_calls([ call({'something': 'something'}, topic='test', previous_uid=event_0_uid), call({'another': 'event'}, topic='test', previous_uid=event_1_uid), ])
async def test_005_reconnect(self): self.bus.reconnect = True with patch.object(self.bus.client, '_connect_routine') as mock: await self.bus._on_disconnect(None) eq_(mock.call_count, 1)