mastodon_async/helpers/
env.rs

1use envy;
2
3use crate::{Data, Result};
4
5/// Attempts to deserialize a Data struct from the environment
6pub fn from_env() -> Result<Data> {
7    Ok(envy::from_env()?)
8}
9
10/// Attempts to deserialize a Data struct from the environment. All keys are
11/// prefixed with the given prefix
12pub fn from_env_prefixed(prefix: &str) -> Result<Data> {
13    Ok(envy::prefixed(prefix).from_env()?)
14}
15
16#[cfg(test)]
17mod tests {
18    use super::*;
19    use std::{
20        env,
21        ops::FnOnce,
22        panic::{catch_unwind, UnwindSafe},
23    };
24
25    fn withenv<F: FnOnce() -> R + UnwindSafe, R>(prefix: Option<&'static str>, test: F) -> R {
26        env::set_var(makekey(prefix, "BASE"), "https://example.com");
27        env::set_var(makekey(prefix, "CLIENT_ID"), "adbc01234");
28        env::set_var(makekey(prefix, "CLIENT_SECRET"), "0987dcba");
29        env::set_var(makekey(prefix, "REDIRECT"), "urn:ietf:wg:oauth:2.0:oob");
30        env::set_var(makekey(prefix, "TOKEN"), "fedc5678");
31
32        let result = catch_unwind(test);
33
34        env::remove_var(makekey(prefix, "BASE"));
35        env::remove_var(makekey(prefix, "CLIENT_ID"));
36        env::remove_var(makekey(prefix, "CLIENT_SECRET"));
37        env::remove_var(makekey(prefix, "REDIRECT"));
38        env::remove_var(makekey(prefix, "TOKEN"));
39
40        fn makekey(prefix: Option<&'static str>, key: &str) -> String {
41            if let Some(prefix) = prefix {
42                format!("{}{}", prefix, key)
43            } else {
44                key.to_string()
45            }
46        }
47
48        result.expect("failed")
49    }
50
51    #[test]
52    fn test_from_env_no_prefix() {
53        let desered = withenv(None, from_env).expect("Couldn't deser");
54        assert_eq!(
55            desered,
56            Data {
57                base: "https://example.com".into(),
58                client_id: "adbc01234".into(),
59                client_secret: "0987dcba".into(),
60                redirect: "urn:ietf:wg:oauth:2.0:oob".into(),
61                token: "fedc5678".into(),
62            }
63        );
64    }
65
66    #[test]
67    fn test_from_env_prefixed() {
68        let desered = withenv(Some("APP_"), || from_env_prefixed("APP_")).expect("Couldn't deser");
69        assert_eq!(
70            desered,
71            Data {
72                base: "https://example.com".into(),
73                client_id: "adbc01234".into(),
74                client_secret: "0987dcba".into(),
75                redirect: "urn:ietf:wg:oauth:2.0:oob".into(),
76                token: "fedc5678".into(),
77            }
78        );
79    }
80}