attention.rs

 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 std::convert::TryFrom;
 8
 9use minidom::Element;
10
11use error::Error;
12
13use ns;
14
15#[derive(Debug, Clone)]
16pub struct Attention;
17
18impl<'a> TryFrom<&'a Element> for Attention {
19    type Error = Error;
20
21    fn try_from(elem: &'a Element) -> Result<Attention, Error> {
22        if !elem.is("attention", ns::ATTENTION) {
23            return Err(Error::ParseError("This is not an attention element."));
24        }
25        for _ in elem.children() {
26            return Err(Error::ParseError("Unknown child in attention element."));
27        }
28        Ok(Attention)
29    }
30}
31
32impl<'a> Into<Element> for &'a Attention {
33    fn into(self) -> Element {
34        Element::builder("attention")
35                .ns(ns::ATTENTION)
36                .build()
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use std::convert::TryFrom;
43    use minidom::Element;
44    use error::Error;
45    use super::Attention;
46
47    #[test]
48    fn test_simple() {
49        let elem: Element = "<attention xmlns='urn:xmpp:attention:0'/>".parse().unwrap();
50        Attention::try_from(&elem).unwrap();
51    }
52
53    #[test]
54    fn test_invalid_child() {
55        let elem: Element = "<attention xmlns='urn:xmpp:attention:0'><coucou/></attention>".parse().unwrap();
56        let error = Attention::try_from(&elem).unwrap_err();
57        let message = match error {
58            Error::ParseError(string) => string,
59            _ => panic!(),
60        };
61        assert_eq!(message, "Unknown child in attention element.");
62    }
63
64    #[test]
65    fn test_serialise() {
66        let elem: Element = "<attention xmlns='urn:xmpp:attention:0'/>".parse().unwrap();
67        let attention = Attention;
68        let elem2: Element = (&attention).into();
69        let elem3: Element = (&attention).into();
70        assert_eq!(elem, elem2);
71        assert_eq!(elem2, elem3);
72    }
73}