def test_registering_view_while_running(hass, test_client): """Test that we can register a view while the server is running.""" yield from bootstrap.async_setup_component( hass, http.DOMAIN, { http.DOMAIN: { http.CONF_SERVER_PORT: get_test_instance_port(), } } ) yield from bootstrap.async_setup_component(hass, 'api') yield from hass.async_start() yield from hass.async_block_till_done() hass.http.register_view(TestView) client = yield from test_client(hass.http.app) resp = yield from client.get('/hello') assert resp.status == 200 text = yield from resp.text() assert text == 'hello'
def test_intent_speech_response(hass, mqtt_mock): """Test intent speech response via Snips.""" event = 'call_service' events = [] @callback def record_event(event): """Add recorded event to set.""" events.append(event) result = yield from async_setup_component(hass, "snips", { "snips": {}, }) assert result result = yield from async_setup_component(hass, "intent_script", { "intent_script": { "spokenIntent": { "speech": { "type": "plain", "text": "I am speaking to you" } } } }) assert result payload = """ { "input": "speak to me", "sessionId": "abcdef0123456789", "intent": { "intentName": "spokenIntent" }, "slots": [] } """ hass.bus.async_listen(event, record_event) async_fire_mqtt_message(hass, 'hermes/intent/spokenIntent', payload) yield from hass.async_block_till_done() assert len(events) == 1 assert events[0].data['domain'] == 'mqtt' assert events[0].data['service'] == 'publish' payload = json.loads(events[0].data['service_data']['payload']) topic = events[0].data['service_data']['topic'] assert payload['sessionId'] == 'abcdef0123456789' assert payload['text'] == 'I am speaking to you' assert topic == 'hermes/dialogueManager/endSession'
def test_deprecated_api_update(hass, hass_client): """Test the API.""" yield from async_setup_component(hass, "shopping_list", {}) yield from intent.async_handle( hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}} ) yield from intent.async_handle( hass, "test", "HassShoppingListAddItem", {"item": {"value": "wine"}} ) beer_id = hass.data["shopping_list"].items[0]["id"] wine_id = hass.data["shopping_list"].items[1]["id"] client = yield from hass_client() resp = yield from client.post( "/api/shopping_list/item/{}".format(beer_id), json={"name": "soda"} ) assert resp.status == 200 data = yield from resp.json() assert data == {"id": beer_id, "name": "soda", "complete": False} resp = yield from client.post( "/api/shopping_list/item/{}".format(wine_id), json={"complete": True} ) assert resp.status == 200 data = yield from resp.json() assert data == {"id": wine_id, "name": "wine", "complete": True} beer, wine = hass.data["shopping_list"].items assert beer == {"id": beer_id, "name": "soda", "complete": False} assert wine == {"id": wine_id, "name": "wine", "complete": True}
def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave yield from async_setup_component(hass, 'zwave', {'zwave': {}}) yield from hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep @asyncio.coroutine def sleep(duration, loop): if duration > 0: sleeps.append(duration) yield from asyncio_sleep(0, loop=loop) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) yield from hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS
def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): yield from async_setup_component(hass, 'zwave', {'zwave': { 'new_entity_ids': True, }}) assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) yield from hass.async_block_till_done() assert len(events) == 1
def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): yield from async_setup_component(hass, 'zwave', {'zwave': { 'new_entity_ids': True, }}) assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) yield from hass.async_block_till_done() assert hass.states.get('binary_sensor.mock_node_mock_value').state is 'off'
def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): yield from async_setup_component( hass, 'zwave', { 'zwave': { 'new_entity_ids': True, 'device_config': { 'zwave.mock_node': { 'ignored': True, } } } }) assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) yield from hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None
def test_hydroquebec_sensor(loop, hass): """Test the Hydroquebec number sensor.""" sys.modules['pyhydroquebec'] = MagicMock() sys.modules['pyhydroquebec.client'] = MagicMock() sys.modules['pyhydroquebec.client.PyHydroQuebecError'] = \ PyHydroQuebecErrorMock import pyhydroquebec.client pyhydroquebec.HydroQuebecClient = HydroQuebecClientMock pyhydroquebec.client.PyHydroQuebecError = PyHydroQuebecErrorMock config = { 'sensor': { 'platform': 'hydroquebec', 'name': 'hydro', 'contract': CONTRACT, 'username': '******', 'password': '******', 'monitored_variables': [ 'balance', ], } } with assert_setup_component(1): yield from async_setup_component(hass, 'sensor', config) state = hass.states.get('sensor.hydro_balance') assert state.state == "160.12" assert state.attributes.get('unit_of_measurement') == "CAD"
def test_api_update(hass, test_client): """Test the API.""" yield from async_setup_component(hass, 'shopping_list', {}) yield from intent.async_handle(hass, 'test', 'HassShoppingListAddItem', {'item': { 'value': 'beer' }}) yield from intent.async_handle(hass, 'test', 'HassShoppingListAddItem', {'item': { 'value': 'wine' }}) beer_id = hass.data['shopping_list'].items[0]['id'] wine_id = hass.data['shopping_list'].items[1]['id'] client = yield from test_client(hass.http.app) resp = yield from client.post('/api/shopping_list/item/{}'.format(beer_id), json={'name': 'soda'}) assert resp.status == 200 data = yield from resp.json() assert data == {'id': beer_id, 'name': 'soda', 'complete': False} resp = yield from client.post('/api/shopping_list/item/{}'.format(wine_id), json={'complete': True}) assert resp.status == 200 data = yield from resp.json() assert data == {'id': wine_id, 'name': 'wine', 'complete': True} beer, wine = hass.data['shopping_list'].items assert beer == {'id': beer_id, 'name': 'soda', 'complete': False} assert wine == {'id': wine_id, 'name': 'wine', 'complete': True}
def test_api_clear_completed(hass, test_client): """Test the API.""" yield from async_setup_component(hass, 'shopping_list', {}) yield from intent.async_handle(hass, 'test', 'HassShoppingListAddItem', {'item': { 'value': 'beer' }}) yield from intent.async_handle(hass, 'test', 'HassShoppingListAddItem', {'item': { 'value': 'wine' }}) beer_id = hass.data['shopping_list'].items[0]['id'] wine_id = hass.data['shopping_list'].items[1]['id'] client = yield from test_client(hass.http.app) # Mark beer as completed resp = yield from client.post('/api/shopping_list/item/{}'.format(beer_id), json={'complete': True}) assert resp.status == 200 resp = yield from client.post('/api/shopping_list/clear_completed') assert resp.status == 200 items = hass.data['shopping_list'].items assert len(items) == 1 assert items[0] == {'id': wine_id, 'name': 'wine', 'complete': False}
def test_get_entity(hass, hass_client): """Test getting entity.""" with patch.object(config, "SECTIONS", ["customize"]): yield from async_setup_component(hass, "config", {}) client = yield from hass_client() def mock_read(path): """Mock reading data.""" return { "hello.beer": { "free": "beer" }, "other.entity": { "do": "something" } } hass.data[DATA_CUSTOMIZE] = {"hello.beer": {"cold": "beer"}} with patch("homeassistant.components.config._read", mock_read): resp = yield from client.get("/api/config/customize/config/hello.beer") assert resp.status == 200 result = yield from resp.json() assert result == {"local": {"free": "beer"}, "global": {"cold": "beer"}}
def test_api_streams(hass): """Test API streams.""" log = logging.getLogger('homeassistant.components.api') with assert_setup_component(1): yield from async_setup_component( hass, 'sensor', {'sensor': { 'platform': 'api_streams', }}) state = hass.states.get('sensor.connected_clients') assert state.state == '0' log.debug('STREAM 1 ATTACHED') yield from hass.async_block_till_done() state = hass.states.get('sensor.connected_clients') assert state.state == '1' log.debug('STREAM 1 ATTACHED') yield from hass.async_block_till_done() state = hass.states.get('sensor.connected_clients') assert state.state == '2' log.debug('STREAM 1 RESPONSE CLOSED') yield from hass.async_block_till_done() state = hass.states.get('sensor.connected_clients') assert state.state == '1'
def test_deprecated_api_clear_completed(hass, hass_client): """Test the API.""" yield from async_setup_component(hass, "shopping_list", {}) yield from intent.async_handle( hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}} ) yield from intent.async_handle( hass, "test", "HassShoppingListAddItem", {"item": {"value": "wine"}} ) beer_id = hass.data["shopping_list"].items[0]["id"] wine_id = hass.data["shopping_list"].items[1]["id"] client = yield from hass_client() # Mark beer as completed resp = yield from client.post( "/api/shopping_list/item/{}".format(beer_id), json={"complete": True} ) assert resp.status == 200 resp = yield from client.post("/api/shopping_list/clear_completed") assert resp.status == 200 items = hass.data["shopping_list"].items assert len(items) == 1 assert items[0] == {"id": wine_id, "name": "wine", "complete": False}
def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave yield from async_setup_component(hass, 'zwave', {'zwave': {}}) yield from hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep @asyncio.coroutine def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) yield from asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) yield from hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS
def test_intent_script(hass): """Test intent scripts work.""" calls = async_mock_service(hass, 'test', 'service') yield from async_setup_component(hass, 'intent_script', { 'intent_script': { 'HelloWorld': { 'action': { 'service': 'test.service', 'data_template': { 'hello': '{{ name }}' } }, 'card': { 'title': 'Hello {{ name }}', 'content': 'Content for {{ name }}', }, 'speech': { 'text': 'Good morning {{ name }}' } } } }) response = yield from intent.async_handle( hass, 'test', 'HelloWorld', {'name': {'value': 'Paulus'}} ) assert len(calls) == 1 assert calls[0].data['hello'] == 'Paulus' assert response.speech['plain']['speech'] == 'Good morning Paulus' assert response.card['simple']['title'] == 'Hello Paulus' assert response.card['simple']['content'] == 'Content for Paulus'
def test_reconnect(hass, monkeypatch, mock_connection_factory): """If transport disconnects, the connection should be retried.""" (connection_factory, transport, protocol) = mock_connection_factory config = { 'platform': 'dsmr', 'reconnect_interval': 0, } # mock waiting coroutine while connection lasts closed = asyncio.Event(loop=hass.loop) @asyncio.coroutine def wait_closed(): yield from closed.wait() protocol.wait_closed = wait_closed yield from async_setup_component(hass, 'sensor', {'sensor': config}) assert connection_factory.call_count == 1 # indicate disconnect, release wait lock and allow reconnect to happen closed.set() # wait for lock set to resolve yield from hass.async_block_till_done() # wait for sleep to resolve yield from hass.async_block_till_done() assert connection_factory.call_count >= 2, \ 'connecting not retried'
def test_snips_call_action(hass, mqtt_mock): """Test calling action via Snips.""" calls = async_mock_service(hass, 'test', 'service') result = yield from async_setup_component(hass, "snips", { "snips": { "intents": { "Lights": { "action": { "service": "test.service", "data_template": { "color": "{{ light_color }}" } } } } } }) assert result async_fire_mqtt_message(hass, 'hermes/nlu/intentParsed', EXAMPLE_MSG) yield from hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.data.get('color') == 'blue'
def test_get_device_config(hass, test_client): """Test getting device config.""" with patch.object(config, 'SECTIONS', ['group']): yield from async_setup_component(hass, 'config', {}) client = yield from test_client(hass.http.app) def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/group/config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'}
def test_update_sensor_device(hass, aioclient_mock, monkeypatch, sia_code, state): """ Test that sensors change state on incoming websocket data. Note that we don't test for the ZD (disconnected) and ZX (problem/short) codes since the binary sensor component is hardcoded to only let on/off states through. """ monkeypatch.setattr("homeassistant.components.spc.SpcWebGateway." "start_listener", lambda x, *args: None) config = { 'spc': { 'api_url': 'http://localhost/', 'ws_url': 'ws://localhost/' } } yield from async_setup_component(hass, 'spc', config) yield from hass.async_block_till_done() assert hass.states.get('binary_sensor.hallway_pir').state == STATE_OFF msg = {"sia_code": sia_code, "sia_address": "3", "description": "Hallway PIR"} yield from spc._async_process_message(msg, hass.data[spc.DATA_REGISTRY]) yield from hass.async_block_till_done() assert hass.states.get('binary_sensor.hallway_pir').state == state
def test_get_device_config(hass, hass_client): """Test getting device config.""" with patch.object(config, "SECTIONS", ["group"]): yield from async_setup_component(hass, "config", {}) client = yield from hass_client() def mock_read(path): """Mock reading data.""" return { "hello.beer": { "free": "beer" }, "other.entity": { "do": "something" } } with patch("homeassistant.components.config._read", mock_read): resp = yield from client.get("/api/config/group/config/hello.beer") assert resp.status == 200 result = yield from resp.json() assert result == {"free": "beer"}
def test_websocket_api(hass): """Test API streams.""" log = logging.getLogger('homeassistant.components.websocket_api') with assert_setup_component(1): yield from async_setup_component( hass, 'sensor', {'sensor': { 'platform': 'api_streams', }}) state = hass.states.get('sensor.connected_clients') assert state.state == '0' log.debug('WS %s: %s', id(log), 'Connected') yield from hass.async_block_till_done() state = hass.states.get('sensor.connected_clients') assert state.state == '1' log.debug('WS %s: %s', id(log), 'Connected') yield from hass.async_block_till_done() state = hass.states.get('sensor.connected_clients') assert state.state == '2' log.debug('WS %s: %s', id(log), 'Closed connection') yield from hass.async_block_till_done() state = hass.states.get('sensor.connected_clients') assert state.state == '1'
def test_scene_activated(hass, mock_openzwave): """Test scene activated event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_SCENE_EVENT: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): yield from async_setup_component(hass, 'zwave', {'zwave': {}}) assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_SCENE_ACTIVATED, listener) node = MockNode(node_id=11) scene_id = 123 hass.async_add_job(mock_receivers[0], node, scene_id) yield from hass.async_block_till_done() assert len(events) == 1 assert events[0].data[ATTR_ENTITY_ID] == "mock_node_11" assert events[0].data[const.ATTR_OBJECT_ID] == "mock_node_11" assert events[0].data[const.ATTR_SCENE_ID] == scene_id
def test_update_alarm_device(hass, aioclient_mock, monkeypatch, sia_code, state): """Test that alarm panel state changes on incoming websocket data.""" monkeypatch.setattr("homeassistant.components.spc.SpcWebGateway." "start_listener", lambda x, *args: None) config = { 'spc': { 'api_url': 'http://localhost/', 'ws_url': 'ws://localhost/' } } yield from async_setup_component(hass, 'spc', config) yield from hass.async_block_till_done() entity_id = 'alarm_control_panel.house' assert hass.states.get(entity_id).state == STATE_ALARM_DISARMED msg = {"sia_code": sia_code, "sia_address": "1", "description": "House¦Sam¦1"} yield from spc._async_process_message(msg, hass.data[spc.DATA_REGISTRY]) yield from hass.async_block_till_done() state_obj = hass.states.get(entity_id) assert state_obj.state == state assert state_obj.attributes['changed_by'] == 'Sam'
def test_fido_sensor(loop, hass): """Test the Fido number sensor.""" sys.modules['pyfido'] = MagicMock() sys.modules['pyfido.client'] = MagicMock() sys.modules['pyfido.client.PyFidoError'] = \ PyFidoErrorMock import pyfido.client pyfido.FidoClient = FidoClientMock pyfido.client.PyFidoError = PyFidoErrorMock config = { 'sensor': { 'platform': 'fido', 'name': 'fido', 'username': '******', 'password': '******', 'monitored_variables': [ 'balance', 'data_remaining', ], } } with assert_setup_component(1): yield from async_setup_component(hass, 'sensor', config) state = hass.states.get('sensor.fido_1112223344_balance') assert state.state == "160.12" assert state.attributes.get('number') == "1112223344" state = hass.states.get('sensor.fido_1112223344_data_remaining') assert state.state == "100.33"
def test_api_streams(hass): """Test API streams.""" log = logging.getLogger('homeassistant.components.api') with assert_setup_component(1): yield from async_setup_component(hass, 'sensor', { 'sensor': { 'platform': 'api_streams', } }) state = hass.states.get('sensor.connected_clients') assert state.state == '0' log.debug('STREAM 1 ATTACHED') yield from hass.async_block_till_done() state = hass.states.get('sensor.connected_clients') assert state.state == '1' log.debug('STREAM 1 ATTACHED') yield from hass.async_block_till_done() state = hass.states.get('sensor.connected_clients') assert state.state == '2' log.debug('STREAM 1 RESPONSE CLOSED') yield from hass.async_block_till_done() state = hass.states.get('sensor.connected_clients') assert state.state == '1'
def test_get_entity(hass, test_client): """Test getting entity.""" with patch.object(config, 'SECTIONS', ['customize']): yield from async_setup_component(hass, 'config', {}) client = yield from test_client(hass.http.app) def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } hass.data[DATA_CUSTOMIZE] = {'hello.beer': {'cold': 'beer'}} with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/customize/config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'local': {'free': 'beer'}, 'global': {'cold': 'beer'}}
def test_api_clear_completed(hass, test_client): """Test the API.""" yield from async_setup_component(hass, 'shopping_list', {}) yield from intent.async_handle( hass, 'test', 'HassShoppingListAddItem', {'item': {'value': 'beer'}} ) yield from intent.async_handle( hass, 'test', 'HassShoppingListAddItem', {'item': {'value': 'wine'}} ) beer_id = hass.data['shopping_list'].items[0]['id'] wine_id = hass.data['shopping_list'].items[1]['id'] client = yield from test_client(hass.http.app) # Mark beer as completed resp = yield from client.post( '/api/shopping_list/item/{}'.format(beer_id), json={ 'complete': True }) assert resp.status == 200 resp = yield from client.post('/api/shopping_list/clear_completed') assert resp.status == 200 items = hass.data['shopping_list'].items assert len(items) == 1 assert items[0] == { 'id': wine_id, 'name': 'wine', 'complete': False }
def test_get_device_config(hass, test_client): """Test getting device config.""" app = mock_http_component_app(hass) with patch.object(config, 'SECTIONS', ['group']): yield from async_setup_component(hass, 'config', {}) hass.http.views[VIEW_NAME].register(app.router) client = yield from test_client(app) def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/group/config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'}
def test_websocket_api(hass): """Test API streams.""" log = logging.getLogger('homeassistant.components.websocket_api') with assert_setup_component(1): yield from async_setup_component(hass, 'sensor', { 'sensor': { 'platform': 'api_streams', } }) state = hass.states.get('sensor.connected_clients') assert state.state == '0' log.debug('WS %s: %s', id(log), 'Connected') yield from hass.async_block_till_done() state = hass.states.get('sensor.connected_clients') assert state.state == '1' log.debug('WS %s: %s', id(log), 'Connected') yield from hass.async_block_till_done() state = hass.states.get('sensor.connected_clients') assert state.state == '2' log.debug('WS %s: %s', id(log), 'Closed connection') yield from hass.async_block_till_done() state = hass.states.get('sensor.connected_clients') assert state.state == '1'
def test_validate_config_ok(hass, hass_client): """Test checking config.""" with patch.object(config, 'SECTIONS', ['core']): yield from async_setup_component(hass, 'config', {}) yield from asyncio.sleep(0.1, loop=hass.loop) client = yield from hass_client() with patch( 'homeassistant.components.config.core.async_check_ha_config_file', return_value=mock_coro()): resp = yield from client.post('/api/config/core/check_config') assert resp.status == 200 result = yield from resp.json() assert result['result'] == 'valid' assert result['errors'] is None with patch( 'homeassistant.components.config.core.async_check_ha_config_file', return_value=mock_coro('beer')): resp = yield from client.post('/api/config/core/check_config') assert resp.status == 200 result = yield from resp.json() assert result['result'] == 'invalid' assert result['errors'] == 'beer'
def test_restore_state(hass): """Test state gets restored.""" hass.config.components.add('recorder') hass.state = CoreState.starting hass.data[DATA_RESTORE_CACHE] = { 'light.bed_light': State('light.bed_light', 'on', { 'brightness': 'value-brightness', 'color_temp': 'value-color_temp', 'rgb_color': 'value-rgb_color', 'xy_color': 'value-xy_color', 'white_value': 'value-white_value', 'effect': 'value-effect', }), } yield from async_setup_component(hass, 'light', { 'light': { 'platform': 'demo', }}) state = hass.states.get('light.bed_light') assert state is not None assert state.entity_id == 'light.bed_light' assert state.state == 'on' assert state.attributes.get('brightness') == 'value-brightness' assert state.attributes.get('color_temp') == 'value-color_temp' assert state.attributes.get('rgb_color') == 'value-rgb_color' assert state.attributes.get('xy_color') == 'value-xy_color' assert state.attributes.get('white_value') == 'value-white_value' assert state.attributes.get('effect') == 'value-effect'
def test_validate_config_ok(hass, test_client): """Test checking config.""" app = mock_http_component_app(hass) with patch.object(config, 'SECTIONS', ['core']): yield from async_setup_component(hass, 'config', {}) hass.http.views[CheckConfigView.name].register(app.router) client = yield from test_client(app) with patch( 'homeassistant.components.config.core.async_check_ha_config_file', return_value=mock_coro()): resp = yield from client.post('/api/config/core/check_config') assert resp.status == 200 result = yield from resp.json() assert result['result'] == 'valid' assert result['errors'] is None with patch( 'homeassistant.components.config.core.async_check_ha_config_file', return_value=mock_coro('beer')): resp = yield from client.post('/api/config/core/check_config') assert resp.status == 200 result = yield from resp.json() assert result['result'] == 'invalid' assert result['errors'] == 'beer'
def test_node_event_activated(hass, mock_openzwave): """Test Node event activated event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_EVENT: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): yield from async_setup_component(hass, 'zwave', {'zwave': {}}) assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NODE_EVENT, listener) node = MockNode(node_id=11) value = 234 hass.async_add_job(mock_receivers[0], node, value) yield from hass.async_block_till_done() assert len(events) == 1 assert events[0].data[const.ATTR_OBJECT_ID] == "mock_node_11" assert events[0].data[const.ATTR_BASIC_LEVEL] == value
def async_discover(hass, service, discovered=None, component=None, hass_config=None): """Fire discovery event. Can ensure a component is loaded.""" if component in DEPENDENCY_BLACKLIST: raise HomeAssistantError( 'Cannot discover the {} component.'.format(component)) if component is not None and component not in hass.config.components: did_lock = False setup_lock = hass.data.get('setup_lock') if setup_lock and setup_lock.locked(): did_lock = True yield from setup_lock.acquire() try: # Could have been loaded while waiting for lock. if component not in hass.config.components: yield from bootstrap.async_setup_component(hass, component, hass_config) finally: if did_lock: setup_lock.release() data = { ATTR_SERVICE: service } if discovered is not None: data[ATTR_DISCOVERED] = discovered hass.bus.async_fire(EVENT_PLATFORM_DISCOVERED, data)
def test_get_device_config(hass, test_client): """Test getting device config.""" with patch.object(config, 'SECTIONS', ['zwave']): yield from async_setup_component(hass, 'config', {}) client = yield from test_client(hass.http.app) def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'}
def cloud_client(hass, test_client): """Fixture that can fetch from the cloud client.""" hass.loop.run_until_complete(async_setup_component(hass, 'cloud', { 'cloud': { 'mode': 'development' } })) return hass.loop.run_until_complete(test_client(hass.http.app))
def cloud_client(hass, test_client): """Fixture that can fetch from the cloud client.""" hass.loop.run_until_complete( async_setup_component(hass, 'cloud', {'cloud': { 'mode': 'development' }})) return hass.loop.run_until_complete(test_client(hass.http.app))
def test_setup_check_env_prevents_load(hass, loop): """Test it does not set up hassbian if environment var not present.""" with patch.dict(os.environ, clear=True), \ patch.object(config, 'SECTIONS', ['hassbian']), \ patch('homeassistant.components.http.' 'HomeAssistantWSGI.register_view') as reg_view: loop.run_until_complete(async_setup_component(hass, 'config', {})) assert 'config' in hass.config.components assert reg_view.called is False
def test_setup_check_env_prevents_load(hass, loop): """Test it does not set up hassbian if environment var not present.""" mock_http_component(hass) with patch.dict(os.environ, clear=True), \ patch.object(config, 'SECTIONS', ['hassbian']): loop.run_until_complete(async_setup_component(hass, 'config', {})) assert 'config' in hass.config.components assert HassbianSuitesView.name not in hass.http.views assert HassbianSuiteInstallView.name not in hass.http.views
def test_setup_check_env_prevents_load(hass, loop): """Test it does not set up hassbian if environment var not present.""" with patch.dict(os.environ, clear=True), \ patch.object(config, 'SECTIONS', ['hassbian']), \ patch('homeassistant.components.http.' 'HomeAssistantHTTP.register_view') as reg_view: loop.run_until_complete(async_setup_component(hass, 'config', {})) assert 'config' in hass.config.components assert reg_view.called is False
def test_setup_check_env_works(hass, loop): """Test it sets up hassbian if environment var present.""" mock_http_component(hass) with patch.dict(os.environ, {'FORCE_HASSBIAN': '1'}), \ patch.object(config, 'SECTIONS', ['hassbian']): loop.run_until_complete(async_setup_component(hass, 'config', {})) assert 'config' in hass.config.components assert HassbianSuitesView.name in hass.http.views assert HassbianSuiteInstallView.name in hass.http.views
def test_add_item(hass): """Test adding an item intent.""" yield from async_setup_component(hass, "shopping_list", {}) response = yield from intent.async_handle( hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}} ) assert response.speech["plain"]["speech"] == "I've added beer to your shopping list"
def test_deprecated_api_create_fail(hass, hass_client): """Test the API.""" yield from async_setup_component(hass, "shopping_list", {}) client = yield from hass_client() resp = yield from client.post("/api/shopping_list/item", json={"name": 1234}) assert resp.status == 400 assert len(hass.data["shopping_list"].items) == 0
def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = {'light.kitchen': {'some_ignored': 'true'}} result = yield from async_setup_component( hass, 'zwave', {'zwave': { 'device_config': device_config }}) assert not result
def test_api_base_url(loop): """Test setting api url.""" hass = MagicMock() hass.loop = loop assert loop.run_until_complete( bootstrap.async_setup_component(hass, 'http', { 'http': { 'base_url': 'example.com' } }) ) assert hass.config.api.base_url == 'http://example.com' assert loop.run_until_complete( bootstrap.async_setup_component(hass, 'http', { 'http': { 'server_host': '1.1.1.1' } }) ) assert hass.config.api.base_url == 'http://1.1.1.1:8123' assert loop.run_until_complete( bootstrap.async_setup_component(hass, 'http', { 'http': { 'server_host': '1.1.1.1' } }) ) assert hass.config.api.base_url == 'http://1.1.1.1:8123' assert loop.run_until_complete( bootstrap.async_setup_component(hass, 'http', { 'http': { } }) ) assert hass.config.api.base_url == 'http://127.0.0.1:8123'
def test_add_item(hass): """Test adding an item intent.""" yield from async_setup_component(hass, 'shopping_list', {}) response = yield from intent.async_handle( hass, 'test', 'HassShoppingListAddItem', {'item': {'value': 'beer'}} ) assert response.speech['plain']['speech'] == \ "I've added beer to your shopping list"
def test_api_create_fail(hass, aiohttp_client): """Test the API.""" yield from async_setup_component(hass, 'shopping_list', {}) client = yield from aiohttp_client(hass.http.app) resp = yield from client.post('/api/shopping_list/item', json={'name': 1234}) assert resp.status == 400 assert len(hass.data['shopping_list'].items) == 0
def mock_http_client(hass, test_client): """Start the Hass HTTP component.""" config = { mailbox.DOMAIN: { 'platform': 'demo' } } hass.loop.run_until_complete( async_setup_component(hass, mailbox.DOMAIN, config)) return hass.loop.run_until_complete(test_client(hass.http.app))
def mock_mqtt_client(hass, config=None): """Mock the MQTT paho client.""" if config is None: config = {mqtt.CONF_BROKER: 'mock-broker'} with mock.patch('paho.mqtt.client.Client') as mock_client: mock_client().connect = lambda *args: 0 result = yield from async_setup_component(hass, mqtt.DOMAIN, {mqtt.DOMAIN: config}) assert result return mock_client()
def test_setup_check_env_works(hass, loop): """Test it sets up hassbian if environment var present.""" with patch.dict(os.environ, {'FORCE_HASSBIAN': '1'}), \ patch.object(config, 'SECTIONS', ['hassbian']), \ patch('homeassistant.components.http.' 'HomeAssistantWSGI.register_view') as reg_view: loop.run_until_complete(async_setup_component(hass, 'config', {})) assert 'config' in hass.config.components assert len(reg_view.mock_calls) == 2 assert isinstance(reg_view.mock_calls[0][1][0], HassbianSuitesView) assert isinstance(reg_view.mock_calls[1][1][0], HassbianSuiteInstallView)
def test_update_device_config_invalid_json(hass, test_client): """Test updating device config.""" with patch.object(config, 'SECTIONS', ['group']): yield from async_setup_component(hass, 'config', {}) client = yield from test_client(hass.http.app) resp = yield from client.post('/api/config/group/config/hello_beer', data='not json') assert resp.status == 400
def test_update_entity_invalid_json(hass, hass_client): """Test updating entity.""" with patch.object(config, 'SECTIONS', ['customize']): yield from async_setup_component(hass, 'config', {}) client = yield from hass_client() resp = yield from client.post('/api/config/customize/config/hello.beer', data='not json') assert resp.status == 400
def test_tcp(hass, mock_connection_factory): """If proper config provided TCP connection should be made.""" (connection_factory, transport, protocol) = mock_connection_factory config = {"platform": "dsmr", "host": "localhost", "port": 1234} with assert_setup_component(1): yield from async_setup_component(hass, "sensor", {"sensor": config}) assert connection_factory.call_args_list[0][0][0] == "localhost" assert connection_factory.call_args_list[0][0][1] == "1234"
def test_update_device_config_invalid_data(hass, test_client): """Test updating device config.""" with patch.object(config, 'SECTIONS', ['zwave']): yield from async_setup_component(hass, 'config', {}) client = yield from test_client(hass.http.app) resp = yield from client.post('/api/config/zwave/device_config/hello.beer', data=json.dumps({'invalid_option': 2})) assert resp.status == 400