Beispiel #1
0
async def test_pure_hot_cool_link_set_mode(mocked_login, mocked_devices, hass):
    """Test set climate mode."""
    await async_setup_component(hass, DYSON_DOMAIN, _get_config())
    await hass.async_block_till_done()

    device = mocked_devices.return_value[0]

    await hass.services.async_call(
        DOMAIN,
        SERVICE_SET_HVAC_MODE,
        {
            ATTR_ENTITY_ID: "climate.temp_name",
            ATTR_HVAC_MODE: HVAC_MODE_HEAT
        },
        True,
    )

    set_config = device.set_configuration
    assert set_config.call_args == call(heat_mode=HeatMode.HEAT_ON)

    await hass.services.async_call(
        DOMAIN,
        SERVICE_SET_HVAC_MODE,
        {
            ATTR_ENTITY_ID: "climate.temp_name",
            ATTR_HVAC_MODE: HVAC_MODE_COOL
        },
        True,
    )

    set_config = device.set_configuration
    assert set_config.call_args == call(heat_mode=HeatMode.HEAT_OFF)
Beispiel #2
0
async def test_play_media(hass, remote):
    """Test for play_media."""
    asyncio_sleep = asyncio.sleep
    sleeps = []

    async def sleep(duration, loop):
        sleeps.append(duration)
        await asyncio_sleep(0, loop=loop)

    await setup_samsungtv(hass, MOCK_CONFIG)
    with patch("asyncio.sleep", new=sleep):
        assert await hass.services.async_call(
            DOMAIN,
            SERVICE_PLAY_MEDIA,
            {
                ATTR_ENTITY_ID: ENTITY_ID,
                ATTR_MEDIA_CONTENT_TYPE: MEDIA_TYPE_CHANNEL,
                ATTR_MEDIA_CONTENT_ID: "576",
            },
            True,
        )
        # keys and update called
        assert remote.control.call_count == 4
        assert remote.control.call_args_list == [
            call("KEY_5"),
            call("KEY_7"),
            call("KEY_6"),
            call("KEY_ENTER"),
        ]
        assert remote.close.call_count == 1
        assert remote.close.call_args_list == [call()]
        assert len(sleeps) == 3
Beispiel #3
0
async def test_restore_all_active_subscriptions_on_reconnect(
        hass, mqtt_client_mock, mqtt_mock):
    """Test active subscriptions are restored correctly on reconnect."""
    # Fake that the client is connected
    mqtt_mock().connected = True

    mqtt_client_mock.subscribe.side_effect = (
        (0, 1),
        (0, 2),
        (0, 3),
        (0, 4),
    )

    unsub = await mqtt.async_subscribe(hass, "test/state", None, qos=2)
    await mqtt.async_subscribe(hass, "test/state", None)
    await mqtt.async_subscribe(hass, "test/state", None, qos=1)
    await hass.async_block_till_done()

    expected = [
        call("test/state", 2),
        call("test/state", 0),
        call("test/state", 1),
    ]
    assert mqtt_client_mock.subscribe.mock_calls == expected

    unsub()
    await hass.async_block_till_done()
    assert mqtt_client_mock.unsubscribe.call_count == 0

    mqtt_mock._mqtt_on_disconnect(None, None, 0)
    mqtt_mock._mqtt_on_connect(None, None, None, 0)
    await hass.async_block_till_done()

    expected.append(call("test/state", 1))
    assert mqtt_client_mock.subscribe.mock_calls == expected
async def test_device_remove_stale_tasmota_device(
    hass, device_reg, hass_ws_client, mqtt_mock, setup_tasmota
):
    """Test removing a stale (undiscovered) Tasmota device through device registry."""
    config_entry = hass.config_entries.async_entries("tasmota")[0]

    mac = "12:34:56:AB:CD:EF"
    device_entry = device_reg.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        connections={("mac", mac)},
    )
    assert device_entry is not None

    device_reg.async_remove_device(device_entry.id)
    await hass.async_block_till_done()

    # Verify device entry is removed
    device_entry = device_reg.async_get_device(set(), {("mac", mac)})
    assert device_entry is None

    # Verify retained discovery topic has been cleared
    mac = mac.replace(":", "")
    mqtt_mock.async_publish.assert_has_calls(
        [
            call(f"tasmota/discovery/{mac}/config", "", 0, True),
            call(f"tasmota/discovery/{mac}/sensors", "", 0, True),
        ],
        any_order=True,
    )
async def test_device_remove(
    hass, mqtt_mock, caplog, device_reg, entity_reg, setup_tasmota
):
    """Test removing a discovered device through device registry."""
    config = copy.deepcopy(DEFAULT_CONFIG)
    mac = config["mac"]

    async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config))
    await hass.async_block_till_done()

    # Verify device entry is created
    device_entry = device_reg.async_get_device(set(), {("mac", mac)})
    assert device_entry is not None

    device_reg.async_remove_device(device_entry.id)
    await hass.async_block_till_done()

    # Verify device entry is removed
    device_entry = device_reg.async_get_device(set(), {("mac", mac)})
    assert device_entry is None

    # Verify retained discovery topic has been cleared
    mqtt_mock.async_publish.assert_has_calls(
        [
            call(f"tasmota/discovery/{mac}/config", "", 0, True),
            call(f"tasmota/discovery/{mac}/sensors", "", 0, True),
        ],
        any_order=True,
    )
Beispiel #6
0
async def test_see_service(mock_see, hass):
    """Test the see service with a unicode dev_id and NO MAC."""
    with assert_setup_component(1, device_tracker.DOMAIN):
        assert await async_setup_component(hass, device_tracker.DOMAIN,
                                           TEST_PLATFORM)
    params = {
        "dev_id": "some_device",
        "host_name": "example.com",
        "location_name": "Work",
        "gps": [0.3, 0.8],
        "attributes": {
            "test": "test"
        },
    }
    common.async_see(hass, **params)
    await hass.async_block_till_done()
    assert mock_see.call_count == 1
    assert mock_see.call_count == 1
    assert mock_see.call_args == call(**params)

    mock_see.reset_mock()
    params["dev_id"] += chr(233)  # e' acute accent from icloud

    common.async_see(hass, **params)
    await hass.async_block_till_done()
    assert mock_see.call_count == 1
    assert mock_see.call_count == 1
    assert mock_see.call_args == call(**params)
Beispiel #7
0
async def test_sending_xy_color(hass, mqtt_mock):
    """Test light.turn_on with hs color sends xy color parameters."""
    assert await async_setup_component(
        hass,
        light.DOMAIN,
        {
            light.DOMAIN: {
                "platform": "mqtt",
                "schema": "json",
                "name": "test",
                "command_topic": "test_light_rgb/set",
                "brightness": True,
                "xy": True,
            }
        },
    )

    state = hass.states.get("light.test")
    assert state.state == STATE_OFF

    await common.async_turn_on(
        hass, "light.test", brightness=50, xy_color=[0.123, 0.123]
    )
    await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78])
    await common.async_turn_on(
        hass, "light.test", rgb_color=[255, 128, 0], white_value=80
    )

    mqtt_mock.async_publish.assert_has_calls(
        [
            call(
                "test_light_rgb/set",
                JsonValidator(
                    '{"state": "ON", "color": {"x": 0.14, "y": 0.131},'
                    ' "brightness": 50}'
                ),
                0,
                False,
            ),
            call(
                "test_light_rgb/set",
                JsonValidator(
                    '{"state": "ON", "color": {"x": 0.654, "y": 0.301},'
                    ' "brightness": 50}'
                ),
                0,
                False,
            ),
            call(
                "test_light_rgb/set",
                JsonValidator(
                    '{"state": "ON", "color": {"x": 0.611, "y": 0.375},'
                    ' "white_value": 80}'
                ),
                0,
                False,
            ),
        ],
        any_order=True,
    )
Beispiel #8
0
async def test_learn_timeout(hass):
    """Test learn service."""
    mock_api = MagicMock()
    mock_api.enter_learning.return_value = None
    mock_api.check_data.return_value = None
    device = BroadlinkDevice(hass, mock_api)

    await async_setup_service(hass, DUMMY_HOST, device)

    now = utcnow()

    with patch.object(
            hass.components.persistent_notification,
            "async_create") as mock_create, patch(
                "homeassistant.components.broadlink.utcnow") as mock_utcnow:

        mock_utcnow.side_effect = [now, now + timedelta(20)]

        await hass.services.async_call(DOMAIN, SERVICE_LEARN,
                                       {"host": DUMMY_HOST})
        await hass.async_block_till_done()

        assert device.api.enter_learning.call_count == 1
        assert device.api.enter_learning.call_args == call()

        assert mock_create.call_count == 1
        assert mock_create.call_args == call("No signal was received",
                                             title="Broadlink switch")
Beispiel #9
0
async def test_set_operation_with_power_command(hass, mqtt_mock):
    """Test setting of new operation mode with power command enabled."""
    config = copy.deepcopy(DEFAULT_CONFIG)
    config["climate"]["power_command_topic"] = "power-command"
    assert await async_setup_component(hass, CLIMATE_DOMAIN, config)
    await hass.async_block_till_done()

    state = hass.states.get(ENTITY_CLIMATE)
    assert state.state == "off"
    await common.async_set_hvac_mode(hass, "cool", ENTITY_CLIMATE)
    state = hass.states.get(ENTITY_CLIMATE)
    assert state.state == "cool"
    mqtt_mock.async_publish.assert_has_calls([
        call("power-command", "ON", 0, False),
        call("mode-topic", "cool", 0, False)
    ])
    mqtt_mock.async_publish.reset_mock()

    await common.async_set_hvac_mode(hass, "off", ENTITY_CLIMATE)
    state = hass.states.get(ENTITY_CLIMATE)
    assert state.state == "off"
    mqtt_mock.async_publish.assert_has_calls([
        call("power-command", "OFF", 0, False),
        call("mode-topic", "off", 0, False)
    ])
    mqtt_mock.async_publish.reset_mock()
Beispiel #10
0
async def test_verisure_no_default_code(hass):
    """Test configs without a default lock code."""
    await setup_verisure_locks(hass, NO_DEFAULT_LOCK_CODE_CONFIG)
    with mock_hub(NO_DEFAULT_LOCK_CODE_CONFIG, STATE_UNLOCKED) as hub:

        mock = hub.session.set_lock_state
        await hass.services.async_call(LOCK_DOMAIN, SERVICE_LOCK,
                                       {"entity_id": "lock.door_lock"})
        await hass.async_block_till_done()
        assert mock.call_count == 0

        await hass.services.async_call(LOCK_DOMAIN, SERVICE_LOCK, {
            "entity_id": "lock.door_lock",
            "code": "12345"
        })
        await hass.async_block_till_done()
        assert mock.call_args == call("12345", LOCKS[0], "lock")

        mock.reset_mock()
        await hass.services.async_call(LOCK_DOMAIN, SERVICE_UNLOCK,
                                       {"entity_id": "lock.door_lock"})
        await hass.async_block_till_done()
        assert mock.call_count == 0

        await hass.services.async_call(
            LOCK_DOMAIN,
            SERVICE_UNLOCK,
            {
                "entity_id": "lock.door_lock",
                "code": "12345"
            },
        )
        await hass.async_block_till_done()
        assert mock.call_args == call("12345", LOCKS[0], "unlock")
Beispiel #11
0
async def test_set_target_temperature(hass, mqtt_mock):
    """Test setting the target temperature."""
    assert await async_setup_component(hass, CLIMATE_DOMAIN, DEFAULT_CONFIG)
    await hass.async_block_till_done()

    state = hass.states.get(ENTITY_CLIMATE)
    assert state.attributes.get("temperature") == 21
    await common.async_set_hvac_mode(hass, "heat", ENTITY_CLIMATE)
    state = hass.states.get(ENTITY_CLIMATE)
    assert state.state == "heat"
    mqtt_mock.async_publish.assert_called_once_with("mode-topic", "heat", 0,
                                                    False)
    mqtt_mock.async_publish.reset_mock()
    await common.async_set_temperature(hass,
                                       temperature=47,
                                       entity_id=ENTITY_CLIMATE)
    state = hass.states.get(ENTITY_CLIMATE)
    assert state.attributes.get("temperature") == 47
    mqtt_mock.async_publish.assert_called_once_with("temperature-topic",
                                                    "47.0", 0, False)

    # also test directly supplying the operation mode to set_temperature
    mqtt_mock.async_publish.reset_mock()
    await common.async_set_temperature(hass,
                                       temperature=21,
                                       hvac_mode="cool",
                                       entity_id=ENTITY_CLIMATE)
    state = hass.states.get(ENTITY_CLIMATE)
    assert state.state == "cool"
    assert state.attributes.get("temperature") == 21
    mqtt_mock.async_publish.assert_has_calls([
        call("mode-topic", "cool", 0, False),
        call("temperature-topic", "21.0", 0, False),
    ])
    mqtt_mock.async_publish.reset_mock()
Beispiel #12
0
async def test_set_away_mode(hass, mqtt_mock):
    """Test setting of the away mode."""
    config = copy.deepcopy(DEFAULT_CONFIG)
    config["climate"]["payload_on"] = "AN"
    config["climate"]["payload_off"] = "AUS"

    assert await async_setup_component(hass, CLIMATE_DOMAIN, config)
    await hass.async_block_till_done()

    state = hass.states.get(ENTITY_CLIMATE)
    assert state.attributes.get("preset_mode") == "none"
    await common.async_set_preset_mode(hass, "away", ENTITY_CLIMATE)
    mqtt_mock.async_publish.assert_called_once_with("away-mode-topic", "AN", 0,
                                                    False)
    mqtt_mock.async_publish.reset_mock()
    state = hass.states.get(ENTITY_CLIMATE)
    assert state.attributes.get("preset_mode") == "away"

    await common.async_set_preset_mode(hass, PRESET_NONE, ENTITY_CLIMATE)
    mqtt_mock.async_publish.assert_called_once_with("away-mode-topic", "AUS",
                                                    0, False)
    state = hass.states.get(ENTITY_CLIMATE)
    assert state.attributes.get("preset_mode") == "none"

    await common.async_set_preset_mode(hass, "hold-on", ENTITY_CLIMATE)
    mqtt_mock.async_publish.reset_mock()

    await common.async_set_preset_mode(hass, "away", ENTITY_CLIMATE)
    mqtt_mock.async_publish.assert_has_calls([
        call("hold-topic", "off", 0, False),
        call("away-mode-topic", "AN", 0, False)
    ])
    state = hass.states.get(ENTITY_CLIMATE)
    assert state.attributes.get("preset_mode") == "away"
Beispiel #13
0
async def test_pure_hot_cool_link_set_fan(mocked_login, mocked_devices, hass):
    """Test set climate fan."""
    await async_setup_component(hass, DYSON_DOMAIN, _get_config())
    await hass.async_block_till_done()

    device = mocked_devices.return_value[0]
    device.temp_unit = TEMP_CELSIUS

    await hass.services.async_call(
        DOMAIN,
        SERVICE_SET_FAN_MODE,
        {
            ATTR_ENTITY_ID: "climate.temp_name",
            ATTR_FAN_MODE: FAN_FOCUS
        },
        True,
    )

    set_config = device.set_configuration
    assert set_config.call_args == call(focus_mode=FocusMode.FOCUS_ON)

    await hass.services.async_call(
        DOMAIN,
        SERVICE_SET_FAN_MODE,
        {
            ATTR_ENTITY_ID: "climate.temp_name",
            ATTR_FAN_MODE: FAN_DIFFUSE
        },
        True,
    )

    set_config = device.set_configuration
    assert set_config.call_args == call(focus_mode=FocusMode.FOCUS_OFF)
Beispiel #14
0
async def test_autodetect_websocket_ssl(hass, remote, remotews):
    """Test for send key with autodetection of protocol."""
    with patch(
        "homeassistant.components.samsungtv.bridge.Remote",
        side_effect=OSError("Boom"),
    ), patch(
        "homeassistant.components.samsungtv.bridge.SamsungTVWS",
        side_effect=[WebSocketProtocolException("Boom"), DEFAULT_MOCK],
    ) as remotews:
        enter = Mock()
        type(enter).token = PropertyMock(return_value="123456789")
        remote = Mock()
        remote.__enter__ = Mock(return_value=enter)
        remote.__exit__ = Mock(return_value=False)
        remotews.return_value = remote

        result = await hass.config_entries.flow.async_init(
            DOMAIN, context={"source": "user"}, data=MOCK_USER_DATA
        )
        assert result["type"] == "create_entry"
        assert result["data"][CONF_METHOD] == "websocket"
        assert result["data"][CONF_TOKEN] == "123456789"
        assert remotews.call_count == 2
        assert remotews.call_args_list == [
            call(**AUTODETECT_WEBSOCKET_PLAIN),
            call(**AUTODETECT_WEBSOCKET_SSL),
        ]
Beispiel #15
0
async def test_sending_rgb_color_no_brightness(hass, mqtt_mock):
    """Test light.turn_on with hs color sends rgb color parameters."""
    assert await async_setup_component(
        hass,
        light.DOMAIN,
        {
            light.DOMAIN: {
                "platform": "mqtt",
                "schema": "json",
                "name": "test",
                "command_topic": "test_light_rgb/set",
                "rgb": True,
            }
        },
    )
    await hass.async_block_till_done()

    state = hass.states.get("light.test")
    assert state.state == STATE_OFF

    await common.async_turn_on(hass,
                               "light.test",
                               brightness=50,
                               xy_color=[0.123, 0.123])
    await common.async_turn_on(hass,
                               "light.test",
                               brightness=50,
                               hs_color=[359, 78])
    await common.async_turn_on(hass,
                               "light.test",
                               rgb_color=[255, 128, 0],
                               brightness=255)

    mqtt_mock.async_publish.assert_has_calls(
        [
            call(
                "test_light_rgb/set",
                JsonValidator(
                    '{"state": "ON", "color": {"r": 0, "g": 24, "b": 50}}'),
                0,
                False,
            ),
            call(
                "test_light_rgb/set",
                JsonValidator(
                    '{"state": "ON", "color": {"r": 50, "g": 11, "b": 11}}'),
                0,
                False,
            ),
            call(
                "test_light_rgb/set",
                JsonValidator(
                    '{"state": "ON", "color": {"r": 255, "g": 128, "b": 0}}'),
                0,
                False,
            ),
        ],
        any_order=True,
    )
Beispiel #16
0
def get_mock_call_fixture(request):
    """Get version specific lambda to make write API call mock."""
    if request.param == influxdb.API_VERSION_2:
        return lambda body, precision=None: call(
            bucket=DEFAULT_BUCKET, record=body, write_precision=precision
        )
    # pylint: disable=unnecessary-lambda
    return lambda body, precision=None: call(body, time_precision=precision)
Beispiel #17
0
async def test_media_pause(hass, remote):
    """Test for media_pause."""
    await setup_samsungtv(hass, MOCK_CONFIG)
    assert await hass.services.async_call(DOMAIN, SERVICE_MEDIA_PAUSE,
                                          {ATTR_ENTITY_ID: ENTITY_ID}, True)
    # key and update called
    assert remote.control.call_count == 1
    assert remote.control.call_args_list == [call("KEY_PAUSE")]
    assert remote.close.call_count == 1
    assert remote.close.call_args_list == [call()]
Beispiel #18
0
async def test_media_previous_track(hass, remote):
    """Test for media_previous_track."""
    await setup_samsungtv(hass, MOCK_CONFIG)
    assert await hass.services.async_call(DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK,
                                          {ATTR_ENTITY_ID: ENTITY_ID}, True)
    # key and update called
    assert remote.control.call_count == 1
    assert remote.control.call_args_list == [call("KEY_CHDOWN")]
    assert remote.close.call_count == 1
    assert remote.close.call_args_list == [call()]
Beispiel #19
0
async def test_volume_down(hass, remote):
    """Test for volume_down."""
    await setup_samsungtv(hass, MOCK_CONFIG)
    assert await hass.services.async_call(DOMAIN, SERVICE_VOLUME_DOWN,
                                          {ATTR_ENTITY_ID: ENTITY_ID}, True)
    # key and update called
    assert remote.control.call_count == 1
    assert remote.control.call_args_list == [call("KEY_VOLDOWN")]
    assert remote.close.call_count == 1
    assert remote.close.call_args_list == [call()]
Beispiel #20
0
async def test_send_key(hass, remote):
    """Test for send key."""
    await setup_samsungtv(hass, MOCK_CONFIG)
    assert await hass.services.async_call(DOMAIN, SERVICE_VOLUME_UP,
                                          {ATTR_ENTITY_ID: ENTITY_ID}, True)
    state = hass.states.get(ENTITY_ID)
    # key and update called
    assert remote.control.call_count == 1
    assert remote.control.call_args_list == [call("KEY_VOLUP")]
    assert remote.close.call_count == 1
    assert remote.close.call_args_list == [call()]
    assert state.state == STATE_ON
async def test_minio_services(hass, caplog, minio_client):
    """Test Minio services."""
    hass.config.allowlist_external_dirs = {"/test"}

    await async_setup_component(
        hass,
        DOMAIN,
        {
            DOMAIN: {
                CONF_HOST: "localhost",
                CONF_PORT: "9000",
                CONF_ACCESS_KEY: "abcdef",
                CONF_SECRET_KEY: "0123456789",
                CONF_SECURE: "true",
            }
        },
    )

    await hass.async_start()
    await hass.async_block_till_done()

    assert "Setup of domain minio took" in caplog.text

    # Call services
    await hass.services.async_call(
        DOMAIN,
        "put",
        {"file_path": "/test/some_file", "key": "some_key", "bucket": "some_bucket"},
        blocking=True,
    )
    assert minio_client.fput_object.call_args == call(
        "some_bucket", "some_key", "/test/some_file"
    )
    minio_client.reset_mock()

    await hass.services.async_call(
        DOMAIN,
        "get",
        {"file_path": "/test/some_file", "key": "some_key", "bucket": "some_bucket"},
        blocking=True,
    )
    assert minio_client.fget_object.call_args == call(
        "some_bucket", "some_key", "/test/some_file"
    )
    minio_client.reset_mock()

    await hass.services.async_call(
        DOMAIN, "remove", {"key": "some_key", "bucket": "some_bucket"}, blocking=True
    )
    assert minio_client.remove_object.call_args == call("some_bucket", "some_key")
    minio_client.reset_mock()
Beispiel #22
0
    def _test_notify_file(self, timestamp):
        """Test the notify file output."""
        filename = "mock_file"
        message = "one, two, testing, testing"
        with assert_setup_component(1) as handle_config:
            assert setup_component(
                self.hass,
                notify.DOMAIN,
                {
                    "notify": {
                        "name": "test",
                        "platform": "file",
                        "filename": filename,
                        "timestamp": timestamp,
                    }
                },
            )
        assert handle_config[notify.DOMAIN]

        m_open = mock_open()
        with patch("homeassistant.components.file.notify.open",
                   m_open,
                   create=True), patch(
                       "homeassistant.components.file.notify.os.stat"
                   ) as mock_st, patch("homeassistant.util.dt.utcnow",
                                       return_value=dt_util.utcnow()):

            mock_st.return_value.st_size = 0
            title = (
                f"{ATTR_TITLE_DEFAULT} notifications "
                f"(Log started: {dt_util.utcnow().isoformat()})\n{'-' * 80}\n")

            self.hass.services.call("notify",
                                    "test", {"message": message},
                                    blocking=True)

            full_filename = os.path.join(self.hass.config.path(), filename)
            assert m_open.call_count == 1
            assert m_open.call_args == call(full_filename, "a")

            assert m_open.return_value.write.call_count == 2
            if not timestamp:
                assert m_open.return_value.write.call_args_list == [
                    call(title),
                    call(f"{message}\n"),
                ]
            else:
                assert m_open.return_value.write.call_args_list == [
                    call(title),
                    call(f"{dt_util.utcnow().isoformat()} {message}\n"),
                ]
Beispiel #23
0
async def test_mute_volume(hass, remote):
    """Test for mute_volume."""
    await setup_samsungtv(hass, MOCK_CONFIG)
    assert await hass.services.async_call(
        DOMAIN,
        SERVICE_VOLUME_MUTE,
        {ATTR_ENTITY_ID: ENTITY_ID, ATTR_MEDIA_VOLUME_MUTED: True},
        True,
    )
    # key and update called
    assert remote.control.call_count == 1
    assert remote.control.call_args_list == [call("KEY_MUTE")]
    assert remote.close.call_count == 1
    assert remote.close.call_args_list == [call()]
Beispiel #24
0
async def test_select_source(hass, remote):
    """Test for select_source."""
    await setup_samsungtv(hass, MOCK_CONFIG)
    assert await hass.services.async_call(
        DOMAIN,
        SERVICE_SELECT_SOURCE,
        {ATTR_ENTITY_ID: ENTITY_ID, ATTR_INPUT_SOURCE: "HDMI"},
        True,
    )
    # key and update called
    assert remote.control.call_count == 1
    assert remote.control.call_args_list == [call("KEY_HDMI")]
    assert remote.close.call_count == 1
    assert remote.close.call_args_list == [call()]
async def test_service_request_channel_level(hass):
    """Test requesting the level of a channel via service call."""
    with patch(
        "homeassistant.components.dynalite.bridge.DynaliteDevices.async_setup",
        return_value=True,
    ), patch(
        "dynalite_devices_lib.dynalite.Dynalite.request_channel_level",
        return_value=True,
    ) as mock_req_chan_lvl:
        assert await async_setup_component(
            hass,
            dynalite.DOMAIN,
            {
                dynalite.DOMAIN: {
                    dynalite.CONF_BRIDGES: [
                        {
                            CONF_HOST: "1.2.3.4",
                            dynalite.CONF_AREA: {"7": {CONF_NAME: "test"}},
                        },
                        {CONF_HOST: "5.6.7.8"},
                    ]
                }
            },
        )
        await hass.async_block_till_done()
        assert len(hass.config_entries.async_entries(dynalite.DOMAIN)) == 2
        await hass.services.async_call(
            dynalite.DOMAIN,
            "request_channel_level",
            {"host": "1.2.3.4", "area": 2, "channel": 3},
        )
        await hass.async_block_till_done()
        mock_req_chan_lvl.assert_called_once_with(2, 3)
        mock_req_chan_lvl.reset_mock()
        with pytest.raises(MultipleInvalid):
            await hass.services.async_call(
                dynalite.DOMAIN,
                "request_channel_level",
                {"area": 3},
            )
        await hass.async_block_till_done()
        mock_req_chan_lvl.assert_not_called()
        await hass.services.async_call(
            dynalite.DOMAIN,
            "request_channel_level",
            {"area": 4, "channel": 5},
        )
        await hass.async_block_till_done()
        assert mock_req_chan_lvl.mock_calls == [call(4, 5), call(4, 5)]
Beispiel #26
0
async def test_setup_entry(create_emitters, create_entities) -> None:
    def _create_entities(*args: Any) -> Awaitable[List[Any]]:
        future: Future[List[Any]] = Future()
        future.set_result([])
        return future

    create_entities.side_effect = _create_entities

    create_emitters.return_value = Future()
    create_emitters.return_value.set_result(None)

    from custom_components.hubitat.switch import (
        async_setup_entry,
        HubitatSwitch,
        HubitatPowerMeterSwitch,
    )

    mock_hass = Mock(spec=["async_register"])
    mock_config_entry = Mock(spec=ConfigEntry)

    def add_entities(entities: List[Entity]) -> None:
        pass

    mock_add_entities = Mock(spec=add_entities)

    await async_setup_entry(mock_hass, mock_config_entry, mock_add_entities)

    assert create_entities.call_count == 3, "expected 3 calls to create entities"

    call1 = call(mock_hass, mock_config_entry, mock_add_entities, "switch",
                 HubitatSwitch)
    call2 = call(
        mock_hass,
        mock_config_entry,
        mock_add_entities,
        "switch",
        HubitatPowerMeterSwitch,
    )
    call3 = call(
        mock_hass,
        mock_config_entry,
        mock_add_entities,
        "switch",
        HubitatPowerMeterSwitch,
    )
    assert create_entities.has_calls([call1, call2, call3])

    assert create_emitters.call_count == 1, "expected 1 call to create emitters"
async def test_setup_with_custom_location(hass):
    """Test the setup with a custom location."""
    # Set up some mock feed entries for this test.
    mock_entry_1 = _generate_mock_feed_entry("1234", "Title 1", 20.5, (-31.1, 150.1))

    with patch(
        "geojson_client.usgs_earthquake_hazards_program_feed."
        "UsgsEarthquakeHazardsProgramFeed"
    ) as mock_feed:
        mock_feed.return_value.update.return_value = "OK", [mock_entry_1]

        with assert_setup_component(1, geo_location.DOMAIN):
            assert await async_setup_component(
                hass, geo_location.DOMAIN, CONFIG_WITH_CUSTOM_LOCATION
            )
            await hass.async_block_till_done()

            # Artificially trigger update.
            hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
            # Collect events.
            await hass.async_block_till_done()

            all_states = hass.states.async_all()
            assert len(all_states) == 1

            assert mock_feed.call_args == call(
                (15.1, 25.2),
                "past_hour_m25_earthquakes",
                filter_minimum_magnitude=0.0,
                filter_radius=200.0,
            )
Beispiel #28
0
async def test_add_event_emitters(HubitatEventEmitter: Mock, get_hub: Mock) -> None:
    mock_device_1 = NonCallableMock(type="switch", attributes=["state"])
    mock_device_2 = NonCallableMock(type="button", attributes=["state"])
    MockHub = Mock(spec=Hub)
    mock_hub = MockHub()
    mock_hub.devices = {"id1": mock_device_1, "id2": mock_device_2}
    get_hub.return_value = mock_hub

    HubitatEventEmitter.return_value.update_device_registry = Mock(
        return_value="update_registry"
    )

    from custom_components.hubitat.entities import create_and_add_event_emitters

    mock_hass = Mock(spec=["async_create_task"])
    MockConfigEntry = Mock(spec=ConfigEntry)
    mock_entry = MockConfigEntry()

    def mock_is_emitter(device: Device) -> bool:
        return device.type == "button"

    is_emitter = Mock(side_effect=mock_is_emitter)

    await create_and_add_event_emitters(mock_hass, mock_entry, is_emitter)

    assert HubitatEventEmitter.call_count == 1, "expected 1 emitter to be created"
    assert mock_hass.async_create_task.call_count == 1, "expected 1 async creations"

    assert mock_hass.async_create_task.has_calls(
        [call("update_registry")]
    ), "1 update_device_registry task should have been created"

    assert (
        mock_hub.add_event_emitters.call_count == 1
    ), "event emitters should have been added to hub"
Beispiel #29
0
async def _test_service(
    hass: HomeAssistantType,
    domain: str,
    vizio_func_name: str,
    ha_service_name: str,
    additional_service_data: Optional[Dict[str, Any]],
    *args,
    **kwargs,
) -> None:
    """Test generic Vizio media player entity service."""
    kwargs["log_api_exception"] = False
    service_data = {ATTR_ENTITY_ID: ENTITY_ID}
    if additional_service_data:
        service_data.update(additional_service_data)

    with patch(
            f"homeassistant.components.vizio.media_player.VizioAsync.{vizio_func_name}"
    ) as service_call:
        await hass.services.async_call(
            domain,
            ha_service_name,
            service_data=service_data,
            blocking=True,
        )
        assert service_call.called

        if args or kwargs:
            assert service_call.call_args == call(*args, **kwargs)
Beispiel #30
0
async def test_setup_with_custom_location(hass):
    """Test the setup with a custom location."""
    # Set up some mock feed entries for this test.
    mock_entry_1 = _generate_mock_feed_entry(
        "1234", "Title 1", 20.5, (38.1, -3.1), category="Category 1"
    )

    with patch("georss_qld_bushfire_alert_client.QldBushfireAlertFeed") as mock_feed:
        mock_feed.return_value.update.return_value = "OK", [mock_entry_1]

        with assert_setup_component(1, geo_location.DOMAIN):
            assert await async_setup_component(
                hass, geo_location.DOMAIN, CONFIG_WITH_CUSTOM_LOCATION
            )

            # Artificially trigger update.
            hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
            # Collect events.
            await hass.async_block_till_done()

            all_states = hass.states.async_all()
            assert len(all_states) == 1

            assert mock_feed.call_args == call(
                (40.4, -3.7), filter_categories=[], filter_radius=200.0
            )