Skip to main content

tpt_env_mocker/
lib.rs

1use std::env;
2use std::sync::{Mutex, MutexGuard};
3
4// Re-export the attribute macro when the `macros` feature is enabled.
5#[cfg(feature = "macros")]
6pub use tpt_env_mocker_macros::tpt_env;
7
8/// Global mutex that serialises all tests that touch environment variables.
9///
10/// Any test using [`MockEnv`] or `#[tpt_env(...)]` holds this lock for the
11/// duration of its body, preventing env-var races in parallel async tests.
12static ENV_MUTEX: Mutex<()> = Mutex::new(());
13
14/// A builder for constructing an environment mock.
15///
16/// # Example
17/// ```rust
18/// use tpt_env_mocker::MockEnv;
19///
20/// let _guard = MockEnv::new()
21///     .set("DATABASE_URL", "postgres://localhost/test")
22///     .set("LOG_LEVEL", "debug")
23///     .lock();
24///
25/// assert_eq!(std::env::var("DATABASE_URL").unwrap(), "postgres://localhost/test");
26/// // `_guard` dropped here → env vars restored
27/// ```
28#[derive(Default)]
29pub struct MockEnv {
30    ops: Vec<Op>,
31}
32
33#[derive(Clone)]
34enum Op {
35    Set(String, String),
36    Remove(String),
37}
38
39impl MockEnv {
40    /// Create a new builder with no pending operations.
41    pub fn new() -> Self {
42        Self::default()
43    }
44
45    /// Queue setting `key` to `value` when [`lock`](Self::lock) is called.
46    pub fn set(mut self, key: &str, value: &str) -> Self {
47        self.ops.push(Op::Set(key.to_owned(), value.to_owned()));
48        self
49    }
50
51    /// Queue removing `key` from the environment when [`lock`](Self::lock) is called.
52    pub fn remove(mut self, key: &str) -> Self {
53        self.ops.push(Op::Remove(key.to_owned()));
54        self
55    }
56
57    /// Acquire the global env lock, apply all queued operations, and return a
58    /// guard that restores the original values on drop.
59    ///
60    /// # Panics
61    /// Does not panic if the global mutex is poisoned: a previous test that
62    /// panicked while holding the lock is automatically recovered so subsequent
63    /// tests still run.
64    pub fn lock(self) -> EnvGuard {
65        // If a previous test panicked while holding the lock, recover the
66        // inner guard so subsequent tests still run.
67        let lock = ENV_MUTEX
68            .lock()
69            .unwrap_or_else(|poisoned| poisoned.into_inner());
70
71        // Snapshot originals before applying ops.
72        let original_values: Vec<(String, Option<String>)> = self
73            .ops
74            .iter()
75            .map(|op| {
76                let key = match op {
77                    Op::Set(k, _) | Op::Remove(k) => k.clone(),
78                };
79                let original = env::var(&key).ok();
80                (key, original)
81            })
82            .collect();
83
84        // Apply ops.
85        for op in self.ops {
86            match op {
87                Op::Set(k, v) => {
88                    // SAFETY: we hold the global lock so no other code modifies
89                    // the environment concurrently within this process.
90                    unsafe { env::set_var(&k, &v) };
91                }
92                Op::Remove(k) => {
93                    unsafe { env::remove_var(&k) };
94                }
95            }
96        }
97
98        EnvGuard {
99            _lock: lock,
100            original_values,
101        }
102    }
103
104    /// Recover from a poisoned global mutex.
105    ///
106    /// Call this in test setup if a previous test panicked while holding the lock.
107    pub fn recover_poison() {
108        let _unused = ENV_MUTEX.lock().unwrap_or_else(|p| p.into_inner());
109    }
110}
111
112/// RAII guard returned by [`MockEnv::lock`].
113///
114/// When dropped, all environment variables modified by the associated
115/// [`MockEnv`] are restored to their original values (or removed if they
116/// did not exist before).
117pub struct EnvGuard {
118    _lock: MutexGuard<'static, ()>,
119    original_values: Vec<(String, Option<String>)>,
120}
121
122impl Drop for EnvGuard {
123    fn drop(&mut self) {
124        for (key, original) in &self.original_values {
125            match original {
126                Some(val) => unsafe { env::set_var(key, val) },
127                None => unsafe { env::remove_var(key) },
128            }
129        }
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    #[test]
138    fn sets_and_restores_env_var() {
139        let key = "TPT_TEST_VAR_RESTORE";
140        env::remove_var(key);
141        {
142            let _g = MockEnv::new().set(key, "hello").lock();
143            assert_eq!(env::var(key).unwrap(), "hello");
144        }
145        assert!(env::var(key).is_err(), "should be restored (removed)");
146    }
147
148    #[test]
149    fn restores_original_value() {
150        let key = "TPT_TEST_VAR_ORIGINAL";
151        unsafe { env::set_var(key, "original") };
152        {
153            let _g = MockEnv::new().set(key, "overridden").lock();
154            assert_eq!(env::var(key).unwrap(), "overridden");
155        }
156        assert_eq!(env::var(key).unwrap(), "original");
157    }
158
159    #[test]
160    fn remove_op() {
161        let key = "TPT_TEST_VAR_REMOVE";
162        unsafe { env::set_var(key, "present") };
163        {
164            let _g = MockEnv::new().remove(key).lock();
165            assert!(env::var(key).is_err());
166        }
167        assert_eq!(env::var(key).unwrap(), "present");
168    }
169
170    #[test]
171    fn multiple_vars() {
172        let k1 = "TPT_MULTI_A";
173        let k2 = "TPT_MULTI_B";
174        {
175            let _g = MockEnv::new().set(k1, "a").set(k2, "b").lock();
176            assert_eq!(env::var(k1).unwrap(), "a");
177            assert_eq!(env::var(k2).unwrap(), "b");
178        }
179        assert!(env::var(k1).is_err());
180        assert!(env::var(k2).is_err());
181    }
182}