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
13pub type Body = String;
14
15pub fn parse_body(root: &Element) -> Result<Body, Error> {
16 // TODO: also support components and servers.
17 if !root.is("body", ns::JABBER_CLIENT) {
18 return Err(Error::ParseError("This is not a body element."));
19 }
20 for _ in root.children() {
21 return Err(Error::ParseError("Unknown child in body element."));
22 }
23 Ok(root.text())
24}
25
26pub fn serialise(body: &Body) -> Element {
27 Element::builder("body")
28 .ns(ns::JABBER_CLIENT)
29 .append(body.to_owned())
30 .build()
31}
32
33#[cfg(test)]
34mod tests {
35 use minidom::Element;
36 use error::Error;
37 use body;
38 use ns;
39
40 #[test]
41 fn test_simple() {
42 let elem: Element = "<body xmlns='jabber:client'/>".parse().unwrap();
43 body::parse_body(&elem).unwrap();
44 }
45
46 #[test]
47 fn test_invalid() {
48 let elem: Element = "<body xmlns='jabber:server'/>".parse().unwrap();
49 let error = body::parse_body(&elem).unwrap_err();
50 let message = match error {
51 Error::ParseError(string) => string,
52 _ => panic!(),
53 };
54 assert_eq!(message, "This is not a body element.");
55 }
56
57 #[test]
58 fn test_invalid_child() {
59 let elem: Element = "<body xmlns='jabber:client'><coucou/></body>".parse().unwrap();
60 let error = body::parse_body(&elem).unwrap_err();
61 let message = match error {
62 Error::ParseError(string) => string,
63 _ => panic!(),
64 };
65 assert_eq!(message, "Unknown child in body element.");
66 }
67
68 #[test]
69 #[ignore]
70 fn test_invalid_attribute() {
71 let elem: Element = "<body xmlns='jabber:client' coucou=''/>".parse().unwrap();
72 let error = body::parse_body(&elem).unwrap_err();
73 let message = match error {
74 Error::ParseError(string) => string,
75 _ => panic!(),
76 };
77 assert_eq!(message, "Unknown attribute in body element.");
78 }
79
80 #[test]
81 fn test_serialise() {
82 let body = body::Body::from("Hello world!");
83 let elem = body::serialise(&body);
84 assert!(elem.is("body", ns::JABBER_CLIENT));
85 }
86}