message_correct.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 Replace {
17    pub id: String,
18}
19
20impl TryFrom<Element> for Replace {
21    type Error = Error;
22
23    fn try_from(elem: Element) -> Result<Replace, Error> {
24        if !elem.is("replace", ns::MESSAGE_CORRECT) {
25            return Err(Error::ParseError("This is not a replace element."));
26        }
27        for _ in elem.children() {
28            return Err(Error::ParseError("Unknown child in replace element."));
29        }
30        let id = get_attr!(elem, "id", required);
31        Ok(Replace { id })
32    }
33}
34
35impl Into<Element> for Replace {
36    fn into(self) -> Element {
37        Element::builder("replace")
38                .ns(ns::MESSAGE_CORRECT)
39                .attr("id", self.id.clone())
40                .build()
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn test_simple() {
50        let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0' id='coucou'/>".parse().unwrap();
51        Replace::try_from(elem).unwrap();
52    }
53
54    #[test]
55    fn test_invalid_child() {
56        let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'><coucou/></replace>".parse().unwrap();
57        let error = Replace::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 replace element.");
63    }
64
65    #[test]
66    fn test_invalid_id() {
67        let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'/>".parse().unwrap();
68        let error = Replace::try_from(elem).unwrap_err();
69        let message = match error {
70            Error::ParseError(string) => string,
71            _ => panic!(),
72        };
73        assert_eq!(message, "Required attribute 'id' missing.");
74    }
75
76    #[test]
77    fn test_serialise() {
78        let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0' id='coucou'/>".parse().unwrap();
79        let replace = Replace { id: String::from("coucou") };
80        let elem2 = replace.into();
81        assert_eq!(elem, elem2);
82    }
83}