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<'a> TryFrom<&'a Element> for Replace {
21 type Error = Error;
22
23 fn try_from(elem: &'a 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 = match elem.attr("id") {
31 Some(id) => id.to_owned(),
32 None => return Err(Error::ParseError("No 'id' attribute present in replace.")),
33 };
34 Ok(Replace { id: id })
35 }
36}
37
38impl<'a> Into<Element> for &'a Replace {
39 fn into(self) -> Element {
40 Element::builder("replace")
41 .ns(ns::MESSAGE_CORRECT)
42 .attr("id", self.id.clone())
43 .build()
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50
51 #[test]
52 fn test_simple() {
53 let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0' id='coucou'/>".parse().unwrap();
54 Replace::try_from(&elem).unwrap();
55 }
56
57 #[test]
58 fn test_invalid_child() {
59 let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'><coucou/></replace>".parse().unwrap();
60 let error = Replace::try_from(&elem).unwrap_err();
61 let message = match error {
62 Error::ParseError(string) => string,
63 _ => panic!(),
64 };
65 assert_eq!(message, "Unknown child in replace element.");
66 }
67
68 #[test]
69 fn test_invalid_id() {
70 let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'/>".parse().unwrap();
71 let error = Replace::try_from(&elem).unwrap_err();
72 let message = match error {
73 Error::ParseError(string) => string,
74 _ => panic!(),
75 };
76 assert_eq!(message, "No 'id' attribute present in replace.");
77 }
78
79 #[test]
80 fn test_serialise() {
81 let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0' id='coucou'/>".parse().unwrap();
82 let replace = Replace { id: String::from("coucou") };
83 let elem2 = (&replace).into();
84 assert_eq!(elem, elem2);
85 }
86}