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 minidom::Element;
8
9use error::Error;
10
11use ns;
12
13#[derive(Debug, Clone)]
14pub struct Replace {
15 pub id: String,
16}
17
18pub fn parse_replace(root: &Element) -> Result<Replace, Error> {
19 if !root.is("replace", ns::MESSAGE_CORRECT) {
20 return Err(Error::ParseError("This is not a replace element."));
21 }
22 for _ in root.children() {
23 return Err(Error::ParseError("Unknown child in replace element."));
24 }
25 let id = match root.attr("id") {
26 Some(id) => id.to_owned(),
27 None => return Err(Error::ParseError("No 'id' attribute present in replace.")),
28 };
29 Ok(Replace { id: id })
30}
31
32pub fn serialise(replace: &Replace) -> Element {
33 Element::builder("replace")
34 .ns(ns::MESSAGE_CORRECT)
35 .attr("id", replace.id.clone())
36 .build()
37}
38
39#[cfg(test)]
40mod tests {
41 use minidom::Element;
42 use error::Error;
43 use message_correct;
44
45 #[test]
46 fn test_simple() {
47 let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0' id='coucou'/>".parse().unwrap();
48 message_correct::parse_replace(&elem).unwrap();
49 }
50
51 #[test]
52 fn test_invalid_child() {
53 let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'><coucou/></replace>".parse().unwrap();
54 let error = message_correct::parse_replace(&elem).unwrap_err();
55 let message = match error {
56 Error::ParseError(string) => string,
57 _ => panic!(),
58 };
59 assert_eq!(message, "Unknown child in replace element.");
60 }
61
62 #[test]
63 fn test_invalid_id() {
64 let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'/>".parse().unwrap();
65 let error = message_correct::parse_replace(&elem).unwrap_err();
66 let message = match error {
67 Error::ParseError(string) => string,
68 _ => panic!(),
69 };
70 assert_eq!(message, "No 'id' attribute present in replace.");
71 }
72
73 #[test]
74 fn test_serialise() {
75 let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0' id='coucou'/>".parse().unwrap();
76 let replace = message_correct::Replace { id: String::from("coucou") };
77 let elem2 = message_correct::serialise(&replace);
78 assert_eq!(elem, elem2);
79 }
80}