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