pub trait EnvSource {
fn get(&self, name: &str) -> Option<String>;
}
#[derive(Debug, Default, Clone, Copy)]
pub struct SystemEnvSource;
impl EnvSource for SystemEnvSource {
fn get(&self, name: &str) -> Option<String> {
std::env::var(name).ok()
}
}
#[derive(Debug, Default, Clone)]
pub struct MockEnvSource {
vars: std::collections::HashMap<String, String>,
}
impl MockEnvSource {
pub fn new() -> Self {
Self::default()
}
pub fn with(mut self, name: &str, value: &str) -> Self {
self.vars.insert(name.to_string(), value.to_string());
self
}
}
impl EnvSource for MockEnvSource {
fn get(&self, name: &str) -> Option<String> {
self.vars.get(name).cloned()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mock_env_source_reads_set_vars() {
let env = MockEnvSource::new().with("CI_TOKEN", "abc");
assert_eq!(env.get("CI_TOKEN").as_deref(), Some("abc"));
assert_eq!(env.get("MISSING"), None);
}
}