1mod error;
2
3pub use error::Error;
4pub use error::Result;
5
6mod var;
7
8pub use var::{env_var, EnvVar};
9
10pub mod required {
11 use std::str::FromStr;
12
13 pub type Result<A> = crate::Result<A, <A as FromStr>::Err>;
14}
15
16pub mod optional {
17 use std::str::FromStr;
18
19 pub type Result<A> = crate::Result<Option<A>, <A as FromStr>::Err>;
20}
21
22#[cfg(test)]
23mod tests {
24 mod test_optional {
25 use crate::env_var;
26 use std::str::FromStr;
27
28 #[test]
29 fn return_none_if_not_found() {
30 let sample = Sample {
31 x: env_var("unknown_variable_name").as_optional().unwrap(),
32 };
33 assert_eq!(sample.x.is_none(), true);
34 }
35
36 #[test]
37 fn can_call_from_str_if_defined() {
38 let sample: Option<Sample> = env_var("PATH").as_optional().unwrap();
39 assert_eq!(sample.is_some(), true);
40 }
41
42 #[derive(Debug)]
43 struct Sample {
44 x: Option<String>,
45 }
46
47 impl FromStr for Sample {
48 type Err = <String as FromStr>::Err;
49
50 fn from_str(s: &str) -> Result<Self, Self::Err> {
51 Ok(Sample {
52 x: Some(s.to_string()),
53 })
54 }
55 }
56 }
57
58 mod test_required {
59 use crate::Error::NotPresent;
60 use crate::{env_var, required};
61 use std::str::FromStr;
62
63 #[test]
64 fn return_error_if_not_found() {
65 let x: required::Result<String> = env_var("unknown_variable_name").as_required();
66 match x {
67 Err(NotPresent(key)) => assert_eq!(key, "unknown_variable_name"),
68 Ok(_) => assert!(false, "unexpected success"),
69 _ => assert!(false, "unexpected error type"),
70 }
71 }
72
73 #[test]
74 fn return_value_if_key_found() {
75 let sample = Sample {
76 x: env_var("PATH").as_required().unwrap(),
77 };
78 assert_eq!(sample.x.is_empty(), false);
79 }
80
81 #[test]
82 fn can_call_from_str_if_defined() {
83 let sample: Sample = env_var("PATH").as_required().unwrap();
84 assert_eq!(sample.x.is_empty(), false);
85 }
86
87 #[derive(Debug)]
88 struct Sample {
89 x: String,
90 }
91
92 impl FromStr for Sample {
93 type Err = <String as FromStr>::Err;
94
95 fn from_str(s: &str) -> Result<Self, Self::Err> {
96 Ok(Sample { x: s.to_string() })
97 }
98 }
99 }
100}