delay.rs

 1use minidom::Element;
 2
 3use error::Error;
 4
 5use ns;
 6
 7#[derive(Debug, Clone)]
 8pub struct Delay {
 9    pub from: Option<String>,
10    pub stamp: String,
11    pub data: Option<String>,
12}
13
14pub fn parse_delay(root: &Element) -> Result<Delay, Error> {
15    if !root.is("delay", ns::DELAY) {
16        return Err(Error::ParseError("This is not a delay element."));
17    }
18    for _ in root.children() {
19        return Err(Error::ParseError("Unknown child in delay element."));
20    }
21    let from = root.attr("from").and_then(|value| value.parse().ok());
22    let stamp = root.attr("stamp").ok_or(Error::ParseError("Mandatory argument 'stamp' not present in delay element."))?.to_owned();
23    let data = match root.text().as_ref() {
24        "" => None,
25        text => Some(text.to_owned()),
26    };
27    Ok(Delay {
28        from: from,
29        stamp: stamp,
30        data: data,
31    })
32}
33
34#[cfg(test)]
35mod tests {
36    use minidom::Element;
37    use error::Error;
38    use delay;
39
40    #[test]
41    fn test_simple() {
42        let elem: Element = "<delay xmlns='urn:xmpp:delay' from='capulet.com' stamp='2002-09-10T23:08:25Z'/>".parse().unwrap();
43        let delay = delay::parse_delay(&elem).unwrap();
44        assert_eq!(delay.from, Some(String::from("capulet.com")));
45        assert_eq!(delay.stamp, "2002-09-10T23:08:25Z");
46        assert_eq!(delay.data, None);
47    }
48
49    #[test]
50    fn test_unknown() {
51        let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'/>".parse().unwrap();
52        let error = delay::parse_delay(&elem).unwrap_err();
53        let message = match error {
54            Error::ParseError(string) => string,
55            _ => panic!(),
56        };
57        assert_eq!(message, "This is not a delay element.");
58    }
59
60    #[test]
61    fn test_invalid_child() {
62        let elem: Element = "<delay xmlns='urn:xmpp:delay'><coucou/></delay>".parse().unwrap();
63        let error = delay::parse_delay(&elem).unwrap_err();
64        let message = match error {
65            Error::ParseError(string) => string,
66            _ => panic!(),
67        };
68        assert_eq!(message, "Unknown child in delay element.");
69    }
70}