async def test_config_flow_registers_webhook(hass, aiohttp_client): """Test setting up Twilio and sending webhook.""" with MockDependency("twilio", "rest"), MockDependency("twilio", "twiml"): with patch("homeassistant.util.get_local_ip", return_value="example.com"): result = await hass.config_entries.flow.async_init( "twilio", context={"source": "user"}) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM, result result = await hass.config_entries.flow.async_configure( result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY webhook_id = result["result"].data["webhook_id"] twilio_events = [] @callback def handle_event(event): """Handle Twilio event.""" twilio_events.append(event) hass.bus.async_listen(twilio.RECEIVED_DATA, handle_event) client = await aiohttp_client(hass.http.app) await client.post("/api/webhook/{}".format(webhook_id), data={"hello": "twilio"}) assert len(twilio_events) == 1 assert twilio_events[0].data["webhook_id"] == webhook_id assert twilio_events[0].data["hello"] == "twilio"
async def test_config_flow_registers_webhook(hass, aiohttp_client): """Test setting up Twilio and sending webhook.""" with MockDependency('twilio', 'rest'), MockDependency('twilio', 'twiml'): with patch('homeassistant.util.get_local_ip', return_value='example.com'): result = await hass.config_entries.flow.async_init( 'twilio', context={'source': 'user'}) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM, result result = await hass.config_entries.flow.async_configure( result['flow_id'], {}) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY webhook_id = result['result'].data['webhook_id'] twilio_events = [] @callback def handle_event(event): """Handle Twilio event.""" twilio_events.append(event) hass.bus.async_listen(twilio.RECEIVED_DATA, handle_event) client = await aiohttp_client(hass.http.app) await client.post('/api/webhook/{}'.format(webhook_id), data={'hello': 'twilio'}) assert len(twilio_events) == 1 assert twilio_events[0].data['webhook_id'] == webhook_id assert twilio_events[0].data['hello'] == 'twilio'
async def test_send_magic_packet(opp): """Test of send magic packet service call.""" with MockDependency("wakeonlan") as mocked_wakeonlan: mac = "aa:bb:cc:dd:ee:ff" bc_ip = "192.168.255.255" wake_on_lan.wakeonlan = mocked_wakeonlan await async_setup_component(opp, DOMAIN, {}) await opp.services.async_call( DOMAIN, SERVICE_SEND_MAGIC_PACKET, {"mac": mac, "broadcast_address": bc_ip}, blocking=True, ) assert len(mocked_wakeonlan.mock_calls) == 1 assert mocked_wakeonlan.mock_calls[-1][1][0] == mac assert mocked_wakeonlan.mock_calls[-1][2]["ip_address"] == bc_ip with pytest.raises(vol.Invalid): await opp.services.async_call( DOMAIN, SERVICE_SEND_MAGIC_PACKET, {"broadcast_address": bc_ip}, blocking=True, ) assert len(mocked_wakeonlan.mock_calls) == 1 await opp.services.async_call( DOMAIN, SERVICE_SEND_MAGIC_PACKET, {"mac": mac}, blocking=True ) assert len(mocked_wakeonlan.mock_calls) == 2 assert mocked_wakeonlan.mock_calls[-1][1][0] == mac assert not mocked_wakeonlan.mock_calls[-1][2]
def platforms(hass, dtv_side_effect, mock_now): """Fixture for setting up test platforms.""" config = { "media_player": [ { "platform": "directv", "name": "Main DVR", "host": IP_ADDRESS, "port": DEFAULT_PORT, "device": DEFAULT_DEVICE, }, { "platform": "directv", "name": "Client DVR", "host": IP_ADDRESS, "port": DEFAULT_PORT, "device": "1", }, ] } with MockDependency("DirectPy"), patch( "DirectPy.DIRECTV", side_effect=dtv_side_effect ), patch("homeassistant.util.dt.utcnow", return_value=mock_now): hass.loop.run_until_complete(async_setup_component(hass, DOMAIN, config)) hass.loop.run_until_complete(hass.async_block_till_done()) yield
async def test_setup_platform_discover_client(hass): """Test setting up the platform from discovery.""" LOCATIONS.append({'locationName': 'Client 1', 'clientAddr': '1'}) LOCATIONS.append({'locationName': 'Client 2', 'clientAddr': '2'}) with MockDependency('DirectPy'), \ patch('DirectPy.DIRECTV', new=MockDirectvClass): await async_setup_component(hass, mp.DOMAIN, WORKING_CONFIG) await hass.async_block_till_done() hass.async_create_task( async_load_platform(hass, mp.DOMAIN, 'directv', DISCOVERY_INFO, {'media_player': {}})) await hass.async_block_till_done() del LOCATIONS[-1] del LOCATIONS[-1] state = hass.states.get(MAIN_ENTITY_ID) assert state state = hass.states.get('media_player.client_1') assert state state = hass.states.get('media_player.client_2') assert state assert len(hass.states.async_entity_ids('media_player')) == 3
async def test_islamic_prayer_times_multiple_sensors(hass): """Test Islamic prayer times sensor with multiple sensors setup.""" multiple_sensors = [ 'fajr', 'sunrise', 'dhuhr', 'asr', 'maghrib', 'isha', 'midnight' ] with MockDependency('prayer_times_calculator') as mock_pt_calc: mock_pt_calc.PrayerTimesCalculator.return_value.fetch_prayer_times \ .return_value = PRAYER_TIMES config = { 'sensor': { 'platform': 'islamic_prayer_times', 'sensors': multiple_sensors } } assert await async_setup_component(hass, 'sensor', config) is True for sensor in multiple_sensors: entity_id = ENTITY_ID_FORMAT.format(sensor) entity_id_name = sensor.capitalize() pt_dt = get_prayer_time_as_dt(PRAYER_TIMES[entity_id_name]) state = hass.states.get(entity_id) assert state.state == pt_dt.isoformat() assert state.name == entity_id_name
async def test_islamic_prayer_times_with_calculation_method(hass): """Test Islamic prayer times configuration with calculation method.""" sensors = ['fajr', 'maghrib'] with MockDependency('prayer_times_calculator') as mock_pt_calc: mock_pt_calc.PrayerTimesCalculator.return_value.fetch_prayer_times \ .return_value = PRAYER_TIMES config = { 'sensor': { 'platform': 'islamic_prayer_times', 'calculation_method': 'mwl', 'sensors': sensors } } assert await async_setup_component(hass, 'sensor', config) is True for sensor in sensors: entity_id = ENTITY_ID_FORMAT.format(sensor) entity_id_name = sensor.capitalize() pt_dt = get_prayer_time_as_dt(PRAYER_TIMES[entity_id_name]) state = hass.states.get(entity_id) assert state.state == pt_dt.isoformat() assert state.name == entity_id_name
async def test_islamic_prayer_times_with_calculation_method(hass): """Test Islamic prayer times configuration with calculation method.""" sensors = ["fajr", "maghrib"] with MockDependency("prayer_times_calculator") as mock_pt_calc: mock_pt_calc.PrayerTimesCalculator.return_value.fetch_prayer_times.return_value = ( PRAYER_TIMES) config = { "sensor": { "platform": "islamic_prayer_times", "calculation_method": "mwl", "sensors": sensors, } } assert await async_setup_component(hass, "sensor", config) is True for sensor in sensors: entity_id = ENTITY_ID_FORMAT.format(sensor) entity_id_name = sensor.capitalize() pt_dt = get_prayer_time_as_dt(PRAYER_TIMES[entity_id_name]) state = hass.states.get(entity_id) assert state.state == pt_dt.isoformat() assert state.name == entity_id_name
def zeroconf_mock(): """Mock zeroconf.""" with MockDependency("zeroconf") as mocked_zeroconf: mocked_zeroconf.Zeroconf.return_value.register_service.return_value = mock_coro( True ) yield
async def test_islamic_prayer_times_multiple_sensors(hass): """Test Islamic prayer times sensor with multiple sensors setup.""" multiple_sensors = [ "fajr", "sunrise", "dhuhr", "asr", "maghrib", "isha", "midnight", ] with MockDependency("prayer_times_calculator") as mock_pt_calc: mock_pt_calc.PrayerTimesCalculator.return_value.fetch_prayer_times.return_value = ( PRAYER_TIMES) config = { "sensor": { "platform": "islamic_prayer_times", "sensors": multiple_sensors } } assert await async_setup_component(hass, "sensor", config) is True for sensor in multiple_sensors: entity_id = ENTITY_ID_FORMAT.format(sensor) entity_id_name = sensor.capitalize() pt_dt = get_prayer_time_as_dt(PRAYER_TIMES[entity_id_name]) state = hass.states.get(entity_id) assert state.state == pt_dt.isoformat() assert state.name == entity_id_name
def platforms(hass, dtv_side_effect, mock_now): """Fixture for setting up test platforms.""" config = { 'media_player': [{ 'platform': 'directv', 'name': 'Main DVR', 'host': IP_ADDRESS, 'port': DEFAULT_PORT, 'device': DEFAULT_DEVICE }, { 'platform': 'directv', 'name': 'Client DVR', 'host': IP_ADDRESS, 'port': DEFAULT_PORT, 'device': '1' }] } with MockDependency('DirectPy'), \ patch('DirectPy.DIRECTV', side_effect=dtv_side_effect), \ patch('homeassistant.util.dt.utcnow', return_value=mock_now): hass.loop.run_until_complete( async_setup_component(hass, mp.DOMAIN, config)) hass.loop.run_until_complete(hass.async_block_till_done()) yield
async def test_setup_platform_discover_client(hass): """Test setting up the platform from discovery.""" LOCATIONS.append({"locationName": "Client 1", "clientAddr": "1"}) LOCATIONS.append({"locationName": "Client 2", "clientAddr": "2"}) with MockDependency("DirectPy"), patch("DirectPy.DIRECTV", new=MockDirectvClass): await async_setup_component(hass, DOMAIN, WORKING_CONFIG) await hass.async_block_till_done() hass.async_create_task( async_load_platform( hass, DOMAIN, "directv", DISCOVERY_INFO, {"media_player": {}} ) ) await hass.async_block_till_done() del LOCATIONS[-1] del LOCATIONS[-1] state = hass.states.get(MAIN_ENTITY_ID) assert state state = hass.states.get("media_player.client_1") assert state state = hass.states.get("media_player.client_2") assert state assert len(hass.states.async_entity_ids("media_player")) == 3
def mock_tellduslive(supports_local_api, authorize): """Mock tellduslive.""" with MockDependency("tellduslive") as mock_tellduslive_: mock_tellduslive_.supports_local_api.return_value = supports_local_api mock_tellduslive_.Session().authorize.return_value = authorize mock_tellduslive_.Session().access_token = "token" mock_tellduslive_.Session().access_token_secret = "token_secret" mock_tellduslive_.Session().authorize_url = "https://example.com" yield mock_tellduslive_
def mock_tellduslive(supports_local_api, authorize): """Mock tellduslive.""" with MockDependency('tellduslive') as mock_tellduslive_: mock_tellduslive_.supports_local_api.return_value = supports_local_api mock_tellduslive_.Session().authorize.return_value = authorize mock_tellduslive_.Session().access_token = 'token' mock_tellduslive_.Session().access_token_secret = 'token_secret' mock_tellduslive_.Session().authorize_url = 'https://example.com' yield mock_tellduslive_
async def test_password_or_pub_key_required(hass): """Test creating an AsusWRT scanner without a pass or pubkey.""" with MockDependency("aioasuswrt.asuswrt") as mocked_asus: mocked_asus.AsusWrt().connection.async_connect = mock_coro_func() mocked_asus.AsusWrt().is_connected = False result = await async_setup_component( hass, DOMAIN, {DOMAIN: {CONF_HOST: "fake_host", CONF_USERNAME: "******"}} ) assert not result
async def test_setup_platform_config(hass): """Test setting up the platform from configuration.""" with MockDependency("DirectPy"), patch("DirectPy.DIRECTV", new=MockDirectvClass): await async_setup_component(hass, DOMAIN, WORKING_CONFIG) await hass.async_block_till_done() state = hass.states.get(MAIN_ENTITY_ID) assert state assert len(hass.states.async_entity_ids("media_player")) == 1
def mock_daikin(): """Mock pydaikin.""" async def mock_daikin_init(): """Mock the init function in pydaikin.""" pass with MockDependency('pydaikin.appliance') as mock_daikin_: mock_daikin_.Appliance().values.get.return_value = 'AABBCCDDEEFF' mock_daikin_.Appliance().init = mock_daikin_init yield mock_daikin_
def mock_pypoint(is_authorized): # pylint: disable=W0621 """Mock pypoint.""" with MockDependency('pypoint') as mock_pypoint_: mock_pypoint_.PointSession().get_access_token.return_value = { 'access_token': 'boo' } mock_pypoint_.PointSession().is_authorized = is_authorized mock_pypoint_.PointSession().user.return_value = { 'email': '*****@*****.**' } yield mock_pypoint_
def mock_pypoint(is_authorized): # pylint: disable=W0621 """Mock pypoint.""" with MockDependency("pypoint") as mock_pypoint_: mock_pypoint_.PointSession().get_access_token.return_value = { "access_token": "boo" } mock_pypoint_.PointSession().is_authorized = is_authorized mock_pypoint_.PointSession().user.return_value = { "email": "*****@*****.**" } yield mock_pypoint_
async def test_not_configuring_cast_not_creates_entry(hass): """Test that no config will not create an entry.""" with patch('homeassistant.components.cast.async_setup_entry', return_value=mock_coro(True)) as mock_setup, \ MockDependency('pychromecast', 'discovery'), \ patch('pychromecast.discovery.discover_chromecasts', return_value=True): await async_setup_component(hass, cast.DOMAIN, {}) await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 0
async def test_not_configuring_cast_not_creates_entry(opp): """Test that no config will not create an entry.""" with patch("openpeerpower.components.cast.async_setup_entry", return_value=mock_coro(True)) as mock_setup, MockDependency( "pychromecast", "discovery"), patch( "pychromecast.discovery.discover_chromecasts", return_value=True): await async_setup_component(opp, cast.DOMAIN, {}) await opp.async_block_till_done() assert len(mock_setup.mock_calls) == 0
async def test_setup_no_host(hass, requests_mock): """No host specified in any way.""" requests_mock.get(hue.API_NUPNP, json=[]) with MockDependency('phue') as mock_phue: result = await async_setup_component(hass, hue.DOMAIN, {hue.DOMAIN: {}}) assert result mock_phue.Bridge.assert_not_called() assert hass.data[hue.DOMAIN] == {}
async def test_setup(hass): """Test setting up the Melissa component.""" with MockDependency("melissa") as mocked_melissa: mocked_melissa.AsyncMelissa().async_connect = mock_coro_func() await melissa.async_setup(hass, VALID_CONFIG) mocked_melissa.AsyncMelissa.assert_called_with(username="******", password="******") assert melissa.DATA_MELISSA in hass.data assert isinstance(hass.data[melissa.DATA_MELISSA], type(mocked_melissa.AsyncMelissa()))
def mock_logi_circle(): """Mock logi_circle.""" with MockDependency('logi_circle', 'exception') as mock_logi_circle_: mock_logi_circle_.exception.AuthorizationFailed = AuthorizationFailed mock_logi_circle_.LogiCircle().authorize = Mock(return_value=mock_coro( return_value=True)) mock_logi_circle_.LogiCircle().close = Mock(return_value=mock_coro( return_value=True)) mock_logi_circle_.LogiCircle().account = mock_coro( return_value={'accountId': 'testId'}) mock_logi_circle_.LogiCircle().authorize_url = 'http://authorize.url' yield mock_logi_circle_
def mock_logi_circle(): """Mock logi_circle.""" with MockDependency("logi_circle", "exception") as mock_logi_circle_: mock_logi_circle_.exception.AuthorizationFailed = AuthorizationFailed mock_logi_circle_.LogiCircle().authorize = Mock(return_value=mock_coro( return_value=True)) mock_logi_circle_.LogiCircle().close = Mock(return_value=mock_coro( return_value=True)) mock_logi_circle_.LogiCircle().account = mock_coro( return_value={"accountId": "testId"}) mock_logi_circle_.LogiCircle().authorize_url = "http://authorize.url" yield mock_logi_circle_
async def test_islamic_prayer_times_data_get_prayer_times(hass): """Test Islamic prayer times data fetcher.""" with MockDependency("prayer_times_calculator") as mock_pt_calc: mock_pt_calc.PrayerTimesCalculator.return_value.fetch_prayer_times.return_value = ( PRAYER_TIMES) pt_data = IslamicPrayerTimesData(latitude=LATITUDE, longitude=LONGITUDE, calc_method=CALC_METHOD) assert pt_data.get_new_prayer_times() == PRAYER_TIMES assert pt_data.prayer_times_info == PRAYER_TIMES
async def test_setup_platform_discover(hass): """Test setting up the platform from discovery.""" with MockDependency('DirectPy'), \ patch('DirectPy.DIRECTV', new=MockDirectvClass): hass.async_create_task( async_load_platform(hass, mp.DOMAIN, 'directv', DISCOVERY_INFO, {'media_player': {}})) await hass.async_block_till_done() state = hass.states.get(MAIN_ENTITY_ID) assert state assert len(hass.states.async_entity_ids('media_player')) == 1
async def test_creating_entry_sets_up_media_player(hass): """Test setting up Cast loads the media player.""" with patch('homeassistant.components.media_player.cast.async_setup_entry', return_value=mock_coro(True)) as mock_setup, \ MockDependency('pychromecast', 'discovery'), \ patch('pychromecast.discovery.discover_chromecasts', return_value=True): result = await hass.config_entries.flow.async_init(cast.DOMAIN) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1
async def test_configuring_cast_creates_entry(hass): """Test that specifying config will create an entry.""" with patch( "homeassistant.components.cast.async_setup_entry", return_value=mock_coro(True) ) as mock_setup, MockDependency("pychromecast", "discovery"), patch( "pychromecast.discovery.discover_chromecasts", return_value=True ): await async_setup_component( hass, cast.DOMAIN, {"cast": {"some_config": "to_trigger_import"}} ) await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1
async def test_islamic_prayer_times_sensor_update(hass): """Test Islamic prayer times sensor update.""" new_prayer_times = { "Fajr": "06:10", "Sunrise": "07:25", "Dhuhr": "12:30", "Asr": "15:32", "Maghrib": "17:45", "Isha": "18:53", "Midnight": "00:45", } with MockDependency("prayer_times_calculator") as mock_pt_calc: mock_pt_calc.PrayerTimesCalculator.return_value.fetch_prayer_times.side_effect = [ PRAYER_TIMES, new_prayer_times, ] config = { "sensor": { "platform": "islamic_prayer_times", "sensors": ["maghrib"] } } assert await async_setup_component(hass, "sensor", config) entity_id = "sensor.islamic_prayer_time_maghrib" pt_dt = get_prayer_time_as_dt(PRAYER_TIMES["Maghrib"]) state = hass.states.get(entity_id) assert state.state == pt_dt.isoformat() midnight = PRAYER_TIMES["Midnight"] now = dt_util.as_local(dt_util.now()) today = now.date() midnight_dt_str = "{}::{}".format(str(today), midnight) midnight_dt = datetime.strptime(midnight_dt_str, "%Y-%m-%d::%H:%M") future = midnight_dt + timedelta(days=1, minutes=1) with patch( "homeassistant.components.islamic_prayer_times.sensor" ".dt_util.utcnow", return_value=future, ): async_fire_time_changed(hass, future) await hass.async_block_till_done() state = hass.states.get(entity_id) pt_dt = get_prayer_time_as_dt(new_prayer_times["Maghrib"]) assert state.state == pt_dt.isoformat()