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#[derive(Debug, Clone)]
17pub struct Ping;
18
19impl TryFrom<Element> for Ping {
20    type Err = Error;
21
22    fn try_from(elem: Element) -> Result<Ping, Error> {
23        if !elem.is("ping", ns::PING) {
24            return Err(Error::ParseError("This is not a ping element."));
25        }
26        for _ in elem.children() {
27            return Err(Error::ParseError("Unknown child in ping element."));
28        }
29        for _ in elem.attrs() {
30            return Err(Error::ParseError("Unknown attribute in ping element."));
31        }
32        Ok(Ping)
33    }
34}
35
36impl From<Ping> for Element {
37    fn from(_: Ping) -> Element {
38        Element::builder("ping")
39                .ns(ns::PING)
40                .build()
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn test_simple() {
50        let elem: Element = "<ping xmlns='urn:xmpp:ping'/>".parse().unwrap();
51        Ping::try_from(elem).unwrap();
52    }
53
54    #[test]
55    fn test_invalid() {
56        let elem: Element = "<ping xmlns='urn:xmpp:ping'><coucou/></ping>".parse().unwrap();
57        let error = Ping::try_from(elem).unwrap_err();
58        let message = match error {
59            Error::ParseError(string) => string,
60            _ => panic!(),
61        };
62        assert_eq!(message, "Unknown child in ping element.");
63    }
64
65    #[test]
66    fn test_invalid_attribute() {
67        let elem: Element = "<ping xmlns='urn:xmpp:ping' coucou=''/>".parse().unwrap();
68        let error = Ping::try_from(elem).unwrap_err();
69        let message = match error {
70            Error::ParseError(string) => string,
71            _ => panic!(),
72        };
73        assert_eq!(message, "Unknown attribute in ping element.");
74    }
75}