tests.rs

  1// Copyright (c) 2020 lumi <lumi@pew.im>
  2// Copyright (c) 2020 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
  3// Copyright (c) 2020 Bastien Orivel <eijebong+minidom@bananium.fr>
  4// Copyright (c) 2020 Astro <astro@spaceboyz.net>
  5// Copyright (c) 2020 Maxime “pep” Buquet <pep@bouah.net>
  6// Copyright (c) 2020 Yue Liu <amznyue@amazon.com>
  7// Copyright (c) 2020 Matt Bilker <me@mbilker.us>
  8//
  9// This Source Code Form is subject to the terms of the Mozilla Public
 10// License, v. 2.0. If a copy of the MPL was not distributed with this
 11// file, You can obtain one at http://mozilla.org/MPL/2.0/.
 12
 13use crate::element::Element;
 14use crate::error::Error;
 15
 16use quick_xml::Reader;
 17
 18const TEST_STRING: &'static str = r#"<root xmlns="root_ns" a="b" xml:lang="en">meow<child c="d"/><child xmlns="child_ns" d="e" xml:lang="fr"/>nya</root>"#;
 19
 20fn build_test_tree() -> Element {
 21    let mut root = Element::builder("root", "root_ns")
 22        .attr("xml:lang", "en")
 23        .attr("a", "b")
 24        .build();
 25    root.append_text_node("meow");
 26    let child = Element::builder("child", "root_ns").attr("c", "d").build();
 27    root.append_child(child);
 28    let other_child = Element::builder("child", "child_ns")
 29        .attr("d", "e")
 30        .attr("xml:lang", "fr")
 31        .build();
 32    root.append_child(other_child);
 33    root.append_text_node("nya");
 34    root
 35}
 36
 37#[test]
 38fn reader_works() {
 39    let mut reader = Reader::from_str(TEST_STRING);
 40    assert_eq!(
 41        Element::from_reader(&mut reader).unwrap(),
 42        build_test_tree()
 43    );
 44}
 45
 46#[test]
 47fn reader_deduplicate_prefixes() {
 48    // The reader shouldn't complain that "child" doesn't have a namespace. It should reuse the
 49    // parent ns with the same prefix.
 50    let _: Element = r#"<root xmlns="ns1"><child/></root>"#.parse().unwrap();
 51    let _: Element = r#"<p1:root xmlns:p1="ns1"><p1:child/></p1:root>"#.parse().unwrap();
 52    let _: Element = r#"<root xmlns="ns1"><child xmlns:p1="ns2"><p1:grandchild/></child></root>"#
 53        .parse()
 54        .unwrap();
 55
 56    match r#"<p1:root xmlns:p1="ns1"><child/></p1:root>"#.parse::<Element>() {
 57        Err(Error::MissingNamespace) => (),
 58        Err(err) => panic!("No or wrong error: {:?}", err),
 59        Ok(elem) => panic!(
 60            "Got Element: {}; was expecting Error::MissingNamespace",
 61            String::from(&elem)
 62        ),
 63    }
 64}
 65
 66#[test]
 67fn reader_no_deduplicate_sibling_prefixes() {
 68    // The reader shouldn't reuse the sibling's prefixes
 69    match r#"<root xmlns="ns1"><p1:child1 xmlns:p1="ns2"/><p1:child2/></root>"#.parse::<Element>() {
 70        Err(Error::MissingNamespace) => (),
 71        Err(err) => panic!("No or wrong error: {:?}", err),
 72        Ok(elem) => panic!(
 73            "Got Element:\n{:?}\n{}\n; was expecting Error::MissingNamespace",
 74            elem,
 75            String::from(&elem)
 76        ),
 77    }
 78}
 79
 80#[test]
 81fn test_real_data() {
 82    let correction = Element::builder("replace", "urn:xmpp:message-correct:0").build();
 83    let body = Element::builder("body", "jabber:client").build();
 84    let message = Element::builder("message", "jabber:client")
 85        .append(body)
 86        .append(correction)
 87        .build();
 88    let stream = Element::builder("stream", "http://etherx.jabber.org/streams")
 89        .prefix(
 90            Some(String::from("stream")),
 91            "http://etherx.jabber.org/streams",
 92        )
 93        .unwrap()
 94        .prefix(None, "jabber:client")
 95        .unwrap()
 96        .append(message)
 97        .build();
 98    println!("{}", String::from(&stream));
 99
100    let jid = Element::builder("jid", "urn:xmpp:presence:0").build();
101    let nick = Element::builder("nick", "urn:xmpp:presence:0").build();
102    let mix = Element::builder("mix", "urn:xmpp:presence:0")
103        .append(jid)
104        .append(nick)
105        .build();
106    let show = Element::builder("show", "jabber:client").build();
107    let status = Element::builder("status", "jabber:client").build();
108    let presence = Element::builder("presence", "jabber:client")
109        .append(show)
110        .append(status)
111        .append(mix)
112        .build();
113    let item = Element::builder("item", "http://jabber.org/protocol/pubsub")
114        .append(presence)
115        .build();
116    let items = Element::builder("items", "http://jabber.org/protocol/pubsub")
117        .append(item)
118        .build();
119    let pubsub = Element::builder("pubsub", "http://jabber.org/protocol/pubsub")
120        .append(items)
121        .build();
122    let iq = Element::builder("iq", "jabber:client")
123        .append(pubsub)
124        .build();
125    let stream = Element::builder("stream", "http://etherx.jabber.org/streams")
126        .prefix(
127            Some(String::from("stream")),
128            "http://etherx.jabber.org/streams",
129        )
130        .unwrap()
131        .prefix(None, "jabber:client")
132        .unwrap()
133        .append(iq)
134        .build();
135
136    println!("{}", String::from(&stream));
137}
138
139#[test]
140fn writer_works() {
141    let root = build_test_tree();
142    let mut writer = Vec::new();
143    {
144        root.write_to(&mut writer).unwrap();
145    }
146    assert_eq!(String::from_utf8(writer).unwrap(), TEST_STRING);
147}
148
149#[test]
150fn writer_with_decl_works() {
151    let root = build_test_tree();
152    let mut writer = Vec::new();
153    {
154        root.write_to_decl(&mut writer).unwrap();
155    }
156    let result = format!(r#"<?xml version="1.0" encoding="utf-8"?>{}"#, TEST_STRING);
157    assert_eq!(String::from_utf8(writer).unwrap(), result);
158}
159
160#[test]
161fn writer_with_prefix() {
162    let root = Element::builder("root", "ns1")
163        .prefix(Some(String::from("p1")), "ns1")
164        .unwrap()
165        .prefix(None, "ns2")
166        .unwrap()
167        .build();
168    assert_eq!(
169        String::from(&root),
170        r#"<p1:root xmlns="ns2" xmlns:p1="ns1"/>"#,
171    );
172}
173
174#[test]
175fn writer_no_prefix_namespace() {
176    let root = Element::builder("root", "ns1").build();
177    // TODO: Note that this isn't exactly equal to a None prefix. it's just that the None prefix is
178    // the most obvious when it's not already used. Maybe fix tests so that it only checks that the
179    // prefix used equals the one declared for the namespace.
180    assert_eq!(String::from(&root), r#"<root xmlns="ns1"/>"#);
181}
182
183#[test]
184fn writer_no_prefix_namespace_child() {
185    let child = Element::builder("child", "ns1").build();
186    let root = Element::builder("root", "ns1").append(child).build();
187    // TODO: Same remark as `writer_no_prefix_namespace`.
188    assert_eq!(String::from(&root), r#"<root xmlns="ns1"><child/></root>"#);
189
190    let child = Element::builder("child", "ns2")
191        .prefix(None, "ns3")
192        .unwrap()
193        .build();
194    let root = Element::builder("root", "ns1").append(child).build();
195    // TODO: Same remark as `writer_no_prefix_namespace`.
196    assert_eq!(
197        String::from(&root),
198        r#"<root xmlns="ns1"><ns0:child xmlns:ns0="ns2" xmlns="ns3"/></root>"#
199    );
200}
201
202#[test]
203fn writer_prefix_namespace_child() {
204    let child = Element::builder("child", "ns1").build();
205    let root = Element::builder("root", "ns1")
206        .prefix(Some(String::from("p1")), "ns1")
207        .unwrap()
208        .append(child)
209        .build();
210    assert_eq!(
211        String::from(&root),
212        r#"<p1:root xmlns:p1="ns1"><p1:child/></p1:root>"#
213    );
214}
215
216#[test]
217fn writer_with_prefix_deduplicate() {
218    let child = Element::builder("child", "ns1")
219        // .prefix(Some(String::from("p1")), "ns1")
220        .build();
221    let root = Element::builder("root", "ns1")
222        .prefix(Some(String::from("p1")), "ns1")
223        .unwrap()
224        .prefix(None, "ns2")
225        .unwrap()
226        .append(child)
227        .build();
228    assert_eq!(
229        String::from(&root),
230        r#"<p1:root xmlns="ns2" xmlns:p1="ns1"><p1:child/></p1:root>"#,
231    );
232
233    // Ensure descendants don't just reuse ancestors' prefixes that have been shadowed in between
234    let grandchild = Element::builder("grandchild", "ns1").build();
235    let child = Element::builder("child", "ns2").append(grandchild).build();
236    let root = Element::builder("root", "ns1").append(child).build();
237    assert_eq!(
238        String::from(&root),
239        r#"<root xmlns="ns1"><child xmlns="ns2"><grandchild xmlns="ns1"/></child></root>"#,
240    );
241}
242
243#[test]
244fn writer_escapes_attributes() {
245    let root = Element::builder("root", "ns1")
246        .attr("a", "\"Air\" quotes")
247        .build();
248    let mut writer = Vec::new();
249    {
250        root.write_to(&mut writer).unwrap();
251    }
252    assert_eq!(
253        String::from_utf8(writer).unwrap(),
254        r#"<root xmlns="ns1" a="&quot;Air&quot; quotes"/>"#
255    );
256}
257
258#[test]
259fn writer_escapes_text() {
260    let root = Element::builder("root", "ns1").append("<3").build();
261    let mut writer = Vec::new();
262    {
263        root.write_to(&mut writer).unwrap();
264    }
265    assert_eq!(
266        String::from_utf8(writer).unwrap(),
267        r#"<root xmlns="ns1">&lt;3</root>"#
268    );
269}
270
271#[test]
272fn builder_works() {
273    let elem = Element::builder("a", "b")
274        .attr("c", "d")
275        .append(Element::builder("child", "b"))
276        .append("e")
277        .build();
278    assert_eq!(elem.name(), "a");
279    assert_eq!(elem.ns(), "b".to_owned());
280    assert_eq!(elem.attr("c"), Some("d"));
281    assert_eq!(elem.attr("x"), None);
282    assert_eq!(elem.text(), "e");
283    assert!(elem.has_child("child", "b"));
284    assert!(elem.is("a", "b"));
285}
286
287#[test]
288fn children_iter_works() {
289    let root = build_test_tree();
290    let mut iter = root.children();
291    assert!(iter.next().unwrap().is("child", "root_ns"));
292    assert!(iter.next().unwrap().is("child", "child_ns"));
293    assert_eq!(iter.next(), None);
294}
295
296#[test]
297fn get_child_works() {
298    let root = build_test_tree();
299    assert_eq!(root.get_child("child", "inexistent_ns"), None);
300    assert_eq!(root.get_child("not_a_child", "root_ns"), None);
301    assert!(root
302        .get_child("child", "root_ns")
303        .unwrap()
304        .is("child", "root_ns"));
305    assert!(root
306        .get_child("child", "child_ns")
307        .unwrap()
308        .is("child", "child_ns"));
309    assert_eq!(
310        root.get_child("child", "root_ns").unwrap().attr("c"),
311        Some("d")
312    );
313    assert_eq!(
314        root.get_child("child", "child_ns").unwrap().attr("d"),
315        Some("e")
316    );
317}
318
319#[test]
320fn namespace_propagation_works() {
321    let mut root = Element::builder("root", "root_ns").build();
322    let mut child = Element::bare("child", "root_ns");
323    let grandchild = Element::bare("grandchild", "root_ns");
324    child.append_child(grandchild);
325    root.append_child(child);
326
327    assert_eq!(root.get_child("child", "root_ns").unwrap().ns(), root.ns());
328    assert_eq!(
329        root.get_child("child", "root_ns")
330            .unwrap()
331            .get_child("grandchild", "root_ns")
332            .unwrap()
333            .ns(),
334        root.ns()
335    );
336}
337
338#[test]
339fn two_elements_with_same_arguments_different_order_are_equal() {
340    let elem1: Element = "<a b='a' c='' xmlns='ns1'/>".parse().unwrap();
341    let elem2: Element = "<a c='' b='a' xmlns='ns1'/>".parse().unwrap();
342    assert_eq!(elem1, elem2);
343
344    let elem1: Element = "<a b='a' c='' xmlns='ns1'/>".parse().unwrap();
345    let elem2: Element = "<a c='d' b='a' xmlns='ns1'/>".parse().unwrap();
346    assert_ne!(elem1, elem2);
347}
348
349#[test]
350fn namespace_attributes_works() {
351    let mut reader = Reader::from_str(TEST_STRING);
352    let root = Element::from_reader(&mut reader).unwrap();
353    assert_eq!("en", root.attr("xml:lang").unwrap());
354    assert_eq!(
355        "fr",
356        root.get_child("child", "child_ns")
357            .unwrap()
358            .attr("xml:lang")
359            .unwrap()
360    );
361}
362
363#[test]
364fn wrongly_closed_elements_error() {
365    let elem1 = "<a xmlns='ns1'></b>".parse::<Element>();
366    assert!(elem1.is_err());
367    let elem1 = "<a xmlns='ns1'></c></a>".parse::<Element>();
368    assert!(elem1.is_err());
369    let elem1 = "<a xmlns='ns1'><c xmlns='ns1'><d xmlns='ns1'/></c></a>".parse::<Element>();
370    assert!(elem1.is_ok());
371}
372
373#[test]
374fn namespace_simple() {
375    let elem: Element = "<message xmlns='jabber:client'/>".parse().unwrap();
376    assert_eq!(elem.name(), "message");
377    assert_eq!(elem.ns(), "jabber:client".to_owned());
378}
379
380#[test]
381fn namespace_prefixed() {
382    let elem: Element = "<stream:features xmlns:stream='http://etherx.jabber.org/streams'/>"
383        .parse()
384        .unwrap();
385    assert_eq!(elem.name(), "features");
386    assert_eq!(elem.ns(), "http://etherx.jabber.org/streams".to_owned(),);
387}
388
389#[test]
390fn namespace_inherited_simple() {
391    let elem: Element = "<stream xmlns='jabber:client'><message xmlns='jabber:client' /></stream>"
392        .parse()
393        .unwrap();
394    assert_eq!(elem.name(), "stream");
395    assert_eq!(elem.ns(), "jabber:client".to_owned());
396    let child = elem.children().next().unwrap();
397    assert_eq!(child.name(), "message");
398    assert_eq!(child.ns(), "jabber:client".to_owned());
399}
400
401#[test]
402fn namespace_inherited_prefixed1() {
403    let elem: Element = "<stream:features xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client'><message xmlns='jabber:client' /></stream:features>"
404        .parse().unwrap();
405    assert_eq!(elem.name(), "features");
406    assert_eq!(elem.ns(), "http://etherx.jabber.org/streams".to_owned(),);
407    let child = elem.children().next().unwrap();
408    assert_eq!(child.name(), "message");
409    assert_eq!(child.ns(), "jabber:client".to_owned());
410}
411
412#[test]
413fn namespace_inherited_prefixed2() {
414    let elem: Element = "<stream xmlns='http://etherx.jabber.org/streams' xmlns:jabber='jabber:client'><jabber:message xmlns:jabber='jabber:client' /></stream>"
415        .parse().unwrap();
416    assert_eq!(elem.name(), "stream");
417    assert_eq!(elem.ns(), "http://etherx.jabber.org/streams".to_owned(),);
418    let child = elem.children().next().unwrap();
419    assert_eq!(child.name(), "message");
420    assert_eq!(child.ns(), "jabber:client".to_owned());
421}
422
423#[test]
424fn fail_comments() {
425    let elem: Result<Element, Error> = "<foo xmlns='ns1'><!-- bar --></foo>".parse();
426    match elem {
427        Err(Error::NoComments) => (),
428        _ => panic!(),
429    };
430}
431
432#[test]
433fn xml_error() {
434    match "<a xmlns='ns1'></b>".parse::<Element>() {
435        Err(crate::error::Error::XmlError(_)) => (),
436        err => panic!("No or wrong error: {:?}", err),
437    }
438
439    match "<a xmlns='ns1'></".parse::<Element>() {
440        Err(crate::error::Error::XmlError(_)) => (),
441        err => panic!("No or wrong error: {:?}", err),
442    }
443}
444
445#[test]
446fn invalid_element_error() {
447    match "<a:b:c>".parse::<Element>() {
448        Err(crate::error::Error::InvalidElement) => (),
449        err => panic!("No or wrong error: {:?}", err),
450    }
451}
452
453#[test]
454fn missing_namespace_error() {
455    match "<a/>".parse::<Element>() {
456        Err(crate::error::Error::MissingNamespace) => (),
457        err => panic!("No or wrong error: {:?}", err),
458    }
459}