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    Ok(Delay {
24        from: from,
25        stamp: stamp,
26        data: None,
27    })
28}
29
30#[cfg(test)]
31mod tests {
32    use minidom::Element;
33    use error::Error;
34    use delay;
35
36    #[test]
37    fn test_simple() {
38        let elem: Element = "<delay xmlns='urn:xmpp:delay' from='capulet.com' stamp='2002-09-10T23:08:25Z'/>".parse().unwrap();
39        let delay = delay::parse_delay(&elem).unwrap();
40        assert_eq!(delay.from, Some(String::from("capulet.com")));
41        assert_eq!(delay.stamp, "2002-09-10T23:08:25Z");
42        assert_eq!(delay.data, None);
43    }
44
45    #[test]
46    fn test_unknown() {
47        let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'/>".parse().unwrap();
48        let error = delay::parse_delay(&elem).unwrap_err();
49        let message = match error {
50            Error::ParseError(string) => string,
51            _ => panic!(),
52        };
53        assert_eq!(message, "This is not a delay element.");
54    }
55
56    #[test]
57    fn test_invalid_child() {
58        let elem: Element = "<delay xmlns='urn:xmpp:delay'><coucou/></delay>".parse().unwrap();
59        let error = delay::parse_delay(&elem).unwrap_err();
60        let message = match error {
61            Error::ParseError(string) => string,
62            _ => panic!(),
63        };
64        assert_eq!(message, "Unknown child in delay element.");
65    }
66}