Exemplo n.º 1
0
def test_rx_device_annce(app, ieee, nwk):
    dst_ep = 0
    cluster_id = ZDOCmd.Device_annce
    device = mock.MagicMock()
    device.status = device.Status.NEW
    app.get_device = mock.MagicMock(return_value=device)
    app.handle_join = mock.MagicMock()
    app.handle_message = mock.MagicMock()

    data = t.uint8_t(0xAA).serialize()
    data += nwk.serialize()
    data += ieee.serialize()
    data += t.uint8_t(0x8E).serialize()

    app.handle_rx(
        ieee,
        nwk,
        mock.sentinel.src_ep,
        dst_ep,
        cluster_id,
        mock.sentinel.profile_id,
        mock.sentinel.rx_opt,
        data,
    )

    assert app.handle_message.call_count == 1
    assert app.handle_join.call_count == 1
    assert app.handle_join.call_args[0][0] == nwk
    assert app.handle_join.call_args[0][1] == ieee
    assert app.handle_join.call_args[0][2] == 0
Exemplo n.º 2
0
async def test_setup_adds_proper_devices(hass):
    """Test if setup adds devices."""
    with mock.patch("homeassistant.components.mfi.switch.MFiClient"
                    ) as mock_client, mock.patch(
                        "homeassistant.components.mfi.switch.MfiSwitch",
                        side_effect=mfi.MfiSwitch) as mock_switch:
        ports = {
            i: mock.MagicMock(model=model,
                              label=f"Port {i}",
                              output=False,
                              data={},
                              ident=f"abcd-{i}")
            for i, model in enumerate(mfi.SWITCH_MODELS)
        }
        ports["bad"] = mock.MagicMock(model="notaswitch")
        print(ports["bad"].model)
        mock_client.return_value.get_devices.return_value = [
            mock.MagicMock(ports=ports)
        ]
        assert await async_setup_component(hass, COMPONENT.DOMAIN, GOOD_CONFIG)
        await hass.async_block_till_done()
        for ident, port in ports.items():
            if ident != "bad":
                mock_switch.assert_any_call(port)
        assert mock.call(ports["bad"], hass) not in mock_switch.mock_calls
Exemplo n.º 3
0
def mock_client_fixture():
    """Mock the prometheus client."""
    with mock.patch(f"{PROMETHEUS_PATH}.prometheus_client") as client:
        counter_client = mock.MagicMock()
        client.Counter = mock.MagicMock(return_value=counter_client)
        setattr(counter_client, "labels", mock.MagicMock(return_value=mock.MagicMock()))
        yield counter_client
Exemplo n.º 4
0
async def _test_remote_at_command(api, monkeypatch, do_reply=True):
    monkeypatch.setattr(t, "serialize",
                        mock.MagicMock(return_value=mock.sentinel.serialize))

    def mock_command(name, *args):
        rsp = xbee_api.COMMAND_REQUESTS[name][2]
        ret = None
        if rsp:
            ret = asyncio.Future()
            if do_reply:
                ret.set_result(mock.sentinel.at_result)
        return ret

    api._command = mock.MagicMock(side_effect=mock_command)
    api._seq = mock.sentinel.seq

    for at_cmd in xbee_api.AT_COMMANDS:
        res = await api._remote_at_command(
            mock.sentinel.ieee,
            mock.sentinel.nwk,
            mock.sentinel.opts,
            at_cmd,
            mock.sentinel.args,
        )
        assert t.serialize.call_count == 1
        assert api._command.call_count == 1
        assert api._command.call_args[0][0] == "remote_at"
        assert api._command.call_args[0][1] == mock.sentinel.ieee
        assert api._command.call_args[0][2] == mock.sentinel.nwk
        assert api._command.call_args[0][3] == mock.sentinel.opts
        assert api._command.call_args[0][4] == at_cmd.encode("ascii")
        assert api._command.call_args[0][5] == mock.sentinel.serialize
        assert res == mock.sentinel.at_result
        t.serialize.reset_mock()
        api._command.reset_mock()
Exemplo n.º 5
0
def _device_join(app, dev, data):
    app.handle_message = mock.MagicMock()
    app.handle_join = mock.MagicMock()

    dst_ep = 0
    cluster_id = 0x0013

    _test_rx(app, dev, dev.nwk, dst_ep, cluster_id, data)
    assert app.handle_join.call_count == 1
    assert app.handle_message.call_count == 1
Exemplo n.º 6
0
def mock_client_fixture():
    """Mock the pubsub client."""
    with mock.patch(f"{GOOGLE_PUBSUB_PATH}.pubsub_v1") as client:
        client.PublisherClient = mock.MagicMock()
        setattr(
            client.PublisherClient,
            "from_service_account_json",
            mock.MagicMock(return_value=mock.MagicMock()),
        )
        yield client
Exemplo n.º 7
0
def make_event(entity_id):
    """Make a mock event for test."""
    domain = split_entity_id(entity_id)[0]
    state = mock.MagicMock(
        state="not blank",
        domain=domain,
        entity_id=entity_id,
        object_id="entity",
        attributes={},
    )
    return mock.MagicMock(data={"new_state": state}, time_fired=12345)
Exemplo n.º 8
0
def test_rx(app):
    device = mock.MagicMock()
    app.handle_message = mock.MagicMock()
    _test_rx(app, device, mock.sentinel.src_nwk, data=mock.sentinel.message)
    assert app.handle_message.call_count == 1
    assert app.handle_message.call_args == ((
        device,
        mock.sentinel.profile_id,
        mock.sentinel.cluster_id,
        mock.sentinel.src_ep,
        mock.sentinel.dst_ep,
        mock.sentinel.message,
    ), )
 def test_setup_adds_proper_devices(self, mock_sensor, mock_client):
     """Test if setup adds devices."""
     ports = {
         i: mock.MagicMock(model=model) for i, model in enumerate(mfi.SENSOR_MODELS)
     }
     ports["bad"] = mock.MagicMock(model="notasensor")
     mock_client.return_value.get_devices.return_value = [
         mock.MagicMock(ports=ports)
     ]
     assert setup_component(self.hass, sensor.DOMAIN, self.GOOD_CONFIG)
     for ident, port in ports.items():
         if ident != "bad":
             mock_sensor.assert_any_call(port, self.hass)
     assert mock.call(ports["bad"], self.hass) not in mock_sensor.mock_calls
Exemplo n.º 10
0
async def test_init_api_mode(api, monkeypatch):
    monkeypatch.setattr(api._uart, "baudrate", 57600)
    api.enter_at_command_mode = mock.AsyncMock(return_value=True)

    res = await api.init_api_mode()
    assert res is None
    assert api.enter_at_command_mode.call_count == 1

    api.enter_at_command_mode = mock.AsyncMock(return_value=False)

    res = await api.init_api_mode()
    assert res is False
    assert api.enter_at_command_mode.call_count == 10

    async def enter_at_mode():
        if api._uart.baudrate == 9600:
            return True
        return False

    api._uart.baudrate = 57600
    api.enter_at_command_mode = mock.MagicMock(side_effect=enter_at_mode)
    api.api_mode_at_commands = mock.AsyncMock(return_value=True)

    res = await api.init_api_mode()
    assert res is True
    assert api.enter_at_command_mode.call_count == 5
Exemplo n.º 11
0
async def test_command_mode_at_cmd_timeout(api):
    command = "+++"

    api._uart.command_mode_send = mock.MagicMock()

    result = await api.command_mode_at_cmd(command)
    assert result is None
Exemplo n.º 12
0
def test_handle_explicit_rx_indicator(api):
    s = mock.sentinel
    data = [
        s.src_ieee,
        s.src_nwk,
        s.src_ep,
        s.dst_ep,
        s.cluster_id,
        s.profile,
        s.opts,
        b"abcdef",
    ]
    api._app = mock.MagicMock()
    api._app.handle_rx = mock.MagicMock()
    api._handle_explicit_rx_indicator(*data)
    assert api._app.handle_rx.call_count == 1
Exemplo n.º 13
0
def test_remote_at_cmd(app, device):
    dev = device()
    app.get_device = mock.MagicMock(return_value=dev)
    app._api = mock.MagicMock(spec=XBee)
    s = mock.sentinel
    app.remote_at_command(s.nwk,
                          s.cmd,
                          s.data,
                          apply_changes=True,
                          encryption=True)
    assert app._api._remote_at_command.call_count == 1
    assert app._api._remote_at_command.call_args[0][0] is dev.ieee
    assert app._api._remote_at_command.call_args[0][1] == s.nwk
    assert app._api._remote_at_command.call_args[0][2] == 0x12
    assert app._api._remote_at_command.call_args[0][3] == s.cmd
    assert app._api._remote_at_command.call_args[0][4] == s.data
Exemplo n.º 14
0
def test_rx_nwk_0000(app):
    app._handle_reply = mock.MagicMock()
    app.handle_message = mock.MagicMock()
    app.get_device = mock.MagicMock()
    app.handle_rx(
        b"\x01\x02\x03\x04\x05\x06\x07\x08",
        0x0000,
        mock.sentinel.src_ep,
        mock.sentinel.dst_ep,
        mock.sentinel.cluster_id,
        mock.sentinel.profile_id,
        mock.sentinel.rxopts,
        b"",
    )
    assert app.handle_message.call_count == 1
    assert app.get_device.call_count == 2
Exemplo n.º 15
0
 def test_setup_adds_proper_devices(self, mock_switch, mock_client):
     """Test if setup adds devices."""
     ports = {
         i: mock.MagicMock(model=model)
         for i, model in enumerate(mfi.SWITCH_MODELS)
     }
     ports["bad"] = mock.MagicMock(model="notaswitch")
     print(ports["bad"].model)
     mock_client.return_value.get_devices.return_value = [
         mock.MagicMock(ports=ports)
     ]
     assert setup_component(self.hass, switch.DOMAIN, self.GOOD_CONFIG)
     self.hass.block_till_done()
     for ident, port in ports.items():
         if ident != "bad":
             mock_switch.assert_any_call(port)
     assert mock.call(ports["bad"], self.hass) not in mock_switch.mock_calls
Exemplo n.º 16
0
def light_mock(hass, brightness):
    """Mock light."""
    controller_mock = mock.MagicMock()
    dev_dict = {
        "address": "a1",
        "name": "fake_light",
        "brightness_levels": brightness
    }
    return mochad.MochadLight(hass, controller_mock, dev_dict)
Exemplo n.º 17
0
def test_frame_received_no_handler(api, monkeypatch):
    monkeypatch.setattr(
        t, "deserialize",
        mock.MagicMock(return_value=(b"deserialized data", b"")))
    my_handler = mock.MagicMock()
    cmd = "no_handler"
    cmd_id = 0x00
    xbee_api.COMMAND_RESPONSES[cmd] = (cmd_id, (), None)
    api._commands_by_id[cmd_id] = cmd

    cmd_opts = xbee_api.COMMAND_RESPONSES[cmd]
    cmd_id = cmd_opts[0]
    payload = b"\x01\x02\x03\x04"
    data = cmd_id.to_bytes(1, "big") + payload
    api.frame_received(data)
    assert t.deserialize.call_count == 1
    assert t.deserialize.call_args[0][0] == payload
    assert my_handler.call_count == 0
Exemplo n.º 18
0
def test_rx_unknown_device_ieee(app):
    """Unknown NWK, and unknown IEEE."""
    app.handle_message = mock.MagicMock()
    app.handle_join = mock.MagicMock()
    app.get_device = mock.MagicMock(side_effect=KeyError)
    app.handle_rx(
        b"\xff\xff\xff\xff\xff\xff\xff\xff",
        0x3334,
        mock.sentinel.src_ep,
        mock.sentinel.dst_ep,
        mock.sentinel.cluster_id,
        mock.sentinel.profile_id,
        mock.sentinel.rxopts,
        b"",
    )
    assert app.handle_join.call_count == 0
    assert app.get_device.call_count == 2
    assert app.handle_message.call_count == 0
Exemplo n.º 19
0
def test_handle_remote_at_rsp(api):
    api._handle_at_response = mock.MagicMock()
    s = mock.sentinel
    api._handle_remote_at_response(s.frame_id, s.ieee, s.nwk, s.cmd, s.status,
                                   s.data)
    assert api._handle_at_response.call_count == 1
    assert api._handle_at_response.call_args[0][0] == s.frame_id
    assert api._handle_at_response.call_args[0][1] == s.cmd
    assert api._handle_at_response.call_args[0][2] == s.status
    assert api._handle_at_response.call_args[0][3] == s.data
Exemplo n.º 20
0
 def setUp(self):
     """Set up things to be run when tests are started."""
     self.hass = get_test_home_assistant()
     controller_mock = mock.MagicMock()
     dev_dict = {
         "address": "a1",
         "name": "fake_light",
         "brightness_levels": 256
     }
     self.light = mochad.MochadLight(self.hass, controller_mock, dev_dict)
Exemplo n.º 21
0
async def test_form_network(app):
    legacy_module = False

    async def mock_at_command(cmd, *args):
        if cmd == "MY":
            return 0x0000
        elif cmd == "WR":
            app._api.coordinator_started_event.set()
        elif cmd == "CE" and legacy_module:
            raise RuntimeError
        return None

    app._api._at_command = mock.MagicMock(spec=XBee._at_command,
                                          side_effect=mock_at_command)
    app._api._queued_at = mock.MagicMock(spec=XBee._at_command,
                                         side_effect=mock_at_command)
    app._get_association_state = mock.AsyncMock(
        spec=application.ControllerApplication._get_association_state,
        return_value=0x00,
    )

    app.write_network_info = mock.MagicMock(wraps=app.write_network_info)

    await app.form_network()
    assert app._api._at_command.call_count >= 1
    assert app._api._queued_at.call_count >= 7

    network_info = app.write_network_info.mock_calls[0][2]["network_info"]

    app._api._queued_at.assert_any_call("SC", 1 << (network_info.channel - 11))
    app._api._queued_at.assert_any_call("KY", b"ZigBeeAlliance09")

    app._api._at_command.reset_mock()
    app._api._queued_at.reset_mock()
    legacy_module = True
    await app.form_network()
    assert app._api._at_command.call_count >= 1
    assert app._api._queued_at.call_count >= 7

    network_info = app.write_network_info.mock_calls[0][2]["network_info"]

    app._api._queued_at.assert_any_call("SC", 1 << (network_info.channel - 11))
    app._api._queued_at.assert_any_call("KY", b"ZigBeeAlliance09")
Exemplo n.º 22
0
def test_handle_tx_status_duplicate(api):
    status = t.TXStatus.SUCCESS
    frame_id = 0x12
    send_fut = mock.MagicMock(spec=asyncio.Future)
    send_fut.set_result.side_effect = asyncio.InvalidStateError
    api._awaiting[frame_id] = (send_fut, )
    s = mock.sentinel
    api._handle_tx_status(frame_id, s.dst_nwk, s.retries, status, s.disc)
    assert len(api._awaiting) == 0
    assert send_fut.set_result.call_count == 1
    assert send_fut.set_exception.call_count == 0
Exemplo n.º 23
0
def _handle_tx_status(api, status, wrong_frame_id=False):
    status = t.TXStatus(status)
    frame_id = 0x12
    send_fut = mock.MagicMock(spec=asyncio.Future)
    api._awaiting[frame_id] = (send_fut, )
    s = mock.sentinel
    if wrong_frame_id:
        frame_id += 1
    api._handle_tx_status(frame_id, s.dst_nwk, s.retries, status,
                          t.DiscoveryStatus())
    return send_fut
Exemplo n.º 24
0
async def test_setup_adds_proper_devices(hass):
    """Test if setup adds devices."""
    with mock.patch(
        "homeassistant.components.mfi.sensor.MFiClient"
    ) as mock_client, mock.patch(
        "homeassistant.components.mfi.sensor.MfiSensor", side_effect=mfi.MfiSensor
    ) as mock_sensor:
        ports = {
            i: mock.MagicMock(model=model) for i, model in enumerate(mfi.SENSOR_MODELS)
        }
        ports["bad"] = mock.MagicMock(model="notasensor")
        mock_client.return_value.get_devices.return_value = [
            mock.MagicMock(ports=ports)
        ]
        assert await async_setup_component(hass, COMPONENT.DOMAIN, GOOD_CONFIG)
        await hass.async_block_till_done()
        for ident, port in ports.items():
            if ident != "bad":
                mock_sensor.assert_any_call(port, hass)
        assert mock.call(ports["bad"], hass) not in mock_sensor.mock_calls
Exemplo n.º 25
0
async def _test_start_network(
    app,
    ai_status=0xFF,
    api_mode=True,
    api_config_succeeds=True,
    ee=1,
    eo=2,
    zs=2,
    legacy_module=False,
):
    ai_tries = 5
    app.state.node_info.nwk = mock.sentinel.nwk

    def _at_command_mock(cmd, *args):
        nonlocal ai_tries
        if not api_mode:
            raise asyncio.TimeoutError
        if cmd == "CE" and legacy_module:
            raise RuntimeError

        ai_tries -= 1 if cmd == "AI" else 0
        return {
            "AI": ai_status if ai_tries < 0 else 0xFF,
            "CE": 1 if ai_status == 0 else 0,
            "EO": eo,
            "EE": ee,
            "ID": 0x25DCF87E03EA5906,
            "MY": 0xFFFE if ai_status else 0x0000,
            "NJ": mock.sentinel.at_nj,
            "OI": 0xDD94,
            "OP": mock.sentinel.at_op,
            "SH": 0x08070605,
            "SL": 0x04030201,
            "ZS": zs,
        }.get(cmd, None)

    def init_api_mode_mock():
        nonlocal api_mode
        api_mode = api_config_succeeds
        return api_config_succeeds

    with mock.patch("zigpy_xbee.api.XBee") as XBee_mock:
        api_mock = mock.MagicMock()
        api_mock._at_command = mock.AsyncMock(side_effect=_at_command_mock)
        api_mock.init_api_mode = mock.AsyncMock(side_effect=init_api_mode_mock)

        XBee_mock.new = mock.AsyncMock(return_value=api_mock)

        await app.connect()

    app.form_network = mock.AsyncMock()
    await app.load_network_info()
    await app.start_network()
    return app
Exemplo n.º 26
0
def test_rx_unknown_device(app, device):
    """Unknown NWK, but existing device."""
    app.handle_message = mock.MagicMock()
    app.handle_join = mock.MagicMock()
    dev = device(nwk=0x1234)
    app.devices[dev.ieee] = dev

    num_before_rx = len(app.devices)
    app.handle_rx(
        b"\x08\x07\x06\x05\x04\x03\x02\x01",
        0x3334,
        mock.sentinel.src_ep,
        mock.sentinel.dst_ep,
        mock.sentinel.cluster_id,
        mock.sentinel.profile_id,
        mock.sentinel.rxopts,
        b"",
    )
    assert app.handle_join.call_count == 1
    assert app.handle_message.call_count == 1
    assert len(app.devices) == num_before_rx
Exemplo n.º 27
0
async def test_command_not_connected(api):
    api._uart = None

    def mock_api_frame(name, *args):
        return mock.sentinel.api_frame_data, api._seq

    api._api_frame = mock.MagicMock(side_effect=mock_api_frame)

    for cmd, cmd_opts in xbee_api.COMMAND_REQUESTS.items():
        with pytest.raises(zigpy.exceptions.APIException):
            await api._command(cmd, mock.sentinel.cmd_data)
        assert api._api_frame.call_count == 0
        api._api_frame.reset_mock()
Exemplo n.º 28
0
async def _test_request(app,
                        expect_reply=True,
                        send_success=True,
                        send_timeout=False,
                        is_end_device=True,
                        node_desc=True,
                        **kwargs):
    seq = 123
    nwk = 0x2345
    ieee = t.EUI64(b"\x01\x02\x03\x04\x05\x06\x07\x08")
    dev = app.add_device(ieee, nwk)

    if node_desc:
        dev.node_desc = mock.MagicMock()
        dev.node_desc.is_end_device = is_end_device
    else:
        dev.node_desc = None

    def _mock_command(cmdname, ieee, nwk, src_ep, dst_ep, cluster, profile,
                      radius, options, data):
        send_fut = asyncio.Future()
        if not send_timeout:
            if send_success:
                send_fut.set_result(xbee_t.TXStatus.SUCCESS)
            else:
                send_fut.set_result(xbee_t.TXStatus.ADDRESS_NOT_FOUND)
        return send_fut

    app._api._command = mock.MagicMock(side_effect=_mock_command)
    return await app.request(dev,
                             0x0260,
                             1,
                             2,
                             3,
                             seq,
                             b"\xaa\x55\xbe\xef",
                             expect_reply=expect_reply,
                             **kwargs)
Exemplo n.º 29
0
async def test_command(api):
    def mock_api_frame(name, *args):
        c = xbee_api.COMMAND_REQUESTS[name]
        return mock.sentinel.api_frame_data, c[2]

    api._api_frame = mock.MagicMock(side_effect=mock_api_frame)
    api._uart.send = mock.MagicMock()

    for cmd_name, cmd_opts in xbee_api.COMMAND_REQUESTS.items():
        cmd_id, schema, expect_reply = cmd_opts
        ret = api._command(cmd_name, mock.sentinel.cmd_data)
        if expect_reply:
            assert asyncio.isfuture(ret) is True
            ret.cancel()
        else:
            assert ret is None
        assert api._api_frame.call_count == 1
        assert api._api_frame.call_args[0][0] == cmd_name
        assert api._api_frame.call_args[0][1] == api._seq - 1
        assert api._api_frame.call_args[0][2] == mock.sentinel.cmd_data
        assert api._uart.send.call_count == 1
        assert api._uart.send.call_args[0][0] == mock.sentinel.api_frame_data
        api._api_frame.reset_mock()
        api._uart.send.reset_mock()

        ret = api._command(cmd_name,
                           mock.sentinel.cmd_data,
                           mask_frame_id=True)
        assert ret is None
        assert api._api_frame.call_count == 1
        assert api._api_frame.call_args[0][0] == cmd_name
        assert api._api_frame.call_args[0][1] == 0
        assert api._api_frame.call_args[0][2] == mock.sentinel.cmd_data
        assert api._uart.send.call_count == 1
        assert api._uart.send.call_args[0][0] == mock.sentinel.api_frame_data
        api._api_frame.reset_mock()
        api._uart.send.reset_mock()
Exemplo n.º 30
0
def test_frame_received(api, monkeypatch):
    monkeypatch.setattr(
        t,
        "deserialize",
        mock.MagicMock(return_value=(
            [
                mock.sentinel.arg_0,
                mock.sentinel.arg_1,
                mock.sentinel.arg_2,
                mock.sentinel.arg_3,
                mock.sentinel.arg_4,
                mock.sentinel.arg_5,
                mock.sentinel.arg_6,
                mock.sentinel.arg_7,
                mock.sentinel.arg_8,
            ],
            b"",
        )),
    )
    my_handler = mock.MagicMock()

    for cmd, cmd_opts in xbee_api.COMMAND_RESPONSES.items():
        cmd_id = cmd_opts[0]
        payload = b"\x01\x02\x03\x04"
        data = cmd_id.to_bytes(1, "big") + payload
        setattr(api, "_handle_{}".format(cmd), my_handler)
        api.frame_received(data)
        assert t.deserialize.call_count == 1
        assert t.deserialize.call_args[0][0] == payload
        assert my_handler.call_count == 1
        assert my_handler.call_args[0][0] == mock.sentinel.arg_0
        assert my_handler.call_args[0][1] == mock.sentinel.arg_1
        assert my_handler.call_args[0][2] == mock.sentinel.arg_2
        assert my_handler.call_args[0][3] == mock.sentinel.arg_3
        t.deserialize.reset_mock()
        my_handler.reset_mock()