コード例 #1
0
async def test_cancel_wait_template(hass):
    """Test the cancelling while wait_template is present."""
    event = "test_event"
    events = async_capture_events(hass, event)
    sequence = cv.SCRIPT_SCHEMA(
        [
            {"wait_template": "{{ states.switch.test.state == 'off' }}"},
            {"event": event},
        ]
    )
    script_obj = script.Script(hass, sequence)
    wait_started_flag = async_watch_for_action(script_obj, "wait")

    try:
        hass.states.async_set("switch.test", "on")
        hass.async_create_task(script_obj.async_run())
        await asyncio.wait_for(wait_started_flag.wait(), 1)

        assert script_obj.is_running
        assert len(events) == 0
    except (AssertionError, asyncio.TimeoutError):
        await script_obj.async_stop()
        raise
    else:
        await script_obj.async_stop()

        assert not script_obj.is_running

        # Make sure the script is really stopped.

        hass.states.async_set("switch.test", "off")
        await hass.async_block_till_done()

        assert not script_obj.is_running
        assert len(events) == 0
コード例 #2
0
async def test_wait_template_timeout(hass, mock_timeout, continue_on_timeout, n_events):
    """Test the wait template, halt on timeout."""
    event = "test_event"
    events = async_capture_events(hass, event)
    sequence = [
        {"wait_template": "{{ states.switch.test.state == 'off' }}", "timeout": 5},
        {"event": event},
    ]
    if continue_on_timeout is not None:
        sequence[0]["continue_on_timeout"] = continue_on_timeout
    sequence = cv.SCRIPT_SCHEMA(sequence)
    script_obj = script.Script(hass, sequence)
    wait_started_flag = async_watch_for_action(script_obj, "wait")

    try:
        hass.states.async_set("switch.test", "on")
        hass.async_create_task(script_obj.async_run())
        await asyncio.wait_for(wait_started_flag.wait(), 1)

        assert script_obj.is_running
        assert len(events) == 0
    except (AssertionError, asyncio.TimeoutError):
        await script_obj.async_stop()
        raise
    else:
        async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=5))
        await hass.async_block_till_done()

        assert not script_obj.is_running
        assert len(events) == n_events
コード例 #3
0
ファイル: test_device_trigger.py プロジェクト: 2Fake/core
async def test_if_fires_on_event(hass, calls, device_reg, entity_reg, platform,
                                 camera_type, event_type):
    """Test for event triggers firing."""
    mac_address = "12:34:56:AB:CD:EF"
    connection = (device_registry.CONNECTION_NETWORK_MAC, mac_address)
    config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={})
    config_entry.add_to_hass(hass)
    device_entry = device_reg.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        connections={connection},
        identifiers={(NETATMO_DOMAIN, mac_address)},
        model=camera_type,
    )
    entity_reg.async_get_or_create(platform,
                                   NETATMO_DOMAIN,
                                   "5678",
                                   device_id=device_entry.id)
    events = async_capture_events(hass, "netatmo_event")

    assert await async_setup_component(
        hass,
        automation.DOMAIN,
        {
            automation.DOMAIN: [
                {
                    "trigger": {
                        "platform": "device",
                        "domain": NETATMO_DOMAIN,
                        "device_id": device_entry.id,
                        "entity_id": f"{platform}.{NETATMO_DOMAIN}_5678",
                        "type": event_type,
                    },
                    "action": {
                        "service": "test.automation",
                        "data_template": {
                            "some":
                            ("{{trigger.event.data.type}} - {{trigger.platform}} - {{trigger.event.data.device_id}}"
                             )
                        },
                    },
                },
            ]
        },
    )

    device = device_reg.async_get_device(set(), {connection})
    assert device is not None

    # Fake that the entity is turning on.
    hass.bus.async_fire(
        event_type=NETATMO_EVENT,
        event_data={
            "type": event_type,
            ATTR_DEVICE_ID: device.id,
        },
    )
    await hass.async_block_till_done()
    assert len(events) == 1
    assert len(calls) == 1
    assert calls[0].data["some"] == f"{event_type} - device - {device.id}"
コード例 #4
0
async def test_unknown_notification(hass, hank_binary_switch, integration,
                                    client):
    """Test behavior of unknown notification type events."""
    # just pick a random node to fake the notification event
    node = hank_binary_switch

    # We emit the event directly so we can skip any validation and event handling
    # by the lib. We will use a class that is guaranteed not to be recognized
    notification_obj = AsyncMock()
    notification_obj.node = node
    with pytest.raises(TypeError):
        node.emit("notification", {"notification": notification_obj})

    notification_events = async_capture_events(hass, "zwave_js_notification")

    # Test a valid notification with an unsupported command class
    event = Event(
        type="notification",
        data={
            "source": "node",
            "event": "notification",
            "nodeId": node.node_id,
            "ccId": 0,
            "args": {
                "commandClassName": "No Operation",
                "commandClass": 0,
                "testNodeId": 1,
                "status": 0,
                "acknowledgedFrames": 2,
            },
        },
    )
    node.receive_event(event)

    assert not notification_events
コード例 #5
0
async def test_power_level_notification(hass, hank_binary_switch, integration,
                                        client):
    """Test power level notification events."""
    # just pick a random node to fake the notification event
    node = hank_binary_switch
    events = async_capture_events(hass, "zwave_js_notification")

    event = Event(
        type="notification",
        data={
            "source": "node",
            "event": "notification",
            "nodeId": 7,
            "ccId": 115,
            "args": {
                "commandClassName": "Powerlevel",
                "commandClass": 115,
                "testNodeId": 1,
                "status": 0,
                "acknowledgedFrames": 2,
            },
        },
    )
    node.receive_event(event)
    await hass.async_block_till_done()
    assert len(events) == 1
    assert events[0].data["command_class_name"] == "Powerlevel"
    assert events[0].data["command_class"] == 115
    assert events[0].data["test_node_id"] == 1
    assert events[0].data["status"] == 0
    assert events[0].data["acknowledged_frames"] == 2
コード例 #6
0
async def test_repeat_count(hass):
    """Test repeat action w/ count option."""
    event = "test_event"
    events = async_capture_events(hass, event)
    count = 3

    sequence = cv.SCRIPT_SCHEMA(
        {
            "repeat": {
                "count": count,
                "sequence": {
                    "event": event,
                    "event_data_template": {
                        "first": "{{ repeat.first }}",
                        "index": "{{ repeat.index }}",
                        "last": "{{ repeat.last }}",
                    },
                },
            }
        }
    )
    script_obj = script.Script(hass, sequence)

    await script_obj.async_run()
    await hass.async_block_till_done()

    assert len(events) == count
    for index, event in enumerate(events):
        assert event.data.get("first") == str(index == 0)
        assert event.data.get("index") == str(index + 1)
        assert event.data.get("last") == str(index == count - 1)
コード例 #7
0
ファイル: test_script.py プロジェクト: Twtcer/core-1
async def test_condition_basic(hass, script_mode):
    """Test if we can use conditions in a script."""
    event = "test_event"
    events = async_capture_events(hass, event)
    sequence = cv.SCRIPT_SCHEMA([
        {
            "event": event
        },
        {
            "condition": "template",
            "value_template": "{{ states.test.entity.state == 'hello' }}",
        },
        {
            "event": event
        },
    ])
    script_obj = script.Script(hass, sequence, script_mode=script_mode)

    assert script_obj.can_cancel == (script_mode != "legacy")

    hass.states.async_set("test.entity", "hello")
    await script_obj.async_run()
    await hass.async_block_till_done()

    assert len(events) == 2

    hass.states.async_set("test.entity", "goodbye")

    await script_obj.async_run()
    await hass.async_block_till_done()

    assert len(events) == 3
コード例 #8
0
ファイル: test_events.py プロジェクト: 2Fake/core
async def test_camera_sound_event(hass):
    """Test a pubsub message for a camera sound event."""
    events = async_capture_events(hass, NEST_EVENT)
    subscriber = await async_setup_devices(
        hass,
        "sdm.devices.types.CAMERA",
        create_device_traits(["sdm.devices.traits.CameraSound"]),
    )
    registry = er.async_get(hass)
    entry = registry.async_get("camera.front")
    assert entry is not None

    timestamp = utcnow()
    await subscriber.async_receive_event(
        create_event("sdm.devices.events.CameraSound.Sound", timestamp=timestamp)
    )
    await hass.async_block_till_done()

    event_time = timestamp.replace(microsecond=0)
    assert len(events) == 1
    assert event_view(events[0].data) == {
        "device_id": entry.device_id,
        "type": "camera_sound",
        "timestamp": event_time,
    }
コード例 #9
0
async def test_event_register(hass: HomeAssistant, knx: KNXTestKit):
    """Test `knx.event_register` service."""
    events = async_capture_events(hass, "knx_event")
    test_address = "1/2/3"

    await knx.setup_integration({})

    # no event registered
    await knx.receive_write(test_address, True)
    await hass.async_block_till_done()
    assert len(events) == 0

    # register event
    await hass.services.async_call(
        "knx", "event_register", {"address": test_address}, blocking=True
    )
    await knx.receive_write(test_address, True)
    await knx.receive_write(test_address, False)
    await hass.async_block_till_done()
    assert len(events) == 2

    # remove event registration - no event added
    await hass.services.async_call(
        "knx",
        "event_register",
        {"address": test_address, "remove": True},
        blocking=True,
    )
    await knx.receive_write(test_address, True)
    await hass.async_block_till_done()
    assert len(events) == 2
コード例 #10
0
ファイル: test_events.py プロジェクト: jbouwh/core
async def test_doorbell_event_session_update(hass, subscriber, setup_platform):
    """Test a pubsub message with updates to an existing session."""
    events = async_capture_events(hass, NEST_EVENT)
    await setup_platform()
    registry = er.async_get(hass)
    entry = registry.async_get("camera.front")
    assert entry is not None

    # Message #1 has a motion event
    timestamp1 = utcnow()
    await subscriber.async_receive_event(
        create_events(
            {
                "sdm.devices.events.CameraMotion.Motion": {
                    "eventSessionId": EVENT_SESSION_ID,
                    "eventId": "n:1",
                },
                "sdm.devices.events.CameraClipPreview.ClipPreview": {
                    "eventSessionId": EVENT_SESSION_ID,
                    "previewUrl": "image-url-1",
                },
            },
            timestamp=timestamp1,
        )
    )

    # Message #2 has an extra person event
    timestamp2 = utcnow()
    await subscriber.async_receive_event(
        create_events(
            {
                "sdm.devices.events.CameraMotion.Motion": {
                    "eventSessionId": EVENT_SESSION_ID,
                    "eventId": "n:1",
                },
                "sdm.devices.events.CameraPerson.Person": {
                    "eventSessionId": EVENT_SESSION_ID,
                    "eventId": "n:2",
                },
                "sdm.devices.events.CameraClipPreview.ClipPreview": {
                    "eventSessionId": EVENT_SESSION_ID,
                    "previewUrl": "image-url-1",
                },
            },
            timestamp=timestamp2,
        )
    )
    await hass.async_block_till_done()

    assert len(events) == 2
    assert event_view(events[0].data) == {
        "device_id": entry.device_id,
        "type": "camera_motion",
        "timestamp": timestamp1.replace(microsecond=0),
    }
    assert event_view(events[1].data) == {
        "device_id": entry.device_id,
        "type": "camera_person",
        "timestamp": timestamp2.replace(microsecond=0),
    }
コード例 #11
0
ファイル: test_events.py プロジェクト: jbouwh/core
async def test_event_zones(hass, subscriber, setup_platform):
    """Test events published with zone information."""
    events = async_capture_events(hass, NEST_EVENT)
    await setup_platform()
    registry = er.async_get(hass)
    entry = registry.async_get("camera.front")
    assert entry is not None

    event_map = {
        "sdm.devices.events.CameraMotion.Motion": {
            "eventSessionId": EVENT_SESSION_ID,
            "eventId": EVENT_ID,
            "zones": ["Zone 1"],
        },
    }

    timestamp = utcnow()
    await subscriber.async_receive_event(create_events(event_map, timestamp=timestamp))
    await hass.async_block_till_done()

    event_time = timestamp.replace(microsecond=0)
    assert len(events) == 1
    assert event_view(events[0].data) == {
        "device_id": entry.device_id,
        "type": "camera_motion",
        "timestamp": event_time,
        "zones": ["Zone 1"],
    }
コード例 #12
0
async def test_repeat_var_in_condition(hass, condition):
    """Test repeat action w/ while option."""
    event = "test_event"
    events = async_capture_events(hass, event)

    sequence = {"repeat": {"sequence": {"event": event}}}
    if condition == "while":
        sequence["repeat"]["while"] = {
            "condition": "template",
            "value_template": "{{ repeat.index <= 2 }}",
        }
    else:
        sequence["repeat"]["until"] = {
            "condition": "template",
            "value_template": "{{ repeat.index == 2 }}",
        }
    script_obj = script.Script(hass, cv.SCRIPT_SCHEMA(sequence))

    with mock.patch(
        "homeassistant.helpers.condition._LOGGER.error",
        side_effect=AssertionError("Template Error"),
    ):
        await script_obj.async_run()

    assert len(events) == 2
コード例 #13
0
ファイル: test_events.py プロジェクト: jbouwh/core
async def test_camera_multiple_event(hass, subscriber, setup_platform):
    """Test a pubsub message for a camera person event."""
    events = async_capture_events(hass, NEST_EVENT)
    await setup_platform()
    registry = er.async_get(hass)
    entry = registry.async_get("camera.front")
    assert entry is not None

    event_map = {
        "sdm.devices.events.CameraMotion.Motion": {
            "eventSessionId": EVENT_SESSION_ID,
            "eventId": EVENT_ID,
        },
        "sdm.devices.events.CameraPerson.Person": {
            "eventSessionId": EVENT_SESSION_ID,
            "eventId": EVENT_ID,
        },
    }

    timestamp = utcnow()
    await subscriber.async_receive_event(create_events(event_map, timestamp=timestamp))
    await hass.async_block_till_done()

    event_time = timestamp.replace(microsecond=0)
    assert len(events) == 2
    assert event_view(events[0].data) == {
        "device_id": entry.device_id,
        "type": "camera_motion",
        "timestamp": event_time,
    }
    assert event_view(events[1].data) == {
        "device_id": entry.device_id,
        "type": "camera_person",
        "timestamp": event_time,
    }
コード例 #14
0
async def test_doorbell_chime_event(hass):
    """Test a pubsub message for a doorbell event."""
    events = async_capture_events(hass, NEST_EVENT)
    subscriber = await async_setup_devices(
        hass,
        "sdm.devices.types.DOORBELL",
        create_device_traits("sdm.devices.traits.DoorbellChime"),
    )

    registry = er.async_get(hass)
    entry = registry.async_get("camera.front")
    assert entry is not None
    assert entry.unique_id == "some-device-id-camera"
    assert entry.original_name == "Front"
    assert entry.domain == "camera"

    device_registry = dr.async_get(hass)
    device = device_registry.async_get(entry.device_id)
    assert device.name == "Front"
    assert device.model == "Doorbell"
    assert device.identifiers == {("nest", DEVICE_ID)}

    timestamp = utcnow()
    await subscriber.async_receive_event(
        create_event("sdm.devices.events.DoorbellChime.Chime", timestamp=timestamp)
    )
    await hass.async_block_till_done()

    event_time = timestamp.replace(microsecond=0)
    assert len(events) == 1
    assert events[0].data == {
        "device_id": entry.device_id,
        "type": "doorbell_chime",
        "timestamp": event_time,
    }
コード例 #15
0
async def test_config_local_sdk(hass, hass_client):
    """Test the local SDK."""
    command_events = async_capture_events(hass, EVENT_COMMAND_RECEIVED)
    turn_on_calls = async_mock_service(hass, "light", "turn_on")
    hass.states.async_set("light.ceiling_lights", "off")

    assert await async_setup_component(hass, "webhook", {})

    config = MockConfig(
        hass=hass,
        local_sdk_webhook_id="mock-webhook-id",
        local_sdk_user_id="mock-user-id",
    )

    client = await hass_client()

    config.async_enable_local_sdk()

    resp = await client.post(
        "/api/webhook/mock-webhook-id",
        json={
            "inputs": [
                {
                    "context": {"locale_country": "US", "locale_language": "en"},
                    "intent": "action.devices.EXECUTE",
                    "payload": {
                        "commands": [
                            {
                                "devices": [{"id": "light.ceiling_lights"}],
                                "execution": [
                                    {
                                        "command": "action.devices.commands.OnOff",
                                        "params": {"on": True},
                                    }
                                ],
                            }
                        ],
                        "structureData": {},
                    },
                }
            ],
            "requestId": "mock-req-id",
        },
    )
    assert resp.status == 200
    result = await resp.json()
    assert result["requestId"] == "mock-req-id"

    assert len(command_events) == 1
    assert command_events[0].context.user_id == config.local_sdk_user_id

    assert len(turn_on_calls) == 1
    assert turn_on_calls[0].context is command_events[0].context

    config.async_disable_local_sdk()

    # Webhook is no longer active
    resp = await client.post("/api/webhook/mock-webhook-id")
    assert resp.status == 200
    assert await resp.read() == b""
コード例 #16
0
async def test_camera_person_event(hass):
    """Test a pubsub message for a camera person event."""
    events = async_capture_events(hass, NEST_EVENT)
    subscriber = await async_setup_devices(
        hass,
        "sdm.devices.types.DOORBELL",
        create_device_traits("sdm.devices.traits.CameraEventImage"),
    )
    registry = await hass.helpers.entity_registry.async_get_registry()
    entry = registry.async_get("camera.front")
    assert entry is not None

    timestamp = utcnow()
    await subscriber.async_receive_event(
        create_event("sdm.devices.events.CameraPerson.Person",
                     timestamp=timestamp))
    await hass.async_block_till_done()

    event_time = timestamp.replace(microsecond=0)
    assert len(events) == 1
    assert events[0].data == {
        "device_id": entry.device_id,
        "type": "camera_person",
        "timestamp": event_time,
    }
コード例 #17
0
async def test_cover_remote(hass, zha_device_joined_restored,
                            zigpy_cover_remote):
    """Test zha cover remote."""

    # load up cover domain
    await zha_device_joined_restored(zigpy_cover_remote)

    cluster = zigpy_cover_remote.endpoints[1].out_clusters[
        closures.WindowCovering.cluster_id]
    zha_events = async_capture_events(hass, "zha_event")

    # up command
    hdr = make_zcl_header(0, global_command=False)
    cluster.handle_message(hdr, [])
    await hass.async_block_till_done()

    assert len(zha_events) == 1
    assert zha_events[0].data[ATTR_COMMAND] == "up_open"

    # down command
    hdr = make_zcl_header(1, global_command=False)
    cluster.handle_message(hdr, [])
    await hass.async_block_till_done()

    assert len(zha_events) == 2
    assert zha_events[1].data[ATTR_COMMAND] == "down_close"
コード例 #18
0
ファイル: test_script.py プロジェクト: Twtcer/core-1
async def test_delay_template_complex_invalid(hass, caplog, script_mode):
    """Test the delay with a complex template that fails."""
    event = "test_event"
    events = async_capture_events(hass, event)
    sequence = cv.SCRIPT_SCHEMA([
        {
            "event": event
        },
        {
            "delay": {
                "seconds": "{{ invalid_delay }}"
            }
        },
        {
            "delay": {
                "seconds": 5
            }
        },
        {
            "event": event
        },
    ])
    script_obj = script.Script(hass, sequence, script_mode=script_mode)
    start_idx = len(caplog.records)

    await script_obj.async_run()
    await hass.async_block_till_done()

    assert any(rec.levelname == "ERROR" and "Error rendering" in rec.message
               for rec in caplog.records[start_idx:])

    assert not script_obj.is_running
    assert len(events) == 1
コード例 #19
0
ファイル: test_script.py プロジェクト: Twtcer/core-1
async def test_cancel_delay(hass, script_mode):
    """Test the cancelling while the delay is present."""
    event = "test_event"
    events = async_capture_events(hass, event)
    sequence = cv.SCRIPT_SCHEMA([{"delay": {"seconds": 5}}, {"event": event}])
    script_obj = script.Script(hass, sequence, script_mode=script_mode)
    delay_started_flag = async_watch_for_action(script_obj, "delay")

    try:
        hass.async_create_task(script_obj.async_run())
        await asyncio.wait_for(delay_started_flag.wait(), 1)

        assert script_obj.is_running
        assert len(events) == 0
    except (AssertionError, asyncio.TimeoutError):
        await script_obj.async_stop()
        raise
    else:
        await script_obj.async_stop()

        assert not script_obj.is_running

        # Make sure the script is really stopped.

        async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=5))
        await hass.async_block_till_done()

        assert not script_obj.is_running
        assert len(events) == 0
コード例 #20
0
ファイル: test_script.py プロジェクト: Twtcer/core-1
async def test_firing_event_template(hass, script_mode):
    """Test the firing of events."""
    event = "test_event"
    context = Context()
    events = async_capture_events(hass, event)

    sequence = cv.SCRIPT_SCHEMA({
        "event": event,
        "event_data_template": {
            "dict": {
                1: "{{ is_world }}",
                2: "{{ is_world }}{{ is_world }}",
                3: "{{ is_world }}{{ is_world }}{{ is_world }}",
            },
            "list": ["{{ is_world }}", "{{ is_world }}{{ is_world }}"],
        },
    })
    script_obj = script.Script(hass, sequence, script_mode=script_mode)

    assert script_obj.can_cancel == (script_mode != "legacy")

    await script_obj.async_run({"is_world": "yes"}, context=context)
    await hass.async_block_till_done()

    assert len(events) == 1
    assert events[0].context is context
    assert events[0].data == {
        "dict": {
            1: "yes",
            2: "yesyes",
            3: "yesyesyes"
        },
        "list": ["yes", "yesyes"],
    }
コード例 #21
0
ファイル: test_init.py プロジェクト: jbouwh/core
async def test_watchdog(
    hass,
    create_hdmi_network,
    mock_cec_adapter,
    adapter_initialized_value,
    watchdog_actions,
):
    """Test the watchdog when adapter is down/up."""
    adapter_initialized = PropertyMock(return_value=adapter_initialized_value)
    events = async_capture_events(hass, EVENT_HDMI_CEC_UNAVAILABLE)

    mock_cec_adapter_instance = mock_cec_adapter.return_value
    type(mock_cec_adapter_instance).initialized = adapter_initialized

    mock_hdmi_network_instance = await create_hdmi_network()

    mock_hdmi_network_instance.set_initialized_callback.assert_called_once()
    callback = mock_hdmi_network_instance.set_initialized_callback.call_args.args[0]
    callback()

    async_fire_time_changed(hass, utcnow() + timedelta(seconds=WATCHDOG_INTERVAL))
    await hass.async_block_till_done()

    adapter_initialized.assert_called_once_with()
    assert len(events) == watchdog_actions
    assert mock_cec_adapter_instance.init.call_count == watchdog_actions
コード例 #22
0
async def test_choose(hass, var, result):
    """Test choose action."""
    event = "test_event"
    events = async_capture_events(hass, event)
    sequence = cv.SCRIPT_SCHEMA(
        {
            "choose": [
                {
                    "conditions": {
                        "condition": "template",
                        "value_template": "{{ var == 1 }}",
                    },
                    "sequence": {"event": event, "event_data": {"choice": "first"}},
                },
                {
                    "conditions": {
                        "condition": "template",
                        "value_template": "{{ var == 2 }}",
                    },
                    "sequence": {"event": event, "event_data": {"choice": "second"}},
                },
            ],
            "default": {"event": event, "event_data": {"choice": "default"}},
        }
    )
    script_obj = script.Script(hass, sequence)

    await script_obj.async_run(MappingProxyType({"var": var}))
    await hass.async_block_till_done()

    assert len(events) == 1
    assert events[0].data["choice"] == result
コード例 #23
0
async def test_poll_control_cluster_command(hass, poll_control_device):
    """Test poll control channel response to cluster command."""
    checkin_mock = AsyncMock()
    poll_control_ch = poll_control_device.channels.pools[0].all_channels[
        "1:0x0020"]
    cluster = poll_control_ch.cluster
    events = async_capture_events(hass, "zha_event")

    with mock.patch.object(poll_control_ch, "check_in_response", checkin_mock):
        tsn = 22
        hdr = make_zcl_header(0, global_command=False, tsn=tsn)
        assert not events
        cluster.handle_message(
            hdr,
            [mock.sentinel.args, mock.sentinel.args2, mock.sentinel.args3])
        await hass.async_block_till_done()

    assert checkin_mock.call_count == 1
    assert checkin_mock.await_count == 1
    assert checkin_mock.await_args[0][0] == tsn
    assert len(events) == 1
    data = events[0].data
    assert data["command"] == "checkin"
    assert data["args"][0] is mock.sentinel.args
    assert data["args"][1] is mock.sentinel.args2
    assert data["args"][2] is mock.sentinel.args3
    assert data["unique_id"] == "00:11:22:33:44:55:66:77:1:0x0020"
    assert data["device_id"] == poll_control_device.device_id
コード例 #24
0
ファイル: test_events.py プロジェクト: rikroe/core
async def test_structure_update_event(hass):
    """Test a pubsub message for a new device being added."""
    events = async_capture_events(hass, NEST_EVENT)
    subscriber = await async_setup_devices(
        hass,
        "sdm.devices.types.DOORBELL",
        create_device_traits(["sdm.devices.traits.DoorbellChime"]),
    )

    # Entity for first device is registered
    registry = er.async_get(hass)
    assert registry.async_get("camera.front")

    new_device = Device.MakeDevice(
        {
            "name": "device-id-2",
            "type": "sdm.devices.types.CAMERA",
            "traits": {
                "sdm.devices.traits.Info": {
                    "customName": "Back",
                },
                "sdm.devices.traits.CameraLiveStream": {},
            },
        },
        auth=None,
    )
    device_manager = await subscriber.async_get_device_manager()
    device_manager.add_device(new_device)

    # Entity for new devie has not yet been loaded
    assert not registry.async_get("camera.back")

    # Send a message that triggers the device to be loaded
    message = EventMessage(
        {
            "eventId": "some-event-id",
            "timestamp": utcnow().isoformat(timespec="seconds"),
            "relationUpdate": {
                "type": "CREATED",
                "subject": "enterprise/example/foo",
                "object": "enterprise/example/devices/some-device-id2",
            },
        },
        auth=None,
    )
    with patch(
        "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation"
    ), patch("homeassistant.components.nest.PLATFORMS", [PLATFORM]), patch(
        "homeassistant.components.nest.api.GoogleNestSubscriber",
        return_value=subscriber,
    ):
        await subscriber.async_receive_event(message)
        await hass.async_block_till_done()

    # No home assistant events published
    assert not events

    assert registry.async_get("camera.front")
    # Currently need a manual reload to detect the new entity
    assert not registry.async_get("camera.back")
コード例 #25
0
async def test_hue_event(hass, mock_bridge_v2, v2_resources_test_data):
    """Test hue button events."""
    await mock_bridge_v2.api.load_test_data(v2_resources_test_data)
    await setup_platform(hass, mock_bridge_v2, ["binary_sensor", "sensor"])
    await async_setup_devices(mock_bridge_v2)
    await async_setup_hue_events(mock_bridge_v2)

    events = async_capture_events(hass, "hue_event")

    # Emit button update event
    btn_event = {
        "button": {
            "last_event": "initial_press"
        },
        "id": "c658d3d8-a013-4b81-8ac6-78b248537e70",
        "metadata": {
            "control_id": 1
        },
        "type": "button",
    }
    mock_bridge_v2.api.emit_event("update", btn_event)

    # wait for the event
    await hass.async_block_till_done()
    await hass.async_block_till_done()
    assert len(events) == 1
    assert events[0].data["id"] == "wall_switch_with_2_controls_button"
    assert events[0].data["unique_id"] == btn_event["id"]
    assert events[0].data["type"] == btn_event["button"]["last_event"]
    assert events[0].data["subtype"] == btn_event["metadata"]["control_id"]
コード例 #26
0
async def test_notifications(hass, hank_binary_switch, integration, client):
    """Test notification events."""
    # just pick a random node to fake the value notification events
    node = hank_binary_switch
    events = async_capture_events(hass, "zwave_js_event")

    # Publish fake Basic Set value notification
    event = Event(
        type="notification",
        data={
            "source": "node",
            "event": "notification",
            "nodeId": 23,
            "notificationLabel": "Keypad lock operation",
            "parameters": {
                "userId": 1
            },
        },
    )
    node.receive_event(event)
    # wait for the event
    await hass.async_block_till_done()
    assert len(events) == 1
    assert events[0].data["type"] == "notification"
    assert events[0].data["home_id"] == client.driver.controller.home_id
    assert events[0].data["node_id"] == 32
    assert events[0].data["label"] == "Keypad lock operation"
    assert events[0].data["parameters"]["userId"] == 1
コード例 #27
0
async def test_get_panels(hass, hass_ws_client, mock_http_client):
    """Test get_panels command."""
    events = async_capture_events(hass, EVENT_PANELS_UPDATED)

    resp = await mock_http_client.get("/map")
    assert resp.status == HTTP_NOT_FOUND

    hass.components.frontend.async_register_built_in_panel(
        "map", "Map", "mdi:tooltip-account", require_admin=True)

    resp = await mock_http_client.get("/map")
    assert resp.status == 200

    assert len(events) == 1

    client = await hass_ws_client(hass)
    await client.send_json({"id": 5, "type": "get_panels"})

    msg = await client.receive_json()

    assert msg["id"] == 5
    assert msg["type"] == TYPE_RESULT
    assert msg["success"]
    assert msg["result"]["map"]["component_name"] == "map"
    assert msg["result"]["map"]["url_path"] == "map"
    assert msg["result"]["map"]["icon"] == "mdi:tooltip-account"
    assert msg["result"]["map"]["title"] == "Map"
    assert msg["result"]["map"]["require_admin"] is True

    hass.components.frontend.async_remove_panel("map")

    resp = await mock_http_client.get("/map")
    assert resp.status == HTTP_NOT_FOUND

    assert len(events) == 2
コード例 #28
0
ファイル: test_events.py プロジェクト: jbouwh/core
async def test_event(
    hass, auth, setup_platform, subscriber, event_trait, expected_model, expected_type
):
    """Test a pubsub message for a doorbell event."""
    events = async_capture_events(hass, NEST_EVENT)
    await setup_platform()

    registry = er.async_get(hass)
    entry = registry.async_get("camera.front")
    assert entry is not None
    assert entry.unique_id == "some-device-id-camera"
    assert entry.domain == "camera"

    device_registry = dr.async_get(hass)
    device = device_registry.async_get(entry.device_id)
    assert device.name == "Front"
    assert device.model == expected_model
    assert device.identifiers == {("nest", DEVICE_ID)}

    timestamp = utcnow()
    await subscriber.async_receive_event(create_event(event_trait, timestamp=timestamp))
    await hass.async_block_till_done()

    event_time = timestamp.replace(microsecond=0)
    assert len(events) == 1
    assert event_view(events[0].data) == {
        "device_id": entry.device_id,
        "type": expected_type,
        "timestamp": event_time,
    }
コード例 #29
0
async def test_webhook_person_event(hass, config_entry, netatmo_auth):
    """Test that person events are handled."""
    with selected_platforms(["camera"]):
        await hass.config_entries.async_setup(config_entry.entry_id)

        await hass.async_block_till_done()

    test_netatmo_event = async_capture_events(hass, NETATMO_EVENT)
    assert not test_netatmo_event

    fake_webhook_event = {
        "persons": [
            {
                "id": "91827374-7e04-5298-83ad-a0cb8372dff1",
                "face_id": "a1b2c3d4e5",
                "face_key": "9876543",
                "is_known": True,
                "face_url": "https://netatmocameraimage.blob.core.windows.net/production/12345",
            }
        ],
        "snapshot_id": "123456789abc",
        "snapshot_key": "foobar123",
        "snapshot_url": "https://netatmocameraimage.blob.core.windows.net/production/12346",
        "event_type": "person",
        "camera_id": "12:34:56:00:f1:62",
        "device_id": "12:34:56:00:f1:62",
        "event_id": "1234567890",
        "message": "MYHOME: John Doe has been seen by Indoor Camera ",
        "push_type": "NACamera-person",
    }

    webhook_id = config_entry.data[CONF_WEBHOOK_ID]
    await simulate_webhook(hass, webhook_id, fake_webhook_event)

    assert test_netatmo_event
コード例 #30
0
async def test_repeat_conditional(hass, condition):
    """Test repeat action w/ while option."""
    event = "test_event"
    events = async_capture_events(hass, event)
    count = 3

    sequence = {
        "repeat": {
            "sequence": [
                {
                    "event": event,
                    "event_data_template": {
                        "first": "{{ repeat.first }}",
                        "index": "{{ repeat.index }}",
                    },
                },
                {"wait_template": "{{ is_state('sensor.test', 'next') }}"},
                {"wait_template": "{{ not is_state('sensor.test', 'next') }}"},
            ],
        }
    }
    if condition == "while":
        sequence["repeat"]["while"] = {
            "condition": "template",
            "value_template": "{{ not is_state('sensor.test', 'done') }}",
        }
    else:
        sequence["repeat"]["until"] = {
            "condition": "template",
            "value_template": "{{ is_state('sensor.test', 'done') }}",
        }
    script_obj = script.Script(hass, cv.SCRIPT_SCHEMA(sequence))

    wait_started = async_watch_for_action(script_obj, "wait")
    hass.states.async_set("sensor.test", "1")

    hass.async_create_task(script_obj.async_run())
    try:
        for index in range(2, count + 1):
            await asyncio.wait_for(wait_started.wait(), 1)
            wait_started.clear()
            hass.states.async_set("sensor.test", "next")
            await asyncio.wait_for(wait_started.wait(), 1)
            wait_started.clear()
            hass.states.async_set("sensor.test", index)
        await asyncio.wait_for(wait_started.wait(), 1)
        hass.states.async_set("sensor.test", "next")
        await asyncio.wait_for(wait_started.wait(), 1)
        wait_started.clear()
        hass.states.async_set("sensor.test", "done")
        await asyncio.wait_for(hass.async_block_till_done(), 1)
    except asyncio.TimeoutError:
        await script_obj.async_stop()
        raise

    assert len(events) == count
    for index, event in enumerate(events):
        assert event.data.get("first") == str(index == 0)
        assert event.data.get("index") == str(index + 1)