File: test_zcl_foundation.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 (855 lines) | stat: -rw-r--r-- 26,081 bytes parent folder | download | duplicates (2)
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
import logging

import pytest

import zigpy.types as t
from zigpy.zcl import foundation


def test_typevalue():
    tv = foundation.TypeValue()
    tv.type = 0x20
    tv.value = t.uint8_t(99)
    ser = tv.serialize()
    r = repr(tv)
    assert r.startswith("TypeValue(") and r.endswith(")")
    assert "type=uint8_t" in r
    assert "value=99" in r

    tv2, data = foundation.TypeValue.deserialize(ser)
    assert data == b""
    assert tv2.type == tv.type
    assert tv2.value == tv.value

    tv3 = foundation.TypeValue(tv2)
    assert tv3.type == tv.type
    assert tv3.value == tv.value
    assert tv3 == tv2

    tv4 = foundation.TypeValue()
    tv4.type = 0x42
    tv4.value = t.CharacterString("test")
    assert "CharacterString" in str(tv4)
    assert "'test'" in str(tv4)

    tv5 = foundation.TypeValue()
    tv5.type = 0x42
    tv5.value = t.CharacterString("test")

    assert tv5 == tv5  # noqa: PLR0124
    assert tv5 == tv4
    assert tv5 != tv3


def test_read_attribute_record():
    orig = b"\x00\x00\x00\x20\x99"
    rar, data = foundation.ReadAttributeRecord.deserialize(orig)
    assert data == b""
    assert rar.status == 0
    assert isinstance(rar.value, foundation.TypeValue)
    assert isinstance(rar.value.value, t.uint8_t)
    assert rar.value.value == 0x99

    r = repr(rar)
    assert len(r) > 5
    assert repr(foundation.Status.SUCCESS) in r

    ser = rar.serialize()
    assert ser == orig


def test_attribute_reporting_config_0():
    arc = foundation.AttributeReportingConfig()
    arc.direction = foundation.ReportingDirection.SendReports
    arc.attrid = 99
    arc.datatype = 0x20
    arc.min_interval = 10
    arc.max_interval = 20
    arc.reportable_change = 30
    ser = arc.serialize()

    arc2, data = foundation.AttributeReportingConfig.deserialize(ser)
    assert data == b""
    assert arc2.direction == arc.direction
    assert arc2.attrid == arc.attrid
    assert arc2.datatype == arc.datatype
    assert arc2.min_interval == arc.min_interval
    assert arc2.max_interval == arc.max_interval
    assert arc.reportable_change == arc.reportable_change

    assert repr(arc)
    assert repr(arc) == repr(arc2)


def test_attribute_reporting_config_1():
    arc = foundation.AttributeReportingConfig()
    arc.direction = 1
    arc.attrid = 99
    arc.timeout = 0x7E
    ser = arc.serialize()

    arc2, data = foundation.AttributeReportingConfig.deserialize(ser)
    assert data == b""
    assert arc2.direction == arc.direction
    assert arc2.timeout == arc.timeout
    assert repr(arc)


def test_attribute_reporting_config_only_dir_and_attrid():
    arc = foundation.AttributeReportingConfig()
    arc.direction = foundation.ReportingDirection.SendReports
    arc.attrid = 99
    ser = arc.serialize(_only_dir_and_attrid=True)

    arc2, data = foundation.AttributeReportingConfig.deserialize(
        ser, _only_dir_and_attrid=True
    )
    assert data == b""
    assert arc2.direction == arc.direction
    assert arc2.attrid == arc.attrid

    assert repr(arc)
    assert repr(arc) == repr(arc2)


def test_attribute_reporting_config_bad_datatype(caplog):
    arc = foundation.AttributeReportingConfig()
    arc.direction = foundation.ReportingDirection.SendReports
    arc.attrid = 99
    arc.datatype = 0xFE  # unknown
    arc.min_interval = 10
    arc.max_interval = 20
    arc.reportable_change = 30

    with caplog.at_level(logging.WARNING):
        arc.serialize()

    assert "Unknown ZCL type" in caplog.text

    arc2 = foundation.AttributeReportingConfig()
    arc2.direction = foundation.ReportingDirection.SendReports
    arc2.attrid = 99
    arc2.datatype = 0xFE  # unknown
    arc2.min_interval = 10
    arc2.max_interval = 20
    # Missing the reportable change, since it can't be set

    assert arc.serialize() == arc2.serialize()

    caplog.clear()

    with caplog.at_level(logging.WARNING):
        arc3, data = foundation.AttributeReportingConfig.deserialize(arc.serialize())

    assert "Unknown ZCL type" in caplog.text

    assert arc3.serialize() == arc.serialize()


def test_write_attribute_status_record():
    attr_id = b"\x01\x00"
    extra = b"12da-"
    res, d = foundation.WriteAttributesStatusRecord.deserialize(
        b"\x00" + attr_id + extra
    )
    assert res.status == foundation.Status.SUCCESS
    assert res.attrid is None
    assert d == attr_id + extra
    r = repr(res)
    assert r.startswith(foundation.WriteAttributesStatusRecord.__name__)
    assert "status" in r
    assert "attrid" not in r

    res, d = foundation.WriteAttributesStatusRecord.deserialize(
        b"\x87" + attr_id + extra
    )
    assert res.status == foundation.Status.INVALID_VALUE
    assert res.attrid == 0x0001
    assert d == extra

    r = repr(res)
    assert "status" in r
    assert "attrid" in r

    rec = foundation.WriteAttributesStatusRecord(foundation.Status.SUCCESS, 0xAABB)
    assert rec.serialize() == b"\x00"
    rec.status = foundation.Status.UNSUPPORTED_ATTRIBUTE
    assert rec.serialize()[0:1] == foundation.Status.UNSUPPORTED_ATTRIBUTE.serialize()
    assert rec.serialize()[1:] == b"\xbb\xaa"


def test_configure_reporting_response_serialization():
    # success status only
    res, d = foundation.ConfigureReportingResponseRecord.deserialize(b"\x00")
    assert res.status == foundation.Status.SUCCESS
    assert res.direction is None
    assert res.attrid is None
    assert d == b""

    # success + direction and attr id
    direction_attr_id = b"\x00\x01\x10"
    extra = b"12da-"
    res, d = foundation.ConfigureReportingResponseRecord.deserialize(
        b"\x00" + direction_attr_id + extra
    )
    assert res.status == foundation.Status.SUCCESS
    assert res.direction is foundation.ReportingDirection.SendReports
    assert res.attrid == 0x1001
    assert d == extra
    r = repr(res)
    assert r.startswith(foundation.ConfigureReportingResponseRecord.__name__ + "(")
    assert "status" in r
    assert "direction" not in r
    assert "attrid" not in r

    # failure record deserialization
    res, d = foundation.ConfigureReportingResponseRecord.deserialize(
        b"\x8c" + direction_attr_id + extra
    )
    assert res.status == foundation.Status.UNREPORTABLE_ATTRIBUTE
    assert res.direction is not None
    assert res.attrid == 0x1001
    assert d == extra

    r = repr(res)
    assert "status" in r
    assert "direction" in r
    assert "attrid" in r

    # successful record serializes only Status
    rec = foundation.ConfigureReportingResponseRecord(
        foundation.Status.SUCCESS, 0x00, 0xAABB
    )
    assert rec.serialize() == b"\x00"
    rec.status = foundation.Status.UNREPORTABLE_ATTRIBUTE
    assert rec.serialize()[0:1] == foundation.Status.UNREPORTABLE_ATTRIBUTE.serialize()
    assert rec.serialize()[1:] == b"\x00\xbb\xaa"


def test_status_undef():
    data = b"\xff"
    extra = b"extra"

    status, rest = foundation.Status.deserialize(data + extra)
    assert rest == extra
    assert status == 0xFF
    assert status.value == 0xFF
    assert status.name == "undefined_0xff"
    assert isinstance(status, foundation.Status)


def test_frame_control():
    """Test FrameControl frame_type."""
    extra = b"abcd\xaa\x55"
    frc, rest = foundation.FrameControl.deserialize(b"\x00" + extra)
    assert rest == extra
    assert frc.frame_type == foundation.FrameType.GLOBAL_COMMAND

    frc, rest = foundation.FrameControl.deserialize(b"\x01" + extra)
    assert rest == extra
    assert frc.frame_type == foundation.FrameType.CLUSTER_COMMAND

    r = repr(frc)
    assert isinstance(r, str)


def test_frame_control_general():
    frc = foundation.FrameControl.general(
        direction=foundation.Direction.Client_to_Server
    )
    assert frc.is_cluster is False
    assert frc.is_general is True
    data = frc.serialize()

    assert data == b"\x00"
    assert not frc.is_manufacturer_specific
    frc = frc.replace(is_manufacturer_specific=False)
    assert frc.serialize() == b"\x00"
    frc = frc.replace(is_manufacturer_specific=True)
    assert frc.serialize() == b"\x04"

    frc = foundation.FrameControl.general(
        direction=foundation.Direction.Client_to_Server
    )
    assert frc.direction == foundation.Direction.Client_to_Server
    assert frc.serialize() == b"\x00"
    frc = frc.replace(direction=foundation.Direction.Server_to_Client)
    assert frc.serialize() == b"\x08"
    assert (
        foundation.FrameControl.general(
            direction=foundation.Direction.Server_to_Client
        ).serialize()
        == b"\x18"
    )

    frc = foundation.FrameControl.general(
        direction=foundation.Direction.Client_to_Server
    )
    assert not frc.disable_default_response
    assert frc.serialize() == b"\x00"
    frc = frc.replace(disable_default_response=False)
    assert frc.serialize() == b"\x00"
    frc = frc.replace(disable_default_response=True)
    assert frc.serialize() == b"\x10"


def test_frame_control_cluster():
    frc = foundation.FrameControl.cluster(
        direction=foundation.Direction.Client_to_Server
    )
    assert frc.is_cluster is True
    assert frc.is_general is False
    data = frc.serialize()

    assert data == b"\x01"
    assert not frc.is_manufacturer_specific
    frc = frc.replace(is_manufacturer_specific=False)
    assert frc.serialize() == b"\x01"
    frc = frc.replace(is_manufacturer_specific=True)
    assert frc.serialize() == b"\x05"

    frc = foundation.FrameControl.cluster(
        direction=foundation.Direction.Client_to_Server
    )
    assert frc.direction == foundation.Direction.Client_to_Server
    assert frc.serialize() == b"\x01"
    frc = frc.replace(direction=foundation.Direction.Client_to_Server)
    assert frc.serialize() == b"\x01"
    frc = frc.replace(direction=foundation.Direction.Server_to_Client)
    assert frc.serialize() == b"\x09"
    assert (
        foundation.FrameControl.cluster(
            direction=foundation.Direction.Server_to_Client
        ).serialize()
        == b"\x19"
    )

    frc = foundation.FrameControl.cluster(
        direction=foundation.Direction.Client_to_Server
    )
    assert not frc.disable_default_response
    assert frc.serialize() == b"\x01"
    frc = frc.replace(disable_default_response=False)
    assert frc.serialize() == b"\x01"
    frc = frc.replace(disable_default_response=True)
    assert frc.serialize() == b"\x11"


def test_frame_header():
    """Test frame header deserialization."""
    data = b"\x1c_\x11\xc0\n"
    extra = b"\xaa\xaa\x55\x55"
    hdr, rest = foundation.ZCLHeader.deserialize(data + extra)

    assert rest == extra
    assert hdr.command_id == 0x0A
    assert hdr.direction == foundation.Direction.Server_to_Client
    assert hdr.manufacturer == 0x115F
    assert hdr.tsn == 0xC0

    assert hdr.serialize() == data

    # check no manufacturer
    hdr.frame_control = hdr.frame_control.replace(is_manufacturer_specific=False)
    assert hdr.serialize() == b"\x18\xc0\n"

    r = repr(hdr)
    assert isinstance(r, str)


def test_frame_header_general():
    """Test frame header general command."""
    (tsn, cmd_id, manufacturer) = (0x11, 0x15, 0x3344)

    hdr = foundation.ZCLHeader.general(tsn, cmd_id, manufacturer)
    assert hdr.frame_control.frame_type == foundation.FrameType.GLOBAL_COMMAND
    assert hdr.command_id == cmd_id
    assert hdr.tsn == tsn
    assert hdr.manufacturer == manufacturer
    assert hdr.frame_control.is_manufacturer_specific

    hdr.manufacturer = None
    assert hdr.manufacturer is None
    assert not hdr.frame_control.is_manufacturer_specific


def test_frame_header_cluster():
    """Test frame header cluster command."""
    (tsn, cmd_id, manufacturer) = (0x11, 0x16, 0x3344)

    hdr = foundation.ZCLHeader.cluster(
        tsn=tsn, command_id=cmd_id, manufacturer=manufacturer
    )
    assert hdr.frame_control.frame_type == foundation.FrameType.CLUSTER_COMMAND
    assert hdr.command_id == cmd_id
    assert hdr.tsn == tsn
    assert hdr.manufacturer == manufacturer
    assert hdr.frame_control.is_manufacturer_specific

    hdr.manufacturer = None
    assert hdr.manufacturer is None
    assert not hdr.frame_control.is_manufacturer_specific


def test_frame_header_disable_manufacturer_id():
    """Test frame header manufacturer ID can be disabled with NO_MANUFACTURER_ID."""

    hdr = foundation.ZCLHeader.cluster(tsn=123, command_id=0x12, manufacturer=None)
    assert hdr.manufacturer is None
    hdr.manufacturer = 0x1234
    assert hdr.manufacturer == 0x1234

    hdr.manufacturer = foundation.ZCLHeader.NO_MANUFACTURER_ID
    assert hdr.manufacturer is None

    hdr2 = foundation.ZCLHeader.cluster(
        tsn=123, command_id=0x12, manufacturer=foundation.ZCLHeader.NO_MANUFACTURER_ID
    )
    assert hdr2.manufacturer is None


def test_attribute_report():
    a = foundation.AttributeReportingConfig()
    a.direction = 0x01
    a.attrid = 0xAA55
    a.timeout = 900
    b = foundation.AttributeReportingConfig(a)
    assert a.attrid == b.attrid
    assert a.direction == b.direction
    assert a.timeout == b.timeout


def test_pytype_to_datatype_derived_enums():
    """Test pytype_to_datatype_id lookup for derived enums."""

    class e_1(t.enum8):
        pass

    class e_2(t.enum8):
        pass

    class e_3(t.enum16):
        pass

    enum8_id = foundation.DataType.from_python_type(t.enum8)
    enum16_id = foundation.DataType.from_python_type(t.enum16)

    assert foundation.DataType.from_python_type(e_1) == enum8_id
    assert foundation.DataType.from_python_type(e_2) == enum8_id
    assert foundation.DataType.from_python_type(e_3) == enum16_id
    assert foundation.DataType.from_python_type(e_2) == enum8_id
    assert foundation.DataType.from_python_type(e_3) == enum16_id


def test_pytype_to_datatype_derived_bitmaps():
    """Test pytype_to_datatype_id lookup for derived enums."""

    class b_1(t.bitmap8):
        pass

    class b_2(t.bitmap8):
        pass

    class b_3(t.bitmap16):
        pass

    bitmap8_id = foundation.DataType.from_python_type(t.bitmap8)
    bitmap16_id = foundation.DataType.from_python_type(t.bitmap16)

    assert foundation.DataType.from_python_type(b_1) == bitmap8_id
    assert foundation.DataType.from_python_type(b_2) == bitmap8_id
    assert foundation.DataType.from_python_type(b_3) == bitmap16_id
    assert foundation.DataType.from_python_type(b_2) == bitmap8_id
    assert foundation.DataType.from_python_type(b_3) == bitmap16_id


def test_ptype_to_datatype_lvlist():
    """Test pytype for Structure."""

    data = b"L\x06\x00\x10\x00!\xce\x0b!\xa8\x01$\x00\x00\x00\x00\x00!\xbdJ ]"
    extra = b"\xaa\x55extra\x00"

    result, rest = foundation.TypeValue.deserialize(data + extra)
    assert rest == extra
    assert (
        foundation.DataType.from_python_type(result.value.__class__)
        == foundation.DataType.struct
    )
    assert (
        foundation.DataType.from_python_type(foundation.ZCLStructure)
        == foundation.DataType.struct
    )

    class _Similar(t.LVList, item_type=foundation.TypeValue, length_type=t.uint16_t):
        pass

    assert foundation.DataType.from_python_type(_Similar) == foundation.DataType.unk


def test_ptype_to_datatype_notype():
    """Test pytype for NoData."""

    class ZigpyUnknown:
        pass

    assert foundation.DataType.from_python_type(ZigpyUnknown) == foundation.DataType.unk


def test_write_attrs_response_deserialize():
    """Test deserialization."""

    data = b"\x00"
    extra = b"\xaa\x55"
    r, rest = foundation.WriteAttributesResponse.deserialize(data + extra)
    assert len(r) == 1
    assert r[0].status == foundation.Status.SUCCESS
    assert rest == extra

    data = b"\x86\x34\x12\x87\x35\x12"
    r, rest = foundation.WriteAttributesResponse.deserialize(data + extra)
    assert len(r) == 2
    assert rest == extra
    assert r[0].status == foundation.Status.UNSUPPORTED_ATTRIBUTE
    assert r[0].attrid == 0x1234
    assert r[1].status == foundation.Status.INVALID_VALUE
    assert r[1].attrid == 0x1235


@pytest.mark.parametrize(
    ("attributes", "data"),
    [
        ({4: 0, 5: 0, 3: 0}, b"\x00"),
        ({4: 0, 5: 0, 3: 0x86}, b"\x86\x03\x00"),
        ({4: 0x87, 5: 0, 3: 0x86}, b"\x87\x04\x00\x86\x03\x00"),
        ({4: 0x87, 5: 0x86, 3: 0x86}, b"\x87\x04\x00\x86\x05\x00\x86\x03\x00"),
    ],
)
def test_write_attrs_response_serialize(attributes, data):
    """Test WriteAttributes Response serialization."""

    r = foundation.WriteAttributesResponse()
    for attr_id, status in attributes.items():
        rec = foundation.WriteAttributesStatusRecord()
        rec.status = status
        rec.attrid = attr_id
        r.append(rec)

    assert r.serialize() == data


def test_configure_reporting_response_deserialize():
    """Test deserialization."""

    data = b"\x00"
    r, rest = foundation.ConfigureReportingResponse.deserialize(data)
    assert len(r) == 1
    assert r[0].status == foundation.Status.SUCCESS
    assert r[0].direction is None
    assert r[0].attrid is None
    assert rest == b""

    data = b"\x00"
    extra = b"\x01\xaa\x55"
    r, rest = foundation.ConfigureReportingResponse.deserialize(data + extra)
    assert len(r) == 1
    assert r[0].status == foundation.Status.SUCCESS
    assert r[0].direction == foundation.ReportingDirection.ReceiveReports
    assert r[0].attrid == 0x55AA
    assert rest == b""

    data = b"\x86\x01\x34\x12\x87\x01\x35\x12"
    r, rest = foundation.ConfigureReportingResponse.deserialize(data)
    assert len(r) == 2
    assert rest == b""
    assert r[0].status == foundation.Status.UNSUPPORTED_ATTRIBUTE
    assert r[0].attrid == 0x1234
    assert r[1].status == foundation.Status.INVALID_VALUE
    assert r[1].attrid == 0x1235

    with pytest.raises(ValueError):
        foundation.ConfigureReportingResponse.deserialize(data + extra)


def test_configure_reporting_response_serialize_empty():
    r = foundation.ConfigureReportingResponse()

    # An empty configure reporting response doesn't make sense
    with pytest.raises(ValueError):
        r.serialize()


@pytest.mark.parametrize(
    ("attributes", "data"),
    [
        ({4: 0, 5: 0, 3: 0}, b"\x00"),
        ({4: 0, 5: 0, 3: 0x86}, b"\x86\x01\x03\x00"),
        ({4: 0x87, 5: 0, 3: 0x86}, b"\x87\x01\x04\x00\x86\x01\x03\x00"),
        (
            {4: 0x87, 5: 0x86, 3: 0x86},
            b"\x87\x01\x04\x00\x86\x01\x05\x00\x86\x01\x03\x00",
        ),
    ],
)
def test_configure_reporting_response_serialize(attributes, data):
    """Test ConfigureReporting Response serialization."""

    r = foundation.ConfigureReportingResponse()
    for attr_id, status in attributes.items():
        rec = foundation.ConfigureReportingResponseRecord()
        rec.status = status
        rec.direction = 0x01
        rec.attrid = attr_id
        r.append(rec)

    assert r.serialize() == data


def test_status_enum():
    """Test Status enums chaining."""
    status_names = [e.name for e in foundation.Status]
    aps_names = [e.name for e in t.APSStatus]
    nwk_names = [e.name for e in t.NWKStatus]
    mac_names = [e.name for e in t.MACStatus]

    status = foundation.Status(0x98)
    assert status.name in status_names
    assert status.name not in aps_names
    assert status.name not in nwk_names
    assert status.name not in mac_names

    status = foundation.Status(0xAE)
    assert status.name not in status_names
    assert status.name in aps_names
    assert status.name not in nwk_names
    assert status.name not in mac_names

    status = foundation.Status(0xD0)
    assert status.name not in status_names
    assert status.name not in aps_names
    assert status.name in nwk_names
    assert status.name not in mac_names

    status = foundation.Status(0xE9)
    assert status.name not in status_names
    assert status.name not in aps_names
    assert status.name not in nwk_names
    assert status.name in mac_names

    status = foundation.Status(0xFF)
    assert status.name not in status_names
    assert status.name not in aps_names
    assert status.name not in nwk_names
    assert status.name not in mac_names
    assert status.name == "undefined_0xff"


def test_schema():
    """Test schema parameter parsing"""

    bad_s = foundation.ZCLCommandDef(
        id=0x12,
        name="test",
        schema={
            "uh oh": t.uint16_t,
        },
        direction=foundation.Direction.Client_to_Server,
    )

    with pytest.raises(ValueError):
        bad_s.with_compiled_schema()

    s = foundation.ZCLCommandDef(
        id=0x12,
        name="test",
        schema={
            "foo": t.uint8_t,
            "bar?": t.uint16_t,
            "baz?": t.uint8_t,
        },
        direction=foundation.Direction.Client_to_Server,
    )
    s = s.with_compiled_schema()

    str(s)

    assert s.schema.foo.type is t.uint8_t
    assert not s.schema.foo.optional

    assert s.schema.bar.type is t.uint16_t
    assert s.schema.bar.optional

    assert s.schema.baz.type is t.uint8_t
    assert s.schema.baz.optional

    assert "test" in str(s) and "direction=<Direction.Client_to_Server" in str(s)

    for kwargs, value in [
        ({"foo": 1}, b"\x01"),
        ({"foo": 1, "bar": 2}, b"\x01\x02\x00"),
        ({"foo": 1, "bar": 2, "baz": 3}, b"\x01\x02\x00\x03"),
    ]:
        assert s.schema(**kwargs) == s.schema(*kwargs.values())
        assert s.schema(**kwargs).serialize() == value
        assert s.schema.deserialize(value) == (s.schema(**kwargs), b"")

    assert issubclass(s.schema, tuple)


def test_command_schema_error_on_tuple():
    """Test schema throwing an exception when a tuple is passed instead of a dict."""

    cmd_def = foundation.ZCLCommandDef(
        id=0x12,
        name="test",
        schema=(t.uint16_t,),
        direction=foundation.Direction.Client_to_Server,
    )

    with pytest.raises(ValueError):
        cmd_def.with_compiled_schema()


def test_zcl_attribute_definition():
    a = foundation.ZCLAttributeDef(
        id=0x1234,
        name="test",
        type=t.uint16_t,
        access="rw",
    )

    assert "0x1234" in str(a)
    assert "'test'" in str(a)
    assert "uint16_t" in str(a)
    assert not a.is_manufacturer_specific  # default
    assert a.access == (
        foundation.ZCLAttributeAccess.Read | foundation.ZCLAttributeAccess.Write
    )

    with pytest.raises(ValueError):
        a.replace(access="x")

    assert a.replace(access="w").access == foundation.ZCLAttributeAccess.Write


def test_invalid_command_def_name():
    command = foundation.ZCLCommandDef(
        id=0x12,
        name="test",
        schema={
            "foo": t.uint8_t,
        },
        direction=foundation.Direction.Client_to_Server,
    )

    with pytest.raises(ValueError):
        command.replace(name="bad name")

    with pytest.raises(ValueError):
        command.replace(name="123name")


def test_invalid_attribute_def_name():
    attr = foundation.ZCLAttributeDef(
        id=0x1234,
        name="test",
        type=t.uint16_t,
    )

    with pytest.raises(ValueError):
        attr.replace(name="bad name")

    with pytest.raises(ValueError):
        attr.replace(name="123name")


def test_zcl_attribute_access():
    A = foundation.ZCLAttributeAccess

    assert A.from_str("") == (A.NONE)
    assert A.from_str("r") == (A.Read)
    assert A.from_str("r*w") == (A.Read | A.Write_Optional)
    assert A.from_str("r*wp") == (A.Read | A.Write_Optional | A.Report)
    assert A.from_str("rp") == (A.Read | A.Report)
    assert A.from_str("rps") == (A.Read | A.Report | A.Scene)
    assert A.from_str("rs") == (A.Read | A.Scene)
    assert A.from_str("rw") == (A.Read | A.Write)
    assert A.from_str("rwp") == (A.Read | A.Write | A.Report)
    assert A.from_str("rws") == (A.Read | A.Write | A.Scene)

    with pytest.raises(ValueError):
        A.from_str("q")


def test_attribute_command_iteration():
    class Commands1(foundation.BaseCommandDefs):
        command1 = foundation.ZCLCommandDef(
            id=0x12,
            name="test",
            schema={
                "foo": t.uint8_t,
            },
            direction=foundation.Direction.Client_to_Server,
        )

    class Commands2(Commands1):
        command2 = foundation.ZCLCommandDef(
            id=0x12,
            name="test2",
            schema={
                "foo": t.uint8_t,
            },
            direction=foundation.Direction.Client_to_Server,
        )

    assert list(Commands1) == [Commands1.command1]
    assert list(Commands2) == [Commands2.command1, Commands2.command2]


def test_attribute_definition_backwards_compat():
    assert foundation.ZCLAttributeDef(0x1234, t.uint8_t) == foundation.ZCLAttributeDef(
        id=0x1234, type=t.uint8_t
    )
    assert foundation.ZCLAttributeDef("name", t.uint8_t) == foundation.ZCLAttributeDef(
        name="name", type=t.uint8_t
    )


def test_command_definition_backwards_compat():
    assert foundation.ZCLCommandDef(0x12, {}) == foundation.ZCLCommandDef(
        id=0x12, schema={}
    )
    assert foundation.ZCLCommandDef("name", {}) == foundation.ZCLCommandDef(
        name="name", schema={}
    )


def test_array():
    orig_data = data = bytes.fromhex(
        "183c010100004841040006000d0106000206010d0206000206020d0306000206030d04060002"
    )
    hdr, data = foundation.ZCLHeader.deserialize(data)

    command = foundation.GENERAL_COMMANDS[hdr.command_id]
    rsp, rest = command.schema.deserialize(data)

    assert rest == b""

    assert rsp.status_records == [
        foundation.ReadAttributeRecord(
            attrid=0x0001,
            status=foundation.Status.SUCCESS,
            value=foundation.Array(
                type=foundation.DataTypeId.octstr,
                value=t.LVList[t.LVBytes, t.uint16_t](
                    [
                        b"\x00\r\x01\x06\x00\x02",
                        b"\x01\r\x02\x06\x00\x02",
                        b"\x02\r\x03\x06\x00\x02",
                        b"\x03\r\x04\x06\x00\x02",
                    ]
                ),
            ),
        )
    ]

    assert orig_data == hdr.serialize() + rsp.serialize()