Skip to main content

uselesskey_core/
error.rs

1use alloc::string::String;
2
3use thiserror::Error;
4
5/// Errors for `uselesskey-core`.
6///
7/// This crate is deliberately “test-first”: many operations are infallible by design.
8/// We still surface IO and environment errors because those are common in test harnesses.
9#[derive(Debug, Error)]
10pub enum Error {
11    #[error("environment variable `{var}` is not set")]
12    MissingEnvVar { var: String },
13
14    #[error("failed to parse seed from environment variable `{var}`: {message}")]
15    InvalidSeed { var: String, message: String },
16
17    #[cfg(feature = "std")]
18    #[error(transparent)]
19    Io(#[from] std::io::Error),
20}
21
22#[cfg(all(test, feature = "std"))]
23mod tests {
24    use super::Error;
25    use std::error::Error as _;
26
27    #[test]
28    fn missing_env_var_message_is_readable() {
29        let missing = Error::MissingEnvVar {
30            var: "MY_VAR".to_string(),
31        };
32        assert_eq!(
33            missing.to_string(),
34            "environment variable `MY_VAR` is not set"
35        );
36        assert!(missing.source().is_none());
37    }
38
39    #[test]
40    fn invalid_seed_message_is_readable() {
41        let invalid = Error::InvalidSeed {
42            var: "MY_VAR".to_string(),
43            message: "bad seed".to_string(),
44        };
45        assert_eq!(
46            invalid.to_string(),
47            "failed to parse seed from environment variable `MY_VAR`: bad seed"
48        );
49        assert!(invalid.source().is_none());
50    }
51
52    #[test]
53    fn io_error_variant_preserves_inner_error() {
54        let inner = std::io::Error::other("io-fail");
55        let io_err: Error = inner.into();
56
57        assert_eq!(io_err.to_string(), "io-fail");
58        assert!(io_err.source().is_none());
59    }
60}