zbus_xml 5.2.0

API to handle D-Bus introspection XML
Documentation
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
use std::error::Error;

use zbus_xml::{Arg, ArgDirection, Interface, Node, PropertyAccess};
use zvariant::Signature;

#[test]
fn serde() -> Result<(), Box<dyn Error>> {
    let example = include_str!("data/sample_object0.xml");
    let node_r = Node::from_reader(example.as_bytes())?;
    let node = Node::try_from(example)?;
    assert_eq!(node, node_r);
    assert_eq!(node.interfaces().len(), 1);
    assert_eq!(node.interfaces()[0].methods().len(), 3);
    assert_eq!(
        node.interfaces()[0].methods()[0].args()[0]
            .direction()
            .unwrap(),
        ArgDirection::In
    );
    assert_eq!(node.nodes().len(), 4);

    let node_str: Node<'_> = example.try_into()?;
    assert_eq!(node_str.interfaces().len(), 1);
    assert_eq!(node_str.nodes().len(), 4);

    let mut writer = Vec::with_capacity(128);
    node.to_writer(&mut writer).unwrap();

    // Round-trip: the written document parses back to an equal tree.
    let written = String::from_utf8(writer)?;
    let reparsed = Node::try_from(written.as_str())?;
    assert_eq!(node, reparsed);

    Ok(())
}

#[test]
fn invalid_arg_type() {
    let input = include_str!("data/invalid_arg_type.xml");
    assert!(matches!(
        Node::try_from(input),
        Err(zbus_xml::Error::Variant(_))
    ));
}

#[test]
fn multi_complete_arg_type() -> Result<(), Box<dyn Error>> {
    let input = r#"
        <!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
        "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
        <node>
            <interface name="org.test.testinterface">
                <method name="testmethod">
                    <arg name="testarg" direction="out" type="tt"/>
                </method>
            </interface>
        </node>
    "#;

    let node = Node::try_from(input)?;
    let arg = &node.interfaces()[0].methods()[0].args()[0];
    let Signature::Structure(fields) = arg.ty().inner() else {
        panic!("expected `tt` to parse as a structure");
    };

    assert_eq!(fields.len(), 2);
    assert_eq!(fields.get(0), Some(&Signature::U64));
    assert_eq!(fields.get(1), Some(&Signature::U64));

    Ok(())
}

#[test]
fn escaped_attributes() -> Result<(), Box<dyn Error>> {
    let input = r#"
        <node>
            <interface name="org.test.testinterface">
                <annotation name="org.test.Escapes" value="&lt;b&gt; &amp; &quot;q&quot; &apos;a&apos; &#65;&#x42;"/>
            </interface>
        </node>
    "#;

    let node = Node::try_from(input)?;
    let annotation = &node.interfaces()[0].annotations()[0];
    assert_eq!(annotation.value(), r#"<b> & "q" 'a' AB"#);

    // Escaping survives a write/parse round-trip.
    let mut writer = Vec::new();
    node.to_writer(&mut writer)?;
    let written = String::from_utf8(writer)?;
    let reparsed = Node::try_from(written.as_str())?;
    assert_eq!(node, reparsed);

    Ok(())
}

#[test]
fn attribute_whitespace_normalization() -> Result<(), Box<dyn Error>> {
    // Literal whitespace in attribute values is normalized to spaces, while whitespace escaped
    // through character references is kept.
    let input = "<node>\n  <interface name=\"org.test.testinterface\">\n    \
                 <annotation name=\"org.test.Ws\" value=\"a\nb\tc\r&#10;&#9;&#13;d\"/>\n  \
                 </interface>\n</node>";

    let node = Node::try_from(input)?;
    let annotation = &node.interfaces()[0].annotations()[0];
    assert_eq!(annotation.value(), "a b c \n\t\rd");

    // The writer escapes whitespace so it survives normalization by any parser.
    let mut writer = Vec::new();
    node.to_writer(&mut writer)?;
    let written = String::from_utf8(writer)?;
    assert!(written.contains("a b c &#10;&#9;&#13;d"));
    let reparsed = Node::try_from(written.as_str())?;
    assert_eq!(node, reparsed);

    Ok(())
}

#[test]
fn crlf_normalizes_to_single_space() -> Result<(), Box<dyn Error>> {
    // A literal CRLF is a single line ending, so attribute-value normalization collapses it to
    // one space (not two); a lone CR or LF likewise yields one space each.
    let input = "<node name=\"a\r\nb\rc\nd\"/>";
    let node = Node::try_from(input)?;
    assert_eq!(node.name(), Some("a b c d"));

    Ok(())
}

#[test]
fn many_attributes() -> Result<(), Box<dyn Error>> {
    // Elements with many attributes parse fine — duplicate detection falls back from a linear
    // scan to a set past a threshold — and duplicates are still caught beyond that threshold.
    let attrs: String = (0..100).map(|i| format!(" a{i}=\"{i}\"")).collect();
    assert!(Node::try_from(format!("<node{attrs}/>").as_str()).is_ok());
    assert!(matches!(
        Node::try_from(format!("<node{attrs} a50=\"dup\"/>").as_str()),
        Err(zbus_xml::Error::Xml(_))
    ));

    Ok(())
}

#[test]
fn doctype_with_quoted_literals() -> Result<(), Box<dyn Error>> {
    // `>` and brackets inside DOCTYPE quoted literals must not terminate the declaration.
    let input = r#"
        <!DOCTYPE node SYSTEM "weird>literal[with]brackets">
        <node>
            <interface name="org.test.testinterface"/>
        </node>
    "#;

    let node = Node::try_from(input)?;
    assert_eq!(node.interfaces().len(), 1);

    Ok(())
}

#[test]
fn ignores_unknown_elements_and_text() -> Result<(), Box<dyn Error>> {
    // Documents in the wild carry foreign elements (with text content, CDATA and comments) that
    // must be skipped, e.g. Telepathy's `tp:docstring`.
    let input = r#"
        <?xml version="1.0" encoding="UTF-8"?>
        <node xmlns:tp="http://telepathy.freedesktop.org/wiki/DbusSpec#extensions-v0">
            <tp:docstring>Some documentation.</tp:docstring>
            <interface name="org.test.testinterface">
                <!-- a comment -->
                <method name="testmethod">
                    <tp:docstring>More <tp:em>documentation</tp:em>.</tp:docstring>
                    <arg name="testarg" direction="out" type="s">
                        <tp:docstring><![CDATA[Even </more> documentation.]]></tp:docstring>
                    </arg>
                </method>
            </interface>
        </node>
    "#;

    let node = Node::try_from(input)?;
    assert_eq!(node.interfaces().len(), 1);
    let method = &node.interfaces()[0].methods()[0];
    assert_eq!(method.args().len(), 1);
    assert_eq!(method.args()[0].name(), Some("testarg"));

    Ok(())
}

/// The expected shape of an argument: its `name`, signature and `direction`.
type ArgSpec = (Option<&'static str>, &'static str, Option<ArgDirection>);

const IN: Option<ArgDirection> = Some(ArgDirection::In);
const OUT: Option<ArgDirection> = Some(ArgDirection::Out);
/// A signal argument has no direction.
const NONE: Option<ArgDirection> = None;

/// Look up an interface by name, panicking with a helpful message if it is absent.
fn interface<'n, 'a>(node: &'n Node<'a>, name: &str) -> &'n Interface<'a> {
    node.interfaces()
        .iter()
        .find(|iface| iface.name() == name)
        .unwrap_or_else(|| panic!("interface `{name}` not found"))
}

/// Assert that `args` matches `expected` exactly — count, and every name, signature and
/// direction.
fn assert_args(context: &str, args: &[Arg], expected: &[ArgSpec]) {
    assert_eq!(
        args.len(),
        expected.len(),
        "{context}: expected {} arg(s), got {}",
        expected.len(),
        args.len(),
    );
    for (i, (arg, &(name, ty, direction))) in args.iter().zip(expected).enumerate() {
        assert_eq!(arg.name(), name, "{context}: arg {i} name");
        assert!(
            arg.ty() == ty,
            "{context}: arg {i} type: expected `{ty}`, got `{}`",
            arg.ty().to_string(),
        );
        assert_eq!(arg.direction(), direction, "{context}: arg {i} direction");
    }
}

/// Assert that `iface`'s methods are exactly `expected` (name and full argument list each), in
/// no particular order.
fn assert_methods(iface: &Interface<'_>, expected: &[(&str, &[ArgSpec])]) {
    assert_eq!(
        iface.methods().len(),
        expected.len(),
        "{}: method count",
        iface.name(),
    );
    for (name, args) in expected {
        let method = iface
            .methods()
            .iter()
            .find(|m| m.name() == *name)
            .unwrap_or_else(|| panic!("method `{}.{name}` not found", iface.name()));
        assert_args(&format!("{}.{name}", iface.name()), method.args(), args);
    }
}

/// Assert that `iface`'s signals are exactly `expected` (name and full argument list each).
fn assert_signals(iface: &Interface<'_>, expected: &[(&str, &[ArgSpec])]) {
    assert_eq!(
        iface.signals().len(),
        expected.len(),
        "{}: signal count",
        iface.name(),
    );
    for (name, args) in expected {
        let signal = iface
            .signals()
            .iter()
            .find(|s| s.name() == *name)
            .unwrap_or_else(|| panic!("signal `{}.{name}` not found", iface.name()));
        assert_args(&format!("{}.{name}", iface.name()), signal.args(), args);
    }
}

/// Assert that `iface`'s properties are exactly `expected` (name, signature and access each).
fn assert_properties(iface: &Interface<'_>, expected: &[(&str, &str, PropertyAccess)]) {
    assert_eq!(
        iface.properties().len(),
        expected.len(),
        "{}: property count",
        iface.name(),
    );
    for &(name, ty, access) in expected {
        let property = iface
            .properties()
            .iter()
            .find(|p| p.name() == name)
            .unwrap_or_else(|| panic!("property `{}.{name}` not found", iface.name()));
        assert!(
            property.ty() == ty,
            "{}.{name}: type: expected `{ty}`, got `{}`",
            iface.name(),
            property.ty().to_string(),
        );
        assert_eq!(property.access(), access, "{}.{name}: access", iface.name());
    }
}

/// Introspection XML captured verbatim from live services (see `data/real_world/README.md`),
/// covering the XML flavors produced by sd-bus, libdbus and GDBus.
const REAL_WORLD_DATA: &[(&str, &str)] = &[
    (
        "dbus_daemon",
        include_str!("data/real_world/dbus_daemon.xml"),
    ),
    (
        "systemd1_manager",
        include_str!("data/real_world/systemd1_manager.xml"),
    ),
    (
        "systemd1_scope_unit",
        include_str!("data/real_world/systemd1_scope_unit.xml"),
    ),
    (
        "systemd1_unit_list",
        include_str!("data/real_world/systemd1_unit_list.xml"),
    ),
    ("hostname1", include_str!("data/real_world/hostname1.xml")),
    ("timedate1", include_str!("data/real_world/timedate1.xml")),
    ("locale1", include_str!("data/real_world/locale1.xml")),
    ("login1", include_str!("data/real_world/login1.xml")),
    ("network1", include_str!("data/real_world/network1.xml")),
    (
        "polkit1_authority",
        include_str!("data/real_world/polkit1_authority.xml"),
    ),
    ("packagekit", include_str!("data/real_world/packagekit.xml")),
    (
        "dconf_writer",
        include_str!("data/real_world/dconf_writer.xml"),
    ),
];

#[test]
fn real_world_data() -> Result<(), Box<dyn Error>> {
    for (name, xml) in REAL_WORLD_DATA {
        // `h` (file descriptor) signatures are only supported by zvariant on Unix, so documents
        // containing them (e.g. from systemd-logind) don't parse on other platforms.
        if cfg!(not(unix)) && xml.contains(r#"type="h""#) {
            assert!(
                matches!(Node::try_from(*xml), Err(zbus_xml::Error::Variant(_))),
                "{name}: expected fd signatures to be rejected on non-Unix"
            );
            continue;
        }

        let node = Node::try_from(*xml).map_err(|e| format!("{name}: {e}"))?;
        let node_r = Node::from_reader(xml.as_bytes()).map_err(|e| format!("{name}: {e}"))?;
        assert_eq!(node, node_r, "{name}: reader and str parses differ");

        // Every service implements the standard Introspectable interface.
        assert!(
            node.interfaces()
                .iter()
                .any(|i| i.name() == "org.freedesktop.DBus.Introspectable"),
            "{name}: missing org.freedesktop.DBus.Introspectable"
        );

        // The document survives a write/parse round-trip unchanged.
        let mut writer = Vec::new();
        node.to_writer(&mut writer)?;
        let written = String::from_utf8(writer)?;
        let reparsed = Node::try_from(written.as_str()).map_err(|e| format!("{name}: {e}"))?;
        assert_eq!(node, reparsed, "{name}: round-trip changed the tree");
    }

    Ok(())
}

#[test]
fn real_world_dbus_daemon() -> Result<(), Box<dyn Error>> {
    // The dbus-daemon document is small and stable, so check its main interface exhaustively:
    // every method, signal and property, with every argument's name, signature and direction.
    let node = Node::try_from(include_str!("data/real_world/dbus_daemon.xml"))?;
    let dbus = interface(&node, "org.freedesktop.DBus");

    assert_methods(
        dbus,
        &[
            ("Hello", &[(None, "s", OUT)]),
            (
                "RequestName",
                &[(None, "s", IN), (None, "u", IN), (None, "u", OUT)],
            ),
            ("ReleaseName", &[(None, "s", IN), (None, "u", OUT)]),
            (
                "StartServiceByName",
                &[(None, "s", IN), (None, "u", IN), (None, "u", OUT)],
            ),
            ("UpdateActivationEnvironment", &[(None, "a{ss}", IN)]),
            ("NameHasOwner", &[(None, "s", IN), (None, "b", OUT)]),
            ("ListNames", &[(None, "as", OUT)]),
            ("ListActivatableNames", &[(None, "as", OUT)]),
            ("AddMatch", &[(None, "s", IN)]),
            ("RemoveMatch", &[(None, "s", IN)]),
            ("GetNameOwner", &[(None, "s", IN), (None, "s", OUT)]),
            ("ListQueuedOwners", &[(None, "s", IN), (None, "as", OUT)]),
            (
                "GetConnectionUnixUser",
                &[(None, "s", IN), (None, "u", OUT)],
            ),
            (
                "GetConnectionUnixProcessID",
                &[(None, "s", IN), (None, "u", OUT)],
            ),
            (
                "GetAdtAuditSessionData",
                &[(None, "s", IN), (None, "ay", OUT)],
            ),
            (
                "GetConnectionSELinuxSecurityContext",
                &[(None, "s", IN), (None, "ay", OUT)],
            ),
            (
                "GetConnectionAppArmorSecurityContext",
                &[(None, "s", IN), (None, "s", OUT)],
            ),
            ("ReloadConfig", &[]),
            ("GetId", &[(None, "s", OUT)]),
            (
                "GetConnectionCredentials",
                &[(None, "s", IN), (None, "a{sv}", OUT)],
            ),
        ],
    );

    assert_signals(
        dbus,
        &[
            (
                "NameOwnerChanged",
                &[(None, "s", NONE), (None, "s", NONE), (None, "s", NONE)],
            ),
            ("NameLost", &[(None, "s", NONE)]),
            ("NameAcquired", &[(None, "s", NONE)]),
            ("ActivatableServicesChanged", &[]),
        ],
    );

    assert_properties(
        dbus,
        &[
            ("Features", "as", PropertyAccess::Read),
            ("Interfaces", "as", PropertyAccess::Read),
        ],
    );

    // GDBus-style named arguments on the standard Properties interface round-trip too.
    let properties = interface(&node, "org.freedesktop.DBus.Properties");
    assert_signals(
        properties,
        &[(
            "PropertiesChanged",
            &[
                (Some("interface_name"), "s", NONE),
                (Some("changed_properties"), "a{sv}", NONE),
                (Some("invalidated_properties"), "as", NONE),
            ],
        )],
    );

    Ok(())
}

#[test]
fn real_world_systemd() -> Result<(), Box<dyn Error>> {
    // The manager document contains `h` (file descriptor) signatures (e.g.
    // `DumpByFileDescriptor`), which zvariant only supports on Unix.
    if cfg!(unix) {
        let node = Node::try_from(include_str!("data/real_world/systemd1_manager.xml"))?;
        let manager = interface(&node, "org.freedesktop.systemd1.Manager");

        // sd-bus emits named, directioned arguments; check a representative set fully.
        assert_args(
            "Manager.GetUnit",
            manager
                .methods()
                .iter()
                .find(|m| m.name() == "GetUnit")
                .expect("GetUnit method")
                .args(),
            &[(Some("name"), "s", IN), (Some("unit"), "o", OUT)],
        );
        assert_args(
            "Manager.StartUnit",
            manager
                .methods()
                .iter()
                .find(|m| m.name() == "StartUnit")
                .expect("StartUnit method")
                .args(),
            &[
                (Some("name"), "s", IN),
                (Some("mode"), "s", IN),
                (Some("job"), "o", OUT),
            ],
        );
        assert_args(
            "Manager.UnitNew",
            manager
                .signals()
                .iter()
                .find(|s| s.name() == "UnitNew")
                .expect("UnitNew signal")
                .args(),
            &[(Some("id"), "s", NONE), (Some("unit"), "o", NONE)],
        );
        assert_args(
            "Manager.JobNew",
            manager
                .signals()
                .iter()
                .find(|s| s.name() == "JobNew")
                .expect("JobNew signal")
                .args(),
            &[
                (Some("id"), "u", NONE),
                (Some("job"), "o", NONE),
                (Some("unit"), "s", NONE),
            ],
        );

        let version = manager
            .properties()
            .iter()
            .find(|p| p.name() == "Version")
            .expect("Version property");
        assert!(version.ty() == "s", "Version type");
        assert_eq!(version.access(), PropertyAccess::Read);
        assert!(version.access().read() && !version.access().write());
        // sd-bus annotates properties with their change-signalling behavior.
        let emits_changed = version
            .annotations()
            .iter()
            .find(|a| a.name() == "org.freedesktop.DBus.Property.EmitsChangedSignal")
            .expect("EmitsChangedSignal annotation");
        assert_eq!(emits_changed.value(), "const");

        // Writable properties exercise the readwrite access path.
        for name in ["LogLevel", "LogTarget"] {
            let property = manager
                .properties()
                .iter()
                .find(|p| p.name() == name)
                .unwrap_or_else(|| panic!("Manager.{name} property"));
            assert!(property.ty() == "s", "Manager.{name}: type");
            assert_eq!(property.access(), PropertyAccess::ReadWrite);
            assert!(property.access().read() && property.access().write());
        }
    }

    // The unit-list object carries the children of /org/freedesktop/systemd1/unit as named,
    // interface-less sub-nodes.
    let node = Node::try_from(include_str!("data/real_world/systemd1_unit_list.xml"))?;
    assert!(!node.nodes().is_empty());
    let init_scope = node
        .nodes()
        .iter()
        .find(|n| n.name() == Some("init_2escope"))
        .expect("init_2escope node");
    assert!(init_scope.interfaces().is_empty());
    assert!(init_scope.nodes().is_empty());

    // A scope unit implements the generic Unit interface and the type-specific Scope interface,
    // both carrying properties.
    let node = Node::try_from(include_str!("data/real_world/systemd1_scope_unit.xml"))?;
    for name in [
        "org.freedesktop.systemd1.Unit",
        "org.freedesktop.systemd1.Scope",
    ] {
        let iface = interface(&node, name);
        assert!(!iface.properties().is_empty(), "{name}: has properties");
    }
    // The generic Unit interface exposes the well-known Id/ActiveState string properties.
    let unit = interface(&node, "org.freedesktop.systemd1.Unit");
    for name in ["Id", "ActiveState"] {
        let property = unit
            .properties()
            .iter()
            .find(|p| p.name() == name)
            .unwrap_or_else(|| panic!("Unit.{name} property"));
        assert!(property.ty() == "s", "Unit.{name}: type");
        assert!(property.access().read(), "Unit.{name}: readable");
    }

    Ok(())
}

#[test]
fn malformed_documents() {
    for input in [
        // Empty document.
        "",
        // Unclosed root element.
        "<node>",
        // Mismatched closing tag.
        "<node><interface name=\"org.test.testinterface\"></node>",
        // Unterminated comment.
        "<node><!-- comment </node>",
        // Missing attribute value quotes.
        "<node name=foo/>",
        // Unknown entity.
        "<node name=\"&unknown;\"/>",
        // Character references to characters invalid in XML.
        "<node name=\"&#0;\"/>",
        "<node name=\"&#x1F;\"/>",
        // Signed character references.
        "<node name=\"&#+65;\"/>",
        "<node name=\"&#x+41;\"/>",
        // Duplicate attribute.
        "<node name=\"a\" name=\"b\"/>",
        // Missing whitespace between attributes.
        "<node name=\"a\"name=\"b\"/>",
    ] {
        assert!(matches!(
            Node::try_from(input),
            Err(zbus_xml::Error::Xml(_))
        ));
    }

    // Missing required attribute.
    let input = "<node><interface name=\"org.test.testinterface\">\
                 <property name=\"foo\" type=\"s\"/></interface></node>";
    assert!(matches!(
        Node::try_from(input),
        Err(zbus_xml::Error::Xml(_))
    ));

    // Invalid interface name.
    let input = "<node><interface name=\"not a valid name\"/></node>";
    assert!(matches!(
        Node::try_from(input),
        Err(zbus_xml::Error::Name(_))
    ));
}

#[test]
fn error_position() {
    // Errors in attribute values point at the offending reference, not past the value.
    let input = r#"<node name="abc&unknown;def"/>"#;
    let Err(zbus_xml::Error::Xml(e)) = Node::try_from(input) else {
        panic!("expected an XML error");
    };
    assert_eq!(e.position(), input.find('&').unwrap());

    // A duplicate attribute points at the second (offending) name.
    let input = r#"<node name="a" name="b"/>"#;
    let Err(zbus_xml::Error::Xml(e)) = Node::try_from(input) else {
        panic!("expected an XML error");
    };
    assert_eq!(e.position(), input.rfind("name").unwrap());

    // A missing required attribute points at the element name.
    let input = "<node><interface name=\"org.test.I\">\
                 <property name=\"p\" type=\"s\"/></interface></node>";
    let Err(zbus_xml::Error::Xml(e)) = Node::try_from(input) else {
        panic!("expected an XML error");
    };
    assert_eq!(e.position(), input.find("property").unwrap());
}

#[test]
fn deeply_nested_documents() -> Result<(), Box<dyn Error>> {
    // The parser iterates over the axes where a document can nest arbitrarily deep, so any
    // depth up to the cap parses even on a small stack. (Recursing instead overflows even
    // multi-MiB stacks well before the cap in debug builds, whose stack frames are large.)
    let deep_nodes = format!("{}{}", "<node>".repeat(1024), "</node>".repeat(1024));
    let deep_foreign = format!(
        "<node><interface name=\"org.test.testinterface\">{}{}</interface></node>",
        "<x>".repeat(1022),
        "</x>".repeat(1022),
    );

    std::thread::Builder::new()
        .stack_size(512 * 1024)
        .spawn(move || {
            let node = Node::try_from(deep_nodes.as_str()).unwrap();
            let mut depth = 1;
            let mut node = &node;
            while let [child] = node.nodes() {
                node = child;
                depth += 1;
            }
            assert_eq!(depth, 1024);

            Node::try_from(deep_foreign.as_str()).unwrap();
        })?
        .join()
        .expect("parsing deeply nested documents must not overflow the stack");

    // One level past the cap is rejected cleanly, on both nesting axes.
    let too_deep = format!("{}{}", "<node>".repeat(1025), "</node>".repeat(1025));
    assert!(matches!(
        Node::try_from(too_deep.as_str()),
        Err(zbus_xml::Error::Xml(_))
    ));
    let too_deep_foreign = format!(
        "<node><interface name=\"org.test.I\">{}{}</interface></node>",
        "<x>".repeat(1025),
        "</x>".repeat(1025),
    );
    assert!(matches!(
        Node::try_from(too_deep_foreign.as_str()),
        Err(zbus_xml::Error::Xml(_))
    ));

    Ok(())
}

#[test]
fn io_error() {
    // A failing reader surfaces as `Error::Io`.
    struct FailingReader;
    impl std::io::Read for FailingReader {
        fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
            Err(std::io::Error::other("boom"))
        }
    }
    assert!(matches!(
        Node::from_reader(FailingReader),
        Err(zbus_xml::Error::Io(_))
    ));
}

#[test]
fn invalid_enum_attributes() -> Result<(), Box<dyn Error>> {
    // An invalid `direction` or `access` value is a clean XML error.
    let bad_direction = "<node><interface name=\"org.test.I\">\
                         <method name=\"M\"><arg type=\"s\" direction=\"sideways\"/></method>\
                         </interface></node>";
    assert!(matches!(
        Node::try_from(bad_direction),
        Err(zbus_xml::Error::Xml(_))
    ));

    let bad_access = "<node><interface name=\"org.test.I\">\
                      <property name=\"P\" type=\"s\" access=\"rw\"/></interface></node>";
    assert!(matches!(
        Node::try_from(bad_access),
        Err(zbus_xml::Error::Xml(_))
    ));

    // A write-only property exercises the `PropertyAccess::Write` arm.
    let write_only = "<node><interface name=\"org.test.I\">\
                      <property name=\"P\" type=\"s\" access=\"write\"/></interface></node>";
    let node = Node::try_from(write_only)?;
    let access = node.interfaces()[0].properties()[0].access();
    assert_eq!(access, PropertyAccess::Write);
    assert!(access.write() && !access.read());

    Ok(())
}

#[test]
fn invalid_member_names() {
    // An invalid method or signal name is an `Error::Name` (like the interface-name case in
    // `malformed_documents`), exercising the same validated-name path for both members.
    for input in [
        "<node><interface name=\"org.test.I\"><method name=\"not valid\"/></interface></node>",
        "<node><interface name=\"org.test.I\"><signal name=\"not valid\"/></interface></node>",
    ] {
        assert!(matches!(
            Node::try_from(input),
            Err(zbus_xml::Error::Name(_))
        ));
    }
}

#[test]
fn root_element_name_is_ignored() -> Result<(), Box<dyn Error>> {
    // The root element's name is not checked, for compatibility with servers that don't name it
    // `node` (and with how the previous quick-xml-based versions behaved).
    let node = Node::try_from("<weirdroot><interface name=\"org.test.I\"/></weirdroot>")?;
    assert_eq!(node.interfaces().len(), 1);
    assert_eq!(node.interfaces()[0].name(), "org.test.I");

    Ok(())
}

#[test]
fn docstrings() -> Result<(), Box<dyn Error>> {
    // Telepathy-style docstrings are captured on interfaces, members and args, verbatim
    // (including markup and references) but with the surrounding whitespace trimmed.
    let input = r#"
        <node xmlns:tp="http://telepathy.freedesktop.org/wiki/DbusSpec#extensions-v0">
            <interface name="org.test.testinterface">
                <tp:docstring>
                    <p>An interface, closely modeled after the
                    <strong>MPRIS</strong> ones &amp; documented inline.</p>
                    <tp:rationale>
                        <p>With a nested rationale.</p>
                    </tp:rationale>
                </tp:docstring>
                <method name="TestMethod">
                    <tp:docstring>Does the thing.</tp:docstring>
                    <arg name="testarg" direction="in" type="s">
                        <tp:docstring>The thing to do.</tp:docstring>
                    </arg>
                    <arg name="undocumented" direction="out" type="u"/>
                </method>
                <signal name="TestSignal">
                    <tp:docstring>Emitted when the thing was done.</tp:docstring>
                    <arg name="testarg" type="s">
                        <tp:docstring>The thing that was done.</tp:docstring>
                    </arg>
                </signal>
                <property name="TestProperty" type="b" access="read">
                    <tp:docstring>Whether the thing has been done.</tp:docstring>
                </property>
                <property name="EmptyDocstring" type="b" access="read">
                    <tp:docstring>   </tp:docstring>
                    <tp:docstring/>
                </property>
            </interface>
        </node>
    "#;

    let node = Node::try_from(input)?;
    let interface = &node.interfaces()[0];
    let docstring = interface.docstring().expect("interface docstring");
    assert!(docstring.starts_with("<p>An interface,"));
    assert!(docstring.contains("<strong>MPRIS</strong> ones &amp; documented inline.</p>"));
    assert!(docstring.contains("<tp:rationale>"));
    assert!(docstring.ends_with("</tp:rationale>"));

    let method = &interface.methods()[0];
    assert_eq!(method.docstring(), Some("Does the thing."));
    assert_eq!(method.args()[0].docstring(), Some("The thing to do."));
    assert_eq!(method.args()[1].docstring(), None);

    let signal = &interface.signals()[0];
    assert_eq!(signal.docstring(), Some("Emitted when the thing was done."));
    assert_eq!(
        signal.args()[0].docstring(),
        Some("The thing that was done.")
    );

    assert_eq!(
        interface.properties()[0].docstring(),
        Some("Whether the thing has been done.")
    );
    // Whitespace-only and self-closing docstrings count as absent.
    assert_eq!(interface.properties()[1].docstring(), None);

    Ok(())
}

#[test]
fn unsupported_element_warnings() -> Result<(), Box<dyn Error>> {
    // Elements that have no place in the introspection format are skipped with a warning.
    let input = r#"
        <node xmlns:tp="http://telepathy.freedesktop.org/wiki/DbusSpec#extensions-v0">
            <tp:flags name="Media_Caps" value-prefix="Cap" type="u">
                <tp:flag suffix="Audio" value="1"/>
            </tp:flags>
            <interface name="org.test.testinterface">
                <tp:docstring>Documented, not warned about.</tp:docstring>
                <method name="TestMethod">
                    <tp:possible-errors/>
                </method>
                <annotation name="org.test.Annotation" value="v">
                    <unexpected/>
                </annotation>
            </interface>
        </node>
    "#;

    let (node, warnings) = Node::from_reader_with_warnings(input.as_bytes())?;
    assert_eq!(node.interfaces().len(), 1);
    assert_eq!(
        node.interfaces()[0].docstring(),
        Some("Documented, not warned about.")
    );

    let elements: Vec<_> = warnings.iter().map(|w| w.element()).collect();
    assert_eq!(elements, ["tp:flags", "tp:possible-errors", "unexpected"]);
    // Nested children of a skipped element (`tp:flag`) are not warned about separately, and
    // warnings point at the start of the offending element.
    assert_eq!(warnings[0].position(), input.find("<tp:flags").unwrap());
    assert!(warnings[0].message().contains("`<tp:flags>`"));
    assert!(warnings[0].to_string().contains("`<tp:flags>`"));

    // The warning-less API still just ignores everything.
    assert_eq!(Node::try_from(input)?, node);

    Ok(())
}

#[test]
fn telepathy_type_definitions() -> Result<(), Box<dyn Error>> {
    let input = r#"
        <node xmlns:tp="http://telepathy.freedesktop.org/wiki/DbusSpec#extensions-v0">
            <tp:simple-type name="Playlist_Id" type="o" array-name="Playlist_Id_List">
                <tp:docstring>Unique playlist identifier.</tp:docstring>
            </tp:simple-type>
            <interface name="org.test.testinterface">
                <tp:enum name="Playlist_Ordering" type="s">
                    <tp:docstring>The way to order playlists.</tp:docstring>
                    <tp:enumvalue suffix="Alphabetical" value="Alphabetical">
                        <tp:docstring>Alphabetical ordering, ascending.</tp:docstring>
                    </tp:enumvalue>
                    <tp:enumvalue suffix="UserDefined" value="User"/>
                </tp:enum>
                <tp:struct name="Playlist" array-name="Playlist_List">
                    <tp:docstring>A data structure describing a playlist.</tp:docstring>
                    <tp:member type="o" tp:type="Playlist_Id" name="Id">
                        <tp:docstring>A unique identifier.</tp:docstring>
                    </tp:member>
                    <tp:member type="s" name="Name"/>
                </tp:struct>
                <tp:mapping name="String_Variant_Map">
                    <tp:member type="s" name="Key"/>
                    <tp:member type="v" name="Value"/>
                </tp:mapping>
                <method name="GetPlaylists">
                    <arg direction="out" name="playlists" type="a(os)" tp:type="Playlist[]"/>
                </method>
                <property name="Orderings" type="as" tp:type="Playlist_Ordering[]" access="read"/>
            </interface>
        </node>
    "#;

    let (node, warnings) = Node::from_reader_with_warnings(input.as_bytes())?;
    assert_eq!(warnings, []);

    use zbus_xml::telepathy::TypeDef;

    // Node-level definitions.
    let [TypeDef::SimpleType(id)] = node.telepathy_types() else {
        panic!("expected a simple type on the node");
    };
    assert_eq!(id.name(), "Playlist_Id");
    assert_eq!(*id.ty().inner(), Signature::ObjectPath);
    assert_eq!(id.docstring(), Some("Unique playlist identifier."));

    // Interface-level definitions.
    let interface = &node.interfaces()[0];
    let [
        TypeDef::Enum(ordering),
        TypeDef::Struct(playlist),
        TypeDef::Mapping(map),
    ] = interface.telepathy_types()
    else {
        panic!("expected enum, struct and mapping on the interface");
    };

    assert_eq!(ordering.name(), "Playlist_Ordering");
    assert_eq!(*ordering.ty().inner(), Signature::Str);
    assert_eq!(ordering.docstring(), Some("The way to order playlists."));
    assert_eq!(ordering.values().len(), 2);
    assert_eq!(ordering.values()[0].suffix(), "Alphabetical");
    assert_eq!(ordering.values()[0].value(), "Alphabetical");
    assert_eq!(
        ordering.values()[0].docstring(),
        Some("Alphabetical ordering, ascending.")
    );
    assert_eq!(ordering.values()[1].suffix(), "UserDefined");
    assert_eq!(ordering.values()[1].value(), "User");
    assert_eq!(ordering.values()[1].docstring(), None);

    assert_eq!(playlist.name(), "Playlist");
    assert_eq!(
        playlist.docstring(),
        Some("A data structure describing a playlist.")
    );
    assert_eq!(playlist.members().len(), 2);
    assert_eq!(playlist.members()[0].name(), "Id");
    assert_eq!(*playlist.members()[0].ty().inner(), Signature::ObjectPath);
    assert_eq!(playlist.members()[0].tp_type(), Some("Playlist_Id"));
    assert_eq!(
        playlist.members()[0].docstring(),
        Some("A unique identifier.")
    );
    assert_eq!(playlist.members()[1].tp_type(), None);
    assert_eq!(playlist.signature().to_string(), "(os)");

    assert_eq!(map.name(), "String_Variant_Map");
    assert_eq!(map.key().name(), "Key");
    assert_eq!(map.value().name(), "Value");
    assert_eq!(map.signature().to_string(), "a{sv}");

    // `tp:type` references on args and properties.
    let method = &interface.methods()[0];
    assert_eq!(method.args()[0].tp_type(), Some("Playlist[]"));
    assert_eq!(
        interface.properties()[0].tp_type(),
        Some("Playlist_Ordering[]")
    );

    Ok(())
}

#[test]
fn malformed_telepathy_type_definitions() -> Result<(), Box<dyn Error>> {
    // A type definition that cannot be parsed doesn't fail the document; it is skipped with a
    // warning.
    let input = r#"
        <node xmlns:tp="http://telepathy.freedesktop.org/wiki/DbusSpec#extensions-v0">
            <tp:simple-type type="o"/>
            <tp:simple-type name="Bad_Type" type="!"/>
            <tp:simple-type name="Empty_Type" type=""/>
            <tp:enum name="No_Type">
                <tp:enumvalue suffix="A" value="0"/>
            </tp:enum>
            <tp:enum name="Bad_Value" type="u">
                <tp:enumvalue value="0"/>
            </tp:enum>
            <tp:struct name="Empty"/>
            <tp:struct name="Bad_Member">
                <tp:member name="No_Type_Either"/>
            </tp:struct>
            <tp:mapping name="Not_A_Pair">
                <tp:member type="s" name="Key"/>
            </tp:mapping>
            <tp:mapping name="Bad_Key">
                <tp:member type="v" name="Key"/>
                <tp:member type="s" name="Value"/>
            </tp:mapping>
            <interface name="org.test.testinterface"/>
        </node>
    "#;

    let (node, warnings) = Node::from_reader_with_warnings(input.as_bytes())?;
    assert_eq!(node.telepathy_types(), []);
    assert_eq!(node.interfaces().len(), 1);

    let messages: Vec<_> = warnings.iter().map(|w| w.message()).collect();
    assert_eq!(
        messages,
        [
            "malformed element `<tp:simple-type>` ignored: missing attribute `name`",
            "malformed element `<tp:simple-type>` ignored: invalid signature in `type`",
            "malformed element `<tp:simple-type>` ignored: invalid signature in `type`",
            "malformed element `<tp:enum>` ignored: missing attribute `type`",
            "malformed element `<tp:enum>` ignored: an enumvalue is missing its `suffix` or \
             `value` attribute",
            "malformed element `<tp:struct>` ignored: no members",
            "malformed element `<tp:struct>` ignored: a member is missing its `name` or `type` \
             attribute, or has an invalid signature",
            "malformed element `<tp:mapping>` ignored: expected exactly 2 members",
            "malformed element `<tp:mapping>` ignored: the key is not a basic type",
        ]
    );
    assert_eq!(
        warnings[0].position(),
        input.find("<tp:simple-type").unwrap()
    );

    // An empty struct member type composes into an invalid struct signature, so it must be
    // rejected too.
    let input = r#"
        <node xmlns:tp="http://telepathy.freedesktop.org/wiki/DbusSpec#extensions-v0">
            <tp:struct name="S"><tp:member name="m" type=""/></tp:struct>
        </node>
    "#;
    let (node, warnings) = Node::from_reader_with_warnings(input.as_bytes())?;
    assert_eq!(node.telepathy_types(), []);
    assert_eq!(warnings.len(), 1);
    assert!(warnings[0].message().contains("`<tp:struct>`"));

    Ok(())
}

#[test]
fn unknown_children_of_telepathy_definitions() -> Result<(), Box<dyn Error>> {
    // Unknown elements are warned about wherever they appear, including inside the leaf
    // elements of type definitions.
    let input = r#"
        <node xmlns:tp="http://telepathy.freedesktop.org/wiki/DbusSpec#extensions-v0">
            <tp:simple-type name="Token" type="s">
                <tp:added version="0.1"/>
            </tp:simple-type>
            <interface name="org.test.testinterface">
                <tp:enum name="Level" type="u">
                    <tp:enumvalue suffix="Low" value="0">
                        <tp:changed version="0.2"/>
                    </tp:enumvalue>
                </tp:enum>
                <tp:struct name="Pair">
                    <tp:member name="first" type="s">
                        <bogus/>
                    </tp:member>
                    <tp:member name="second" type="s"/>
                </tp:struct>
            </interface>
        </node>
    "#;

    let (node, warnings) = Node::from_reader_with_warnings(input.as_bytes())?;
    // The definitions themselves still parse fine.
    assert_eq!(node.telepathy_types().len(), 1);
    assert_eq!(node.interfaces()[0].telepathy_types().len(), 2);

    let elements: Vec<_> = warnings.iter().map(|w| w.element()).collect();
    assert_eq!(elements, ["tp:added", "tp:changed", "bogus"]);

    Ok(())
}