ping.rs

 1// Copyright (c) 2017 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
 2// Copyright (c) 2017 Maxime “pep” Buquet <pep+code@bouah.net>
 3//
 4// This Source Code Form is subject to the terms of the Mozilla Public
 5// License, v. 2.0. If a copy of the MPL was not distributed with this
 6// file, You can obtain one at http://mozilla.org/MPL/2.0/.
 7
 8use try_from::TryFrom;
 9
10use minidom::Element;
11
12use error::Error;
13
14use ns;
15
16/// Structure representing a `<ping xmlns='urn:xmpp:ping'/>` element.
17#[derive(Debug, Clone)]
18pub struct Ping;
19
20impl TryFrom<Element> for Ping {
21    type Err = Error;
22
23    fn try_from(elem: Element) -> Result<Ping, Error> {
24        if !elem.is("ping", ns::PING) {
25            return Err(Error::ParseError("This is not a ping element."));
26        }
27        for _ in elem.children() {
28            return Err(Error::ParseError("Unknown child in ping element."));
29        }
30        for _ in elem.attrs() {
31            return Err(Error::ParseError("Unknown attribute in ping element."));
32        }
33        Ok(Ping)
34    }
35}
36
37impl From<Ping> for Element {
38    fn from(_: Ping) -> Element {
39        Element::builder("ping")
40                .ns(ns::PING)
41                .build()
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn test_simple() {
51        let elem: Element = "<ping xmlns='urn:xmpp:ping'/>".parse().unwrap();
52        Ping::try_from(elem).unwrap();
53    }
54
55    #[test]
56    fn test_invalid() {
57        let elem: Element = "<ping xmlns='urn:xmpp:ping'><coucou/></ping>".parse().unwrap();
58        let error = Ping::try_from(elem).unwrap_err();
59        let message = match error {
60            Error::ParseError(string) => string,
61            _ => panic!(),
62        };
63        assert_eq!(message, "Unknown child in ping element.");
64    }
65
66    #[test]
67    fn test_invalid_attribute() {
68        let elem: Element = "<ping xmlns='urn:xmpp:ping' coucou=''/>".parse().unwrap();
69        let error = Ping::try_from(elem).unwrap_err();
70        let message = match error {
71            Error::ParseError(string) => string,
72            _ => panic!(),
73        };
74        assert_eq!(message, "Unknown attribute in ping element.");
75    }
76}