hashes.rs

 1use minidom::Element;
 2
 3use error::Error;
 4
 5use ns;
 6
 7#[derive(Debug, Clone)]
 8pub struct Hash {
 9    pub algo: String,
10    pub hash: String,
11}
12
13pub fn parse_hash(root: &Element) -> Result<Hash, Error> {
14    if !root.is("hash", ns::HASHES) {
15        return Err(Error::ParseError("This is not a hash element."));
16    }
17    for _ in root.children() {
18        return Err(Error::ParseError("Unknown child in hash element."));
19    }
20    let algo = root.attr("algo").ok_or(Error::ParseError("Mandatory argument 'algo' not present in hash element."))?.to_owned();
21    let hash = match root.text().as_ref() {
22        "" => return Err(Error::ParseError("Hash element shouldn’t be empty.")),
23        text => text.to_owned(),
24    };
25    Ok(Hash {
26        algo: algo,
27        hash: hash,
28    })
29}
30
31#[cfg(test)]
32mod tests {
33    use minidom::Element;
34    use error::Error;
35    use hashes;
36
37    #[test]
38    fn test_simple() {
39        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2' algo='sha-256'>2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=</hash>".parse().unwrap();
40        let hash = hashes::parse_hash(&elem).unwrap();
41        assert_eq!(hash.algo, "sha-256");
42        assert_eq!(hash.hash, "2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=");
43    }
44
45    #[test]
46    fn test_unknown() {
47        let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'/>".parse().unwrap();
48        let error = hashes::parse_hash(&elem).unwrap_err();
49        let message = match error {
50            Error::ParseError(string) => string,
51            _ => panic!(),
52        };
53        assert_eq!(message, "This is not a hash element.");
54    }
55
56    #[test]
57    fn test_invalid_child() {
58        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2'><coucou/></hash>".parse().unwrap();
59        let error = hashes::parse_hash(&elem).unwrap_err();
60        let message = match error {
61            Error::ParseError(string) => string,
62            _ => panic!(),
63        };
64        assert_eq!(message, "Unknown child in hash element.");
65    }
66}