1// Copyright (c) 2017 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use try_from::TryFrom;
8
9use minidom::Element;
10
11use error::Error;
12
13use ns;
14
15/// Structure representing an `<attention xmlns='urn:xmpp:attention:0'/>` element.
16#[derive(Debug, Clone)]
17pub struct Attention;
18
19impl TryFrom<Element> for Attention {
20 type Err = Error;
21
22 fn try_from(elem: Element) -> Result<Attention, Error> {
23 if !elem.is("attention", ns::ATTENTION) {
24 return Err(Error::ParseError("This is not an attention element."));
25 }
26 for _ in elem.children() {
27 return Err(Error::ParseError("Unknown child in attention element."));
28 }
29 for _ in elem.attrs() {
30 return Err(Error::ParseError("Unknown attribute in attention element."));
31 }
32 Ok(Attention)
33 }
34}
35
36impl From<Attention> for Element {
37 fn from(_: Attention) -> Element {
38 Element::builder("attention")
39 .ns(ns::ATTENTION)
40 .build()
41 }
42}
43
44#[cfg(test)]
45mod tests {
46 use super::*;
47
48 #[test]
49 fn test_simple() {
50 let elem: Element = "<attention xmlns='urn:xmpp:attention:0'/>".parse().unwrap();
51 Attention::try_from(elem).unwrap();
52 }
53
54 #[test]
55 fn test_invalid_child() {
56 let elem: Element = "<attention xmlns='urn:xmpp:attention:0'><coucou/></attention>".parse().unwrap();
57 let error = Attention::try_from(elem).unwrap_err();
58 let message = match error {
59 Error::ParseError(string) => string,
60 _ => panic!(),
61 };
62 assert_eq!(message, "Unknown child in attention element.");
63 }
64
65 #[test]
66 fn test_invalid_attribute() {
67 let elem: Element = "<attention xmlns='urn:xmpp:attention:0' coucou=''/>".parse().unwrap();
68 let error = Attention::try_from(elem).unwrap_err();
69 let message = match error {
70 Error::ParseError(string) => string,
71 _ => panic!(),
72 };
73 assert_eq!(message, "Unknown attribute in attention element.");
74 }
75
76 #[test]
77 fn test_serialise() {
78 let elem: Element = "<attention xmlns='urn:xmpp:attention:0'/>".parse().unwrap();
79 let attention = Attention;
80 let elem2: Element = attention.into();
81 assert_eq!(elem, elem2);
82 }
83}