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