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#[derive(Debug, Clone)]
16pub struct Attention;
17
18impl TryFrom<Element> for Attention {
19 type Err = Error;
20
21 fn try_from(elem: 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 for _ in elem.attrs() {
29 return Err(Error::ParseError("Unknown attribute in attention element."));
30 }
31 Ok(Attention)
32 }
33}
34
35impl From<Attention> for Element {
36 fn from(_: Attention) -> Element {
37 Element::builder("attention")
38 .ns(ns::ATTENTION)
39 .build()
40 }
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
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_invalid_attribute() {
66 let elem: Element = "<attention xmlns='urn:xmpp:attention:0' coucou=''/>".parse().unwrap();
67 let error = Attention::try_from(elem).unwrap_err();
68 let message = match error {
69 Error::ParseError(string) => string,
70 _ => panic!(),
71 };
72 assert_eq!(message, "Unknown attribute in attention element.");
73 }
74
75 #[test]
76 fn test_serialise() {
77 let elem: Element = "<attention xmlns='urn:xmpp:attention:0'/>".parse().unwrap();
78 let attention = Attention;
79 let elem2: Element = attention.into();
80 assert_eq!(elem, elem2);
81 }
82}