Skip to main content

age_setup/types/
validation.rs

1use crate::errors::{Error, Result, ValidationError};
2pub(crate) fn validate_age_prefix(key: &str) -> Result<()> {
3    if key.is_empty() {
4        return Err(Error::from(ValidationError::invalid_public_key(
5            "Key is empty",
6        )));
7    }
8    if !key.starts_with("age1") {
9        return Err(Error::from(ValidationError::invalid_public_key(format!(
10            "Key must start with 'age1', got: {}",
11            &key[..key.len().min(10)]
12        ))));
13    }
14    Ok(())
15}
16#[cfg(test)]
17mod tests {
18    use super::*;
19    use crate::errors::Error;
20
21    #[test]
22    fn test_validate_age_prefix_empty() {
23        let result = validate_age_prefix("");
24        assert!(result.is_err());
25        match result.unwrap_err() {
26            Error::Validation(e) => {
27                let msg = format!("{}", e);
28                assert!(msg.contains("Key is empty"));
29            }
30            _ => panic!(),
31        }
32    }
33
34    #[test]
35    fn test_validate_age_prefix_wrong_prefix() {
36        let result = validate_age_prefix("xyz123");
37        assert!(result.is_err());
38        match result.unwrap_err() {
39            Error::Validation(e) => {
40                let msg = format!("{}", e);
41                assert!(msg.contains("must start with 'age1'"));
42                assert!(msg.contains("xyz123"));
43            }
44            _ => panic!(),
45        }
46    }
47
48    #[test]
49    fn test_validate_age_prefix_short_prefix() {
50        let result = validate_age_prefix("age");
51        assert!(result.is_err());
52    }
53
54    #[test]
55    fn test_validate_age_prefix_valid() {
56        let result = validate_age_prefix("age1abcdef");
57        assert!(result.is_ok());
58    }
59}