File: test_application.py

package info (click to toggle)
zigpy 0.80.1-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 3,012 kB
  • sloc: python: 34,822; sql: 2,109; makefile: 7
file content (1616 lines) | stat: -rw-r--r-- 49,334 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
import asyncio
from datetime import datetime, timezone
import errno
import logging
from unittest import mock
from unittest.mock import ANY, PropertyMock, call

import pytest

import zigpy.application
import zigpy.config as conf
from zigpy.exceptions import (
    DeliveryError,
    NetworkNotFormed,
    NetworkSettingsInconsistent,
    TransientConnectionError,
)
import zigpy.ota
import zigpy.quirks
import zigpy.types as t
from zigpy.zcl import clusters, foundation
import zigpy.zdo.types as zdo_t

from .async_mock import AsyncMock, MagicMock, patch, sentinel
from .conftest import (
    NCP_IEEE,
    App,
    make_app,
    make_ieee,
    make_neighbor,
    make_neighbor_from_device,
    make_node_desc,
)


@pytest.fixture
def ieee():
    return make_ieee()


async def test_permit(app, ieee):
    app.devices[ieee] = MagicMock()
    app.devices[ieee].zdo.permit = AsyncMock()
    app.permit_ncp = AsyncMock()
    await app.permit(node=(1, 1, 1, 1, 1, 1, 1, 1))
    assert app.devices[ieee].zdo.permit.call_count == 0
    assert app.permit_ncp.call_count == 0
    await app.permit(node=ieee)
    assert app.devices[ieee].zdo.permit.call_count == 1
    assert app.permit_ncp.call_count == 0
    await app.permit(node=NCP_IEEE)
    assert app.devices[ieee].zdo.permit.call_count == 1
    assert app.permit_ncp.call_count == 1


async def test_permit_delivery_failure(app, ieee):
    def zdo_permit(*args, **kwargs):
        raise DeliveryError("Failed")

    app.devices[ieee] = MagicMock()
    app.devices[ieee].zdo.permit = zdo_permit
    app.permit_ncp = AsyncMock()
    await app.permit(node=ieee)
    assert app.permit_ncp.call_count == 0


async def test_permit_broadcast(app):
    app.permit_ncp = AsyncMock()
    app.send_packet = AsyncMock()
    await app.permit(time_s=30)
    assert app.send_packet.call_count == 1
    assert app.permit_ncp.call_count == 1

    assert app.send_packet.mock_calls[0].args[0].dst.addr_mode == t.AddrMode.Broadcast


@patch("zigpy.device.Device.initialize", new_callable=AsyncMock)
async def test_join_handler_skip(init_mock, app, ieee):
    node_desc = make_node_desc()

    app.handle_join(1, ieee, None)
    app.get_device(ieee).node_desc = node_desc

    app.handle_join(1, ieee, None)
    assert app.get_device(ieee).node_desc == node_desc


async def test_join_handler_change_id(app, ieee):
    app.handle_join(1, ieee, None)
    app.handle_join(2, ieee, None)
    assert app.devices[ieee].nwk == 2


async def test_unknown_device_left(app, ieee):
    with patch.object(app, "listener_event", wraps=app.listener_event):
        app.handle_leave(0x1234, ieee)
        app.listener_event.assert_not_called()


async def test_known_device_left(app, ieee):
    dev = app.add_device(ieee, 0x1234)

    with patch.object(app, "listener_event", wraps=app.listener_event):
        app.handle_leave(0x1234, ieee)
        app.listener_event.assert_called_once_with("device_left", dev)


async def _remove(
    app, ieee, retval, zdo_reply=True, delivery_failure=True, has_node_desc=True
):
    async def leave(*args, **kwargs):
        if zdo_reply:
            return retval
        elif delivery_failure:
            raise DeliveryError("Error")
        else:
            raise asyncio.TimeoutError

    device = MagicMock()
    device.ieee = ieee
    device.zdo.leave.side_effect = leave

    if has_node_desc:
        device.node_desc = zdo_t.NodeDescriptor(1, 64, 142, 4388, 82, 255, 0, 255, 0)
    else:
        device.node_desc = None

    app.devices[ieee] = device
    await app.remove(ieee)
    for _i in range(1, 20):
        await asyncio.sleep(0)
    assert ieee not in app.devices


async def test_remove(app, ieee):
    """Test remove with successful zdo status."""

    with patch.object(app, "_remove_device", wraps=app._remove_device) as remove_device:
        await _remove(app, ieee, [0])
        assert remove_device.await_count == 1


async def test_remove_with_failed_zdo(app, ieee):
    """Test remove with unsuccessful zdo status."""

    with patch.object(app, "_remove_device", wraps=app._remove_device) as remove_device:
        await _remove(app, ieee, [1])
        assert remove_device.await_count == 1


async def test_remove_nonexistent(app, ieee):
    with patch.object(app, "_remove_device", AsyncMock()) as remove_device:
        await app.remove(ieee)
        for _i in range(1, 20):
            await asyncio.sleep(0)
        assert ieee not in app.devices
        assert remove_device.await_count == 0


async def test_remove_with_unreachable_device(app, ieee):
    with patch.object(app, "_remove_device", wraps=app._remove_device) as remove_device:
        await _remove(app, ieee, [0], zdo_reply=False)
        assert remove_device.await_count == 1


async def test_remove_with_reply_timeout(app, ieee):
    with patch.object(app, "_remove_device", wraps=app._remove_device) as remove_device:
        await _remove(app, ieee, [0], zdo_reply=False, delivery_failure=False)
        assert remove_device.await_count == 1


async def test_remove_without_node_desc(app, ieee):
    with patch.object(app, "_remove_device", wraps=app._remove_device) as remove_device:
        await _remove(app, ieee, [0], has_node_desc=False)
        assert remove_device.await_count == 1


def test_add_device(app, ieee):
    app.add_device(ieee, 8)
    app.add_device(ieee, 9)
    assert app.get_device(ieee).nwk == 9


def test_get_device_nwk(app, ieee):
    dev = app.add_device(ieee, 8)
    assert app.get_device(nwk=8) is dev


def test_get_device_ieee(app, ieee):
    dev = app.add_device(ieee, 8)
    assert app.get_device(ieee=ieee) is dev


def test_get_device_both(app, ieee):
    dev = app.add_device(ieee, 8)
    assert app.get_device(ieee=ieee, nwk=8) is dev


def test_get_device_missing(app, ieee):
    with pytest.raises(KeyError):
        app.get_device(nwk=8)


def test_device_property(app):
    app.add_device(nwk=0x0000, ieee=NCP_IEEE)
    assert app._device is app.get_device(ieee=NCP_IEEE)


def test_ieee(app):
    assert app.state.node_info.ieee


def test_nwk(app):
    assert app.state.node_info.nwk is not None


def test_config(app):
    assert app.config == app._config


def test_deserialize(app, ieee):
    dev = MagicMock()
    app.deserialize(dev, 1, 1, b"")
    assert dev.deserialize.call_count == 1


@pytest.mark.filterwarnings("ignore::DeprecationWarning")
async def test_handle_message_shim(app):
    dev = MagicMock()
    dev.nwk = 0x1234

    app.packet_received = MagicMock(spec_set=app.packet_received)
    app.handle_message(dev, 260, 1, 2, 3, b"data")

    assert app.packet_received.mock_calls == [
        call(
            t.ZigbeePacket(
                profile_id=260,
                cluster_id=1,
                src_ep=2,
                dst_ep=3,
                data=t.SerializableBytes(b"data"),
                src=t.AddrModeAddress(
                    addr_mode=t.AddrMode.NWK,
                    address=0x1234,
                ),
                dst=t.AddrModeAddress(
                    addr_mode=t.AddrMode.NWK,
                    address=0x0000,
                ),
            )
        )
    ]


@patch("zigpy.device.Device.is_initialized", new_callable=PropertyMock)
@patch("zigpy.quirks.handle_message_from_uninitialized_sender", new=MagicMock())
async def test_handle_message_uninitialized_dev(is_init_mock, app, ieee):
    dev = app.add_device(ieee, 0x1234)
    dev.packet_received = MagicMock()
    is_init_mock.return_value = False

    assert not dev.initializing

    def make_packet(
        profile_id: int, cluster_id: int, src_ep: int, dst_ep: int, data: bytes
    ) -> t.ZigbeePacket:
        return t.ZigbeePacket(
            profile_id=profile_id,
            cluster_id=cluster_id,
            src_ep=src_ep,
            dst_ep=dst_ep,
            data=t.SerializableBytes(data),
            src=t.AddrModeAddress(
                addr_mode=t.AddrMode.NWK,
                address=dev.nwk,
            ),
            dst=t.AddrModeAddress(
                addr_mode=t.AddrMode.NWK,
                address=0x0000,
            ),
        )

    # Power Configuration cluster not allowed, no endpoints
    app.packet_received(
        make_packet(profile_id=260, cluster_id=0x0001, src_ep=1, dst_ep=1, data=b"test")
    )
    assert dev.packet_received.call_count == 0
    assert zigpy.quirks.handle_message_from_uninitialized_sender.call_count == 1

    # Device should be completing initialization
    assert dev.initializing

    # ZDO is allowed
    app.packet_received(
        make_packet(profile_id=260, cluster_id=0x0000, src_ep=0, dst_ep=0, data=b"test")
    )
    assert dev.packet_received.call_count == 1

    # Endpoint is uninitialized but Basic attribute read responses still work
    ep = dev.add_endpoint(1)
    app.packet_received(
        make_packet(profile_id=260, cluster_id=0x0000, src_ep=1, dst_ep=1, data=b"test")
    )
    assert dev.packet_received.call_count == 2

    # Others still do not
    app.packet_received(
        make_packet(profile_id=260, cluster_id=0x0001, src_ep=1, dst_ep=1, data=b"test")
    )
    assert dev.packet_received.call_count == 2
    assert zigpy.quirks.handle_message_from_uninitialized_sender.call_count == 2

    # They work after the endpoint is initialized
    ep.status = zigpy.endpoint.Status.ZDO_INIT
    app.packet_received(
        make_packet(profile_id=260, cluster_id=0x0001, src_ep=1, dst_ep=1, data=b"test")
    )
    assert dev.packet_received.call_count == 3
    assert zigpy.quirks.handle_message_from_uninitialized_sender.call_count == 2


def test_get_dst_address(app):
    r = app.get_dst_address(MagicMock())
    assert r.addrmode == 3
    assert r.endpoint == 1


def test_props(app):
    assert app.state.network_info.channel is not None
    assert app.state.network_info.channel_mask is not None
    assert app.state.network_info.extended_pan_id is not None
    assert app.state.network_info.pan_id is not None
    assert app.state.network_info.nwk_update_id is not None


@pytest.mark.filterwarnings(
    "ignore::DeprecationWarning"
)  # TODO: migrate `handle_message_from_uninitialized_sender` away from `handle_message`
async def test_uninitialized_message_handlers(app, ieee):
    """Test uninitialized message handlers."""
    handler_1 = MagicMock(return_value=None)
    handler_2 = MagicMock(return_value=True)

    zigpy.quirks.register_uninitialized_device_message_handler(handler_1)
    zigpy.quirks.register_uninitialized_device_message_handler(handler_2)

    device = app.add_device(ieee, 0x1234)

    app.handle_message(device, 0x0260, 0x0000, 0, 0, b"123abcd23")
    assert handler_1.call_count == 0
    assert handler_2.call_count == 0

    app.handle_message(device, 0x0260, 0x0000, 1, 1, b"123abcd23")
    assert handler_1.call_count == 1
    assert handler_2.call_count == 1

    handler_1.return_value = True
    app.handle_message(device, 0x0260, 0x0000, 1, 1, b"123abcd23")
    assert handler_1.call_count == 2
    assert handler_2.call_count == 1


async def test_remove_parent_devices(app, make_initialized_device):
    """Test removing an end device with parents."""

    end_device = make_initialized_device(app)
    end_device.node_desc.logical_type = zdo_t.LogicalType.EndDevice

    router_1 = make_initialized_device(app)
    router_1.node_desc.logical_type = zdo_t.LogicalType.Router

    router_2 = make_initialized_device(app)
    router_2.node_desc.logical_type = zdo_t.LogicalType.Router

    parent = make_initialized_device(app)

    app.topology.neighbors[router_1.ieee] = [
        make_neighbor_from_device(router_2),
        make_neighbor_from_device(parent),
    ]
    app.topology.neighbors[router_2.ieee] = [
        make_neighbor_from_device(parent),
        make_neighbor_from_device(router_1),
    ]
    app.topology.neighbors[parent.ieee] = [
        make_neighbor_from_device(router_2),
        make_neighbor_from_device(router_1),
        make_neighbor_from_device(end_device),
        make_neighbor(ieee=make_ieee(123), nwk=0x9876),
    ]

    p1 = patch.object(end_device.zdo, "leave", AsyncMock())
    p2 = patch.object(end_device.zdo, "request", AsyncMock())
    p3 = patch.object(parent.zdo, "leave", AsyncMock())
    p4 = patch.object(parent.zdo, "request", AsyncMock())
    p5 = patch.object(router_1.zdo, "leave", AsyncMock())
    p6 = patch.object(router_1.zdo, "request", AsyncMock())
    p7 = patch.object(router_2.zdo, "leave", AsyncMock())
    p8 = patch.object(router_2.zdo, "request", AsyncMock())

    with p1, p2, p3, p4, p5, p6, p7, p8:
        await app.remove(end_device.ieee)
        for _i in range(1, 60):
            await asyncio.sleep(0)

        assert end_device.zdo.leave.await_count == 1
        assert end_device.zdo.request.await_count == 0
        assert router_1.zdo.leave.await_count == 0
        assert router_1.zdo.request.await_count == 0
        assert router_2.zdo.leave.await_count == 0
        assert router_2.zdo.request.await_count == 0
        assert parent.zdo.leave.await_count == 0
        assert parent.zdo.request.await_count == 1


@patch("zigpy.device.Device.schedule_initialize", new_callable=MagicMock)
@patch("zigpy.device.Device.schedule_group_membership_scan", new_callable=MagicMock)
@patch("zigpy.device.Device.is_initialized", new_callable=PropertyMock)
async def test_device_join_rejoin(is_init_mock, group_scan_mock, init_mock, app, ieee):
    app.listener_event = MagicMock()
    is_init_mock.return_value = False

    # First join is treated as a new join
    app.handle_join(0x0001, ieee, None)
    app.listener_event.assert_called_once_with("device_joined", ANY)
    app.listener_event.reset_mock()
    init_mock.assert_called_once()
    init_mock.reset_mock()

    # Second join with the same NWK is just a reset, not a join
    app.handle_join(0x0001, ieee, None)
    app.listener_event.assert_not_called()
    group_scan_mock.assert_not_called()

    # Since the device is still partially initialized, re-initialize it
    init_mock.assert_called_once()
    init_mock.reset_mock()

    # Another join with the same NWK but initialized will trigger a group re-scan
    is_init_mock.return_value = True

    app.handle_join(0x0001, ieee, None)
    is_init_mock.return_value = True
    app.listener_event.assert_not_called()
    group_scan_mock.assert_called_once()
    group_scan_mock.reset_mock()
    init_mock.assert_not_called()

    # Join with a different NWK but the same IEEE is a re-join
    app.handle_join(0x0002, ieee, None)
    app.listener_event.assert_called_once_with("device_joined", ANY)
    group_scan_mock.assert_not_called()
    init_mock.assert_called_once()


async def test_get_device(app):
    """Test get_device."""

    await app.startup()

    app.add_device(t.EUI64.convert("11:11:11:11:22:22:22:22"), 0x0000)
    dev_2 = app.add_device(app.state.node_info.ieee, 0x0000)
    app.add_device(t.EUI64.convert("11:11:11:11:22:22:22:33"), 0x0000)

    assert app.get_device(nwk=0x0000) is dev_2


async def test_probe_success():
    config = {"path": "/dev/test"}

    with (
        patch.object(App, "connect") as connect,
        patch.object(App, "disconnect") as disconnect,
    ):
        result = await App.probe(config)

    assert set(config.items()) <= set(result.items())

    assert connect.await_count == 1
    assert disconnect.await_count == 1


async def test_probe_failure():
    config = {"path": "/dev/test"}

    with (
        patch.object(App, "connect", side_effect=asyncio.TimeoutError) as connect,
        patch.object(App, "disconnect") as disconnect,
    ):
        result = await App.probe(config)

    assert result is False

    assert connect.await_count == 1
    assert disconnect.await_count == 1


async def test_form_network(app):
    with patch.object(app, "write_network_info") as write1:
        await app.form_network()

    with patch.object(app, "write_network_info") as write2:
        await app.form_network()

    nwk_info1 = write1.mock_calls[0].kwargs["network_info"]
    node_info1 = write1.mock_calls[0].kwargs["node_info"]

    nwk_info2 = write2.mock_calls[0].kwargs["network_info"]
    node_info2 = write2.mock_calls[0].kwargs["node_info"]

    assert node_info1 == node_info2

    # Critical network settings are randomized
    assert nwk_info1.extended_pan_id != nwk_info2.extended_pan_id
    assert nwk_info1.pan_id != nwk_info2.pan_id
    assert nwk_info1.network_key != nwk_info2.network_key

    # The well-known TCLK is used
    assert (
        nwk_info1.tc_link_key.key
        == nwk_info2.tc_link_key.key
        == t.KeyData(b"ZigBeeAlliance09")
    )

    assert nwk_info1.channel in (11, 15, 20, 25)


@mock.patch("zigpy.util.pick_optimal_channel", mock.Mock(return_value=22))
async def test_form_network_find_best_channel(app):
    orig_start_network = app.start_network

    async def start_network(*args, **kwargs):
        start_network.await_count += 1

        if start_network.await_count == 1:
            raise NetworkNotFormed

        return await orig_start_network(*args, **kwargs)

    start_network.await_count = 0
    app.start_network = start_network

    with patch.object(app, "write_network_info") as write:
        with patch.object(
            app.backups, "create_backup", wraps=app.backups.create_backup
        ) as create_backup:
            await app.form_network()

    assert start_network.await_count == 2

    # A temporary network will be formed first
    nwk_info1 = write.mock_calls[0].kwargs["network_info"]
    assert nwk_info1.channel == 11

    # Then, after the scan, a better channel is chosen
    nwk_info2 = write.mock_calls[1].kwargs["network_info"]
    assert nwk_info2.channel == 22

    # Only a single backup will be present
    assert create_backup.await_count == 1


async def test_startup_formed():
    app = make_app({})
    app.start_network = AsyncMock(wraps=app.start_network)
    app.form_network = AsyncMock()
    app.permit = AsyncMock()

    await app.startup(auto_form=False)

    assert app.start_network.await_count == 1
    assert app.form_network.await_count == 0
    assert app.permit.await_count == 1


async def test_startup_not_formed():
    app = make_app({})
    app.start_network = AsyncMock(wraps=app.start_network)
    app.form_network = AsyncMock()
    app.load_network_info = AsyncMock(
        side_effect=[NetworkNotFormed(), NetworkNotFormed(), None]
    )
    app.permit = AsyncMock()

    app.backups.backups = []
    app.backups.restore_backup = AsyncMock()

    with pytest.raises(NetworkNotFormed):
        await app.startup(auto_form=False)

    assert app.start_network.await_count == 0
    assert app.form_network.await_count == 0
    assert app.permit.await_count == 0

    await app.startup(auto_form=True)

    assert app.start_network.await_count == 1
    assert app.form_network.await_count == 1
    assert app.permit.await_count == 1
    assert app.backups.restore_backup.await_count == 0


async def test_startup_not_formed_with_backup():
    app = make_app({})
    app.start_network = AsyncMock(wraps=app.start_network)
    app.load_network_info = AsyncMock(side_effect=[NetworkNotFormed(), None])
    app.permit = AsyncMock()

    app.backups.restore_backup = AsyncMock()
    app.backups.backups = [sentinel.OLD_BACKUP, sentinel.NEW_BACKUP]

    await app.startup(auto_form=True)

    assert app.start_network.await_count == 1
    app.backups.restore_backup.assert_called_once_with(sentinel.NEW_BACKUP)


async def test_startup_backup():
    app = make_app({conf.CONF_NWK_BACKUP_ENABLED: True})

    with patch("zigpy.backups.BackupManager.start_periodic_backups") as p:
        await app.startup()

    p.assert_called_once()


async def test_startup_no_backup():
    app = make_app({conf.CONF_NWK_BACKUP_ENABLED: False})

    with patch("zigpy.backups.BackupManager.start_periodic_backups") as p:
        await app.startup()

    p.assert_not_called()


def with_attributes(obj, **attrs):
    for k, v in attrs.items():
        setattr(obj, k, v)

    return obj


@pytest.mark.parametrize(
    "error",
    [
        with_attributes(OSError("Network is unreachable"), errno=errno.ENETUNREACH),
        ConnectionRefusedError(),
    ],
)
async def test_startup_failure_transient_error(error):
    app = make_app({conf.CONF_NWK_BACKUP_ENABLED: False})

    with patch.object(app, "connect", side_effect=[error]):
        with pytest.raises(TransientConnectionError):
            await app.startup()


@patch("zigpy.backups.BackupManager.from_network_state")
@patch("zigpy.backups.BackupManager.most_recent_backup")
async def test_initialize_compatible_backup(
    mock_most_recent_backup, mock_backup_from_state
):
    app = make_app({conf.CONF_NWK_VALIDATE_SETTINGS: True})
    mock_backup_from_state.return_value.is_compatible_with.return_value = True

    await app.initialize()

    mock_backup_from_state.return_value.is_compatible_with.assert_called_once()
    mock_most_recent_backup.assert_called_once()


@patch("zigpy.backups.BackupManager.from_network_state")
@patch("zigpy.backups.BackupManager.most_recent_backup")
async def test_initialize_incompatible_backup(
    mock_most_recent_backup, mock_backup_from_state
):
    app = make_app({conf.CONF_NWK_VALIDATE_SETTINGS: True})
    mock_backup_from_state.return_value.is_compatible_with.return_value = False

    with pytest.raises(NetworkSettingsInconsistent) as exc:
        await app.initialize()

    mock_backup_from_state.return_value.is_compatible_with.assert_called_once()
    mock_most_recent_backup.assert_called_once()

    assert exc.value.old_state is mock_most_recent_backup()
    assert exc.value.new_state is mock_backup_from_state.return_value


async def test_relays_received_device_exists(app):
    device = MagicMock()

    app._discover_unknown_device = AsyncMock(spec_set=app._discover_unknown_device)
    app.get_device = MagicMock(spec_set=app.get_device, return_value=device)
    app.handle_relays(nwk=0x1234, relays=[0x5678, 0xABCD])

    app.get_device.assert_called_once_with(nwk=0x1234)
    assert device.relays == [0x5678, 0xABCD]
    assert app._discover_unknown_device.call_count == 0


async def test_relays_received_device_does_not_exist(app):
    app._discover_unknown_device = AsyncMock(spec_set=app._discover_unknown_device)
    app.get_device = MagicMock(wraps=app.get_device)
    app.handle_relays(nwk=0x1234, relays=[0x5678, 0xABCD])

    app.get_device.assert_called_once_with(nwk=0x1234)
    app._discover_unknown_device.assert_called_once_with(nwk=0x1234)


async def test_request_concurrency():
    current_concurrency = 0
    peak_concurrency = 0

    class SlowApp(App):
        async def send_packet(self, packet):
            nonlocal current_concurrency, peak_concurrency

            async with self._limit_concurrency():
                current_concurrency += 1
                peak_concurrency = max(peak_concurrency, current_concurrency)

                await asyncio.sleep(0.1)
                current_concurrency -= 1

                if packet % 10 == 7:
                    # Fail randomly
                    raise DeliveryError("Failure")

    app = make_app({conf.CONF_MAX_CONCURRENT_REQUESTS: 16}, app_base=SlowApp)

    assert current_concurrency == 0
    assert peak_concurrency == 0

    await asyncio.gather(
        *[app.send_packet(i) for i in range(100)], return_exceptions=True
    )

    assert current_concurrency == 0
    assert peak_concurrency == 16


@pytest.fixture
def device():
    device = MagicMock()
    device.nwk = 0xABCD
    device.ieee = t.EUI64.convert("aa:bb:cc:dd:11:22:33:44")

    return device


@pytest.fixture
def packet(app, device):
    return t.ZigbeePacket(
        src=t.AddrModeAddress(
            addr_mode=t.AddrMode.NWK, address=app.state.node_info.nwk
        ),
        src_ep=0x9A,
        dst=t.AddrModeAddress(addr_mode=t.AddrMode.NWK, address=device.nwk),
        dst_ep=0xBC,
        tsn=0xDE,
        profile_id=0x1234,
        cluster_id=0x0006,
        data=t.SerializableBytes(b"test data"),
        source_route=None,
        extended_timeout=False,
        tx_options=t.TransmitOptions.NONE,
    )


async def test_request(app, device, packet):
    app.build_source_route_to = MagicMock(spec_set=app.build_source_route_to)

    async def send_request(app, **kwargs):
        kwargs = {
            "device": device,
            "profile": 0x1234,
            "cluster": 0x0006,
            "src_ep": 0x9A,
            "dst_ep": 0xBC,
            "sequence": 0xDE,
            "data": b"test data",
            "expect_reply": True,
            "use_ieee": False,
            "extended_timeout": False,
            **kwargs,
        }

        return await app.request(**kwargs)

    # Test sending with NWK
    status, msg = await send_request(app)
    assert status == zigpy.zcl.foundation.Status.SUCCESS
    assert isinstance(msg, str)

    app.send_packet.assert_called_once_with(packet)
    app.send_packet.reset_mock()

    # Test sending with IEEE
    await send_request(app, use_ieee=True)
    app.send_packet.assert_called_once_with(
        packet.replace(
            src=t.AddrModeAddress(
                addr_mode=t.AddrMode.IEEE,
                address=app.state.node_info.ieee,
            ),
            dst=t.AddrModeAddress(
                addr_mode=t.AddrMode.IEEE,
                address=device.ieee,
            ),
        )
    )
    app.send_packet.reset_mock()

    # Test sending with source route
    app.build_source_route_to.return_value = [0x000A, 0x000B]

    with patch.dict(app.config, {conf.CONF_SOURCE_ROUTING: True}):
        await send_request(app)

    app.build_source_route_to.assert_called_once_with(dest=device)
    app.send_packet.assert_called_once_with(
        packet.replace(source_route=[0x000A, 0x000B])
    )
    app.send_packet.reset_mock()

    # Test sending without waiting for a reply
    status, msg = await send_request(app, expect_reply=False)

    app.send_packet.assert_called_once_with(
        packet.replace(tx_options=t.TransmitOptions.ACK)
    )
    app.send_packet.reset_mock()

    # Test explicit ACK control (enabled)
    status, msg = await send_request(app, ask_for_ack=True)

    app.send_packet.assert_called_once_with(
        packet.replace(tx_options=t.TransmitOptions.ACK)
    )
    app.send_packet.reset_mock()

    # Test explicit ACK control (disabled)
    status, msg = await send_request(app, ask_for_ack=False)

    app.send_packet.assert_called_once_with(
        packet.replace(tx_options=t.TransmitOptions(0))
    )
    app.send_packet.reset_mock()


async def test_request_retrying_success(app, device, packet) -> None:
    app.send_packet.side_effect = [
        DeliveryError("Failure"),
        DeliveryError("Failure"),
        None,
    ]

    await app.request(
        device=device,
        profile=0x1234,
        cluster=0x0006,
        src_ep=0x9A,
        dst_ep=0xBC,
        sequence=0xDE,
        data=b"test data",
        expect_reply=True,
        use_ieee=False,
        extended_timeout=False,
    )

    assert app.send_packet.mock_calls == [
        call(packet),
        call(
            packet.replace(
                tx_options=packet.tx_options | t.TransmitOptions.FORCE_ROUTE_DISCOVERY
            )
        ),
        call(
            packet.replace(
                tx_options=packet.tx_options | t.TransmitOptions.FORCE_ROUTE_DISCOVERY
            )
        ),
    ]


async def test_request_retrying_failure(app, device, packet) -> None:
    app.send_packet.side_effect = [
        DeliveryError("Failure"),
        DeliveryError("Failure"),
        DeliveryError("Failure"),
    ]

    with pytest.raises(DeliveryError):
        await app.request(
            device=device,
            profile=0x1234,
            cluster=0x0006,
            src_ep=0x9A,
            dst_ep=0xBC,
            sequence=0xDE,
            data=b"test data",
            expect_reply=True,
            use_ieee=False,
            extended_timeout=False,
        )

    assert app.send_packet.mock_calls == [
        call(packet),
        call(
            packet.replace(
                tx_options=packet.tx_options | t.TransmitOptions.FORCE_ROUTE_DISCOVERY
            )
        ),
        call(
            packet.replace(
                tx_options=packet.tx_options | t.TransmitOptions.FORCE_ROUTE_DISCOVERY
            )
        ),
    ]


def test_build_source_route_has_relays(app):
    device = MagicMock()
    device.relays = [0x1234, 0x5678]

    assert app.build_source_route_to(device) == [0x5678, 0x1234]


def test_build_source_route_no_relays(app):
    device = MagicMock()
    device.relays = None

    assert app.build_source_route_to(device) is None


async def test_send_mrequest(app, packet):
    status, msg = await app.mrequest(
        group_id=0xABCD,
        profile=0x1234,
        cluster=0x0006,
        src_ep=0x9A,
        sequence=0xDE,
        data=b"test data",
        hops=12,
        non_member_radius=34,
    )
    assert status == zigpy.zcl.foundation.Status.SUCCESS
    assert isinstance(msg, str)

    app.send_packet.assert_called_once_with(
        packet.replace(
            dst=t.AddrModeAddress(addr_mode=t.AddrMode.Group, address=0xABCD),
            dst_ep=None,
            radius=12,
            non_member_radius=34,
            tx_options=t.TransmitOptions.NONE,
        )
    )


async def test_send_broadcast(app, packet):
    status, msg = await app.broadcast(
        profile=0x1234,
        cluster=0x0006,
        src_ep=0x9A,
        dst_ep=0xBC,
        grpid=0x0000,  # unused
        radius=12,
        sequence=0xDE,
        data=b"test data",
        broadcast_address=t.BroadcastAddress.RX_ON_WHEN_IDLE,
    )
    assert status == zigpy.zcl.foundation.Status.SUCCESS
    assert isinstance(msg, str)

    app.send_packet.assert_called_once_with(
        packet.replace(
            dst=t.AddrModeAddress(
                addr_mode=t.AddrMode.Broadcast,
                address=t.BroadcastAddress.RX_ON_WHEN_IDLE,
            ),
            radius=12,
            tx_options=t.TransmitOptions.NONE,
        )
    )


@pytest.fixture
def zdo_packet(app, device):
    return t.ZigbeePacket(
        src=t.AddrModeAddress(addr_mode=t.AddrMode.NWK, address=device.nwk),
        dst=t.AddrModeAddress(
            addr_mode=t.AddrMode.NWK, address=app.state.node_info.nwk
        ),
        src_ep=0x00,  # ZDO
        dst_ep=0x00,
        tsn=0xDE,
        profile_id=0x0000,
        cluster_id=0x0000,
        data=t.SerializableBytes(b""),
        source_route=None,
        extended_timeout=False,
        tx_options=t.TransmitOptions.ACK,
        lqi=123,
        rssi=-80,
    )


@patch("zigpy.device.Device.initialize", AsyncMock())
async def test_packet_received_new_device_zdo_announce(app, device, zdo_packet):
    app.handle_join = MagicMock(wraps=app.handle_join)

    zdo_data = zigpy.zdo.ZDO(None)._serialize(
        zdo_t.ZDOCmd.Device_annce,
        *{
            "NWKAddr": device.nwk,
            "IEEEAddr": device.ieee,
            "Capability": 0x00,
        }.values(),
    )

    zdo_packet.cluster_id = zdo_t.ZDOCmd.Device_annce
    zdo_packet.data = t.SerializableBytes(
        t.uint8_t(zdo_packet.tsn).serialize() + zdo_data
    )
    app.packet_received(zdo_packet)

    app.handle_join.assert_called_once_with(
        nwk=device.nwk, ieee=device.ieee, parent_nwk=None
    )

    zigpy_device = app.get_device(ieee=device.ieee)
    assert zigpy_device.lqi == zdo_packet.lqi
    assert zigpy_device.rssi == zdo_packet.rssi


@patch("zigpy.device.Device.initialize", AsyncMock())
async def test_packet_received_new_device_discovery(app, device, zdo_packet):
    app.handle_join = MagicMock(wraps=app.handle_join)

    async def send_packet(packet):
        if packet.dst_ep != 0x00 or packet.cluster_id != zdo_t.ZDOCmd.IEEE_addr_req:
            return

        hdr, args = zigpy.zdo.ZDO(None).deserialize(
            packet.cluster_id, packet.data.serialize()
        )
        assert args == list(
            {
                "NWKAddrOfInterest": device.nwk,
                "RequestType": zdo_t.AddrRequestType.Single,
                "StartIndex": 0,
            }.values()
        )

        zdo_data = zigpy.zdo.ZDO(None)._serialize(
            zdo_t.ZDOCmd.IEEE_addr_rsp,
            *{
                "Status": zdo_t.Status.SUCCESS,
                "IEEEAddr": device.ieee,
                "NWKAddr": device.nwk,
                "NumAssocDev": 0,
                "StartIndex": 0,
                "NWKAddrAssocDevList": [],
            }.values(),
        )

        # Receive the IEEE address reply
        zdo_packet.data = t.SerializableBytes(
            t.uint8_t(zdo_packet.tsn).serialize() + zdo_data
        )
        zdo_packet.cluster_id = zdo_t.ZDOCmd.IEEE_addr_rsp
        app.packet_received(zdo_packet)

    app.send_packet = AsyncMock(side_effect=send_packet)

    # Receive a bogus packet first, to trigger device discovery
    bogus_packet = zdo_packet.replace(dst_ep=0x01, src_ep=0x01)
    app.packet_received(bogus_packet)

    await asyncio.sleep(0.1)

    app.handle_join.assert_called_once_with(
        nwk=device.nwk, ieee=device.ieee, parent_nwk=None, handle_rejoin=False
    )

    zigpy_device = app.get_device(ieee=device.ieee)
    assert zigpy_device.lqi == zdo_packet.lqi
    assert zigpy_device.rssi == zdo_packet.rssi


@patch("zigpy.device.Device.initialize", AsyncMock())
async def test_packet_received_ieee_no_rejoin(app, device, zdo_packet, caplog):
    device.is_initialized = True
    app.devices[device.ieee] = device

    app.handle_join = MagicMock(wraps=app.handle_join)

    zdo_data = zigpy.zdo.ZDO(None)._serialize(
        zdo_t.ZDOCmd.IEEE_addr_rsp,
        *{
            "Status": zdo_t.Status.SUCCESS,
            "IEEEAddr": device.ieee,
            "NWKAddr": device.nwk,
        }.values(),
    )

    zdo_packet.cluster_id = zdo_t.ZDOCmd.IEEE_addr_rsp
    zdo_packet.data = t.SerializableBytes(
        t.uint8_t(zdo_packet.tsn).serialize() + zdo_data
    )
    app.packet_received(zdo_packet)

    assert "joined the network" not in caplog.text

    app.handle_join.assert_called_once_with(
        nwk=device.nwk, ieee=device.ieee, parent_nwk=None, handle_rejoin=False
    )

    assert len(device.schedule_group_membership_scan.mock_calls) == 0
    assert len(device.schedule_initialize.mock_calls) == 0


@patch("zigpy.device.Device.initialize", AsyncMock())
async def test_packet_received_ieee_rejoin(app, device, zdo_packet, caplog):
    device.is_initialized = True
    app.devices[device.ieee] = device

    app.handle_join = MagicMock(wraps=app.handle_join)

    zdo_data = zigpy.zdo.ZDO(None)._serialize(
        zdo_t.ZDOCmd.IEEE_addr_rsp,
        *{
            "Status": zdo_t.Status.SUCCESS,
            "IEEEAddr": device.ieee,
            "NWKAddr": device.nwk + 1,  # NWK has changed
        }.values(),
    )

    zdo_packet.cluster_id = zdo_t.ZDOCmd.IEEE_addr_rsp
    zdo_packet.data = t.SerializableBytes(
        t.uint8_t(zdo_packet.tsn).serialize() + zdo_data
    )
    app.packet_received(zdo_packet)

    assert "joined the network" not in caplog.text

    app.handle_join.assert_called_once_with(
        nwk=device.nwk, ieee=device.ieee, parent_nwk=None, handle_rejoin=False
    )

    assert len(device.schedule_initialize.mock_calls) == 1


async def test_bad_zdo_packet_received(app, device):
    device.is_initialized = True
    app.devices[device.ieee] = device

    bogus_zdo_packet = t.ZigbeePacket(
        src=t.AddrModeAddress(addr_mode=t.AddrMode.NWK, address=device.nwk),
        src_ep=1,
        dst=t.AddrModeAddress(addr_mode=t.AddrMode.NWK, address=0x0000),
        dst_ep=0,  # bad destination endpoint
        tsn=180,
        profile_id=260,
        cluster_id=6,
        data=t.SerializableBytes(b"\x08n\n\x00\x00\x10\x00"),
        lqi=255,
        rssi=-30,
    )

    app.packet_received(bogus_zdo_packet)

    assert len(device.packet_received.mock_calls) == 1


def test_get_device_with_address_nwk(app, device):
    app.devices[device.ieee] = device

    assert (
        app.get_device_with_address(
            t.AddrModeAddress(addr_mode=t.AddrMode.NWK, address=device.nwk)
        )
        is device
    )
    assert (
        app.get_device_with_address(
            t.AddrModeAddress(addr_mode=t.AddrMode.IEEE, address=device.ieee)
        )
        is device
    )

    with pytest.raises(ValueError):
        app.get_device_with_address(
            t.AddrModeAddress(addr_mode=t.AddrMode.Group, address=device.nwk)
        )

    with pytest.raises(KeyError):
        app.get_device_with_address(
            t.AddrModeAddress(addr_mode=t.AddrMode.NWK, address=device.nwk + 1)
        )


async def test_request_future_matching(app, make_initialized_device):
    device = make_initialized_device(app)
    device._packet_debouncer.filter = MagicMock(return_value=False)

    ota = device.endpoints[1].add_output_cluster(clusters.general.Ota.cluster_id)

    req_hdr, req_cmd = ota._create_request(
        general=False,
        command_id=ota.commands_by_name["query_next_image"].id,
        schema=ota.commands_by_name["query_next_image"].schema,
        disable_default_response=False,
        direction=foundation.Direction.Client_to_Server,
        args=(),
        kwargs={
            "field_control": 0,
            "manufacturer_code": 0x1234,
            "image_type": 0x5678,
            "current_file_version": 0x11112222,
        },
    )

    packet = t.ZigbeePacket(
        src=t.AddrModeAddress(addr_mode=t.AddrMode.NWK, address=device.nwk),
        src_ep=1,
        dst=t.AddrModeAddress(addr_mode=t.AddrMode.NWK, address=0x0000),
        dst_ep=1,
        tsn=req_hdr.tsn,
        profile_id=260,
        cluster_id=ota.cluster_id,
        data=t.SerializableBytes(req_hdr.serialize() + req_cmd.serialize()),
        lqi=255,
        rssi=-30,
    )

    assert not app._req_listeners[device]

    with app.wait_for_response(
        device, [ota.commands_by_name["query_next_image"].schema()]
    ) as rsp_fut:
        # Attach two listeners
        with app.wait_for_response(
            device, [ota.commands_by_name["query_next_image"].schema()]
        ) as rsp_fut2:
            assert app._req_listeners[device]

            # Listeners are resolved FIFO
            app.packet_received(packet)
            assert rsp_fut.done()
            assert not rsp_fut2.done()

            app.packet_received(packet)
            assert rsp_fut.done()
            assert rsp_fut2.done()

            # Unhandled packets are ignored
            app.packet_received(packet)

            rsp_hdr, rsp_cmd = await rsp_fut
            assert rsp_hdr == req_hdr
            assert rsp_cmd == req_cmd
            assert rsp_cmd.current_file_version == 0x11112222

    assert not app._req_listeners[device]


async def test_request_callback_matching(app, make_initialized_device):
    device = make_initialized_device(app)
    device._packet_debouncer.filter = MagicMock(return_value=False)
    ota = device.endpoints[1].add_output_cluster(clusters.general.Ota.cluster_id)

    req_hdr, req_cmd = ota._create_request(
        general=False,
        command_id=ota.commands_by_name["query_next_image"].id,
        schema=ota.commands_by_name["query_next_image"].schema,
        disable_default_response=False,
        direction=foundation.Direction.Client_to_Server,
        args=(),
        kwargs={
            "field_control": 0,
            "manufacturer_code": 0x1234,
            "image_type": 0x5678,
            "current_file_version": 0x11112222,
        },
    )

    packet = t.ZigbeePacket(
        src=t.AddrModeAddress(addr_mode=t.AddrMode.NWK, address=device.nwk),
        src_ep=1,
        dst=t.AddrModeAddress(addr_mode=t.AddrMode.NWK, address=0x0000),
        dst_ep=1,
        tsn=req_hdr.tsn,
        profile_id=260,
        cluster_id=ota.cluster_id,
        data=t.SerializableBytes(req_hdr.serialize() + req_cmd.serialize()),
        lqi=255,
        rssi=-30,
    )

    mock_callback = mock.Mock()

    assert not app._req_listeners[device]

    with app.callback_for_response(
        device, [ota.commands_by_name["query_next_image"].schema()], mock_callback
    ):
        assert app._req_listeners[device]

        asyncio.get_running_loop().call_soon(app.packet_received, packet)
        asyncio.get_running_loop().call_soon(app.packet_received, packet)
        asyncio.get_running_loop().call_soon(app.packet_received, packet)

        await asyncio.sleep(0.1)

        assert len(mock_callback.mock_calls) == 3
        assert mock_callback.mock_calls == [mock.call(req_hdr, req_cmd)] * 3

    assert not app._req_listeners[device]


async def test_energy_scan_default(app):
    await app.startup()

    raw_scan_results = [
        170,
        191,
        181,
        165,
        179,
        169,
        196,
        163,
        174,
        162,
        190,
        186,
        191,
        178,
        204,
        187,
    ]
    coordinator = app._device
    coordinator.zdo.Mgmt_NWK_Update_req = AsyncMock(
        return_value=[
            zdo_t.Status.SUCCESS,
            t.Channels.ALL_CHANNELS,
            29,
            10,
            raw_scan_results,
        ]
    )

    results = await app.energy_scan(
        channels=t.Channels.ALL_CHANNELS, duration_exp=2, count=1
    )

    assert len(results) == 16
    assert results == dict(zip(range(11, 26 + 1), raw_scan_results))


async def test_energy_scan_not_implemented(app):
    """Energy scanning still "works" even when the radio doesn't implement it."""
    await app.startup()
    app._device.zdo.Mgmt_NWK_Update_req.side_effect = asyncio.TimeoutError()

    results = await app.energy_scan(
        channels=t.Channels.ALL_CHANNELS, duration_exp=2, count=1
    )
    assert results == {c: 0 for c in range(11, 26 + 1)}


async def test_startup_broadcast_failure_due_to_interference(app, caplog):
    err = DeliveryError(
        "Failed to deliver packet: <TXStatus.MAC_CHANNEL_ACCESS_FAILURE: 225>", 225
    )

    with mock.patch.object(app, "permit", side_effect=err):
        with caplog.at_level(logging.WARNING):
            await app.startup()

    # The application will still start up, however
    assert "Failed to send startup broadcast" in caplog.text
    assert "interference" in caplog.text


async def test_startup_broadcast_failure_other(app, caplog):
    with mock.patch.object(app, "permit", side_effect=DeliveryError("Error", 123)):
        with pytest.raises(DeliveryError, match="^Error$"):
            await app.startup()


@patch("zigpy.application.CHANNEL_CHANGE_SETTINGS_RELOAD_DELAY_S", 0.1)
@patch("zigpy.application.CHANNEL_CHANGE_BROADCAST_DELAY_S", 0.01)
async def test_move_network_to_new_channel(app):
    async def nwk_update(*args, **kwargs):
        async def inner():
            await asyncio.sleep(
                zigpy.application.CHANNEL_CHANGE_SETTINGS_RELOAD_DELAY_S * 5
            )
            NwkUpdate = args[0]
            app.state.network_info.channel = list(NwkUpdate.ScanChannels)[0]
            app.state.network_info.nwk_update_id = NwkUpdate.nwkUpdateId

        asyncio.create_task(inner())  # noqa: RUF006

    await app.startup()

    assert app.state.network_info.channel != 26

    with patch.object(
        app._device.zdo, "Mgmt_NWK_Update_req", side_effect=nwk_update
    ) as mock_update:
        await app.move_network_to_channel(new_channel=26, num_broadcasts=10)

    assert app.state.network_info.channel == 26
    assert len(mock_update.mock_calls) == 1


async def test_move_network_to_new_channel_noop(app):
    await app.startup()

    old_channel = app.state.network_info.channel

    with patch("zigpy.zdo.broadcast") as mock_broadcast:
        await app.move_network_to_channel(new_channel=old_channel)

    assert app.state.network_info.channel == old_channel
    assert len(mock_broadcast.mock_calls) == 0


async def test_startup_multiple_dblistener(app):
    app._dblistener = AsyncMock()
    app.connect = AsyncMock(side_effect=RuntimeError())

    with pytest.raises(RuntimeError):
        await app.startup()

    with pytest.raises(RuntimeError):
        await app.startup()

    # The database listener will not be shut down automatically
    assert len(app._dblistener.shutdown.mock_calls) == 0


async def test_connection_lost(app):
    exc = RuntimeError()
    listener = MagicMock()

    app.add_listener(listener)
    app.connection_lost(exc)

    listener.connection_lost.assert_called_with(exc)


async def test_watchdog(app):
    error = RuntimeError()

    app = make_app({})
    app._watchdog_period = 0.1
    app._watchdog_feed = AsyncMock(side_effect=[None, None, error])
    app.connection_lost = MagicMock()

    assert app._watchdog_task is None
    await app.startup()
    assert app._watchdog_task is not None

    # We call it once during startup synchronously
    assert app._watchdog_feed.mock_calls == [call()]
    assert app.connection_lost.mock_calls == []

    await asyncio.sleep(0.5)

    assert app._watchdog_feed.mock_calls == [call(), call(), call()]
    assert app.connection_lost.mock_calls == [call(error)]
    assert app._watchdog_task.done()


@pytest.mark.filterwarnings("ignore::DeprecationWarning")
async def test_permit_with_key(app):
    app = make_app({})

    app.permit_with_link_key = AsyncMock()

    with pytest.raises(ValueError):
        await app.permit_with_key(
            node=t.EUI64.convert("aa:bb:cc:dd:11:22:33:44"),
            code=b"invalid code that is far too long and of the wrong parity",
            time_s=60,
        )

    assert app.permit_with_link_key.mock_calls == []

    await app.permit_with_key(
        node=t.EUI64.convert("aa:bb:cc:dd:11:22:33:44"),
        code=bytes.fromhex("11223344556677884AF7"),
        time_s=60,
    )

    assert app.permit_with_link_key.mock_calls == [
        call(
            node=t.EUI64.convert("aa:bb:cc:dd:11:22:33:44"),
            link_key=t.KeyData.convert("41618FC0C83B0E14A589954B16E31466"),
            time_s=60,
        )
    ]


async def test_probe(app):
    class BaudSpecificApp(App):
        _probe_configs = [
            {conf.CONF_DEVICE_BAUDRATE: 57600},
            {conf.CONF_DEVICE_BAUDRATE: 115200},
        ]

        async def connect(self):
            if self._config[conf.CONF_DEVICE][conf.CONF_DEVICE_BAUDRATE] != 115200:
                raise asyncio.TimeoutError

    # Only one baudrate is valid
    assert (await BaudSpecificApp.probe({conf.CONF_DEVICE_PATH: "/dev/null"})) == {
        conf.CONF_DEVICE_PATH: "/dev/null",
        conf.CONF_DEVICE_BAUDRATE: 115200,
        conf.CONF_DEVICE_FLOW_CONTROL: None,
    }

    class NeverConnectsApp(App):
        async def connect(self):
            raise asyncio.TimeoutError

    # No settings will work
    assert (await NeverConnectsApp.probe({conf.CONF_DEVICE_PATH: "/dev/null"})) is False


async def test_network_scan(app) -> None:
    beacons = [
        t.NetworkBeacon(
            pan_id=t.NWK(0x1234),
            extended_pan_id=t.EUI64.convert("11:22:33:44:55:66:77:88"),
            channel=11,
            nwk_update_id=1,
            permit_joining=True,
            stack_profile=2,
            lqi=255,
            rssi=-80,
        ),
        t.NetworkBeacon(
            pan_id=t.NWK(0xABCD),
            extended_pan_id=t.EUI64.convert("11:22:33:44:55:66:77:88"),
            channel=15,
            nwk_update_id=2,
            permit_joining=False,
            stack_profile=2,
            lqi=255,
            rssi=-40,
        ),
    ]

    with patch.object(app, "_network_scan") as mock_scan:
        mock_scan.return_value.__aiter__.return_value = beacons

        results = [
            b
            async for b in app.network_scan(
                channels=t.Channels.from_channel_list([11, 15]),
                duration_exp=1,
            )
        ]

    assert results == beacons
    assert mock_scan.mock_calls == [
        call(
            channels=t.Channels.from_channel_list([11, 15]),
            duration_exp=1,
        ),
        call().__aiter__(),
    ]


async def test_packet_capture(app) -> None:
    packets = [
        t.CapturedPacket(
            timestamp=datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone.utc),
            rssi=-60,
            lqi=250,
            channel=15,
            data=bytes.fromhex("02007f"),
        ),
        t.CapturedPacket(
            timestamp=datetime(2021, 1, 1, 0, 0, 1, tzinfo=timezone.utc),
            rssi=-70,
            lqi=240,
            channel=15,
            data=bytes.fromhex(
                "61886fefbe445600004802653c00001e1228eea3dd0046b8a11c004b120000631ea30c"
                "f9079829433d9b6165c3b56171df2557407024"
            ),
        ),
    ]

    with patch.object(app, "_packet_capture") as mock_capture:
        mock_capture.return_value.__aiter__.return_value = packets

        results = [p async for p in app.packet_capture(channel=15)]

    assert results == packets

    assert packets[0].compute_fcs() == b"\xc8\x3e"
    assert packets[1].compute_fcs() == b"\x63\x7d"

    with patch.object(app, "_packet_capture_change_channel"):
        await app.packet_capture_change_channel(channel=25)
        assert app._packet_capture_change_channel.mock_calls == [call(channel=25)]