Debian Codegraph @

tests/integration/util/testenv.rs

raw
1 use once_cell::sync::OnceCell;
2 use std::collections::HashMap;
3 use std::io::Write;
4 use std::path::{Path, PathBuf};
5 use std::sync::{Arc, Mutex, PoisonError};
6 use std::{env, fs, io};
7 use tempfile::{tempdir, TempDir};
8
9 use super::*;
10
11 /// Env var convenience type.
12 type EnvMap = HashMap<String, String>;
13
14 /// Initialized in [`get_env_locker`]
15 static ENV_LOCKER: OnceCell<Arc<Mutex<EnvMap>>> = OnceCell::new();
16
17 /// A test environment.
18 ///
19 /// Will create a new temporary directory. Use its builder methods to configure
20 /// the directory structure, preset variables, envfile name and contents, and
21 /// the working directory to run the test from.
22 ///
23 /// Creation methods:
24 /// - [`TestEnv::init`]: blank environment (no envfile)
25 /// - [`TestEnv::init_with_envfile`]: blank environment with an envfile
26 /// - [`TestEnv::default`]: default testing environment (1 existing var and 2
27 /// set in a `.env` file)
28 #[derive(Debug)]
29 pub struct TestEnv {
30 temp_dir: TempDir,
31 work_dir: PathBuf,
32 env_vars: Vec<KeyVal>,
33 envfile_contents: Option<String>,
34 envfile_path: PathBuf,
35 }
36
37 /// Simple key value struct for representing environment variables
38 #[derive(Debug, Clone)]
39 pub struct KeyVal {
40 key: String,
41 value: String,
42 }
43
44 /// Run a test closure within a test environment.
45 ///
46 /// Resets the environment variables, loads the [`TestEnv`], then runs the test
47 /// closure. Ensures only one thread has access to the process environment.
48 pub fn test_in_env<F>(test_env: TestEnv, test: F)
49 where
50 F: FnOnce(),
51 {
52 let locker = get_env_locker();
53 // ignore a poisoned mutex
54 // we expect some tests may panic to indicate a failure
55 let original_env = locker.lock().unwrap_or_else(PoisonError::into_inner);
56 // we reset the environment anyway upon acquiring the lock
57 reset_env(&original_env);
58 create_env(&test_env);
59 test();
60 // drop the lock and the `TestEnv` - should delete the tempdir
61 }
62
63 /// Run a test closure within the default test environment.
64 ///
65 /// Resets the environment variables, creates the default [`TestEnv`], then runs
66 /// the test closure. Ensures only one thread has access to the process
67 /// environment.
68 ///
69 /// The default testing environment sets an existing environment variable
70 /// `TEST_EXISTING_KEY`, which is set to `from_env`. It also creates a `.env`
71 /// file with the two lines:
72 ///
73 /// ```ini
74 /// TESTKEY=test_val
75 /// TEST_EXISTING_KEY=from_file
76 /// ```
77 ///
78 /// Notice that file has the potential to override `TEST_EXISTING_KEY` depending
79 /// on the what's being tested.
80 pub fn test_in_default_env<F>(test: F)
81 where
82 F: FnOnce(),
83 {
84 let test_env = TestEnv::default();
85 test_in_env(test_env, test);
86 }
87
88 impl TestEnv {
89 /// Blank testing environment in a new temporary directory.
90 ///
91 /// No envfile_contents or pre-existing variables to set. The envfile_name
92 /// is set to `.env` but wont be written until its contents is set. The
93 /// working directory is the created temporary directory.
94 pub fn init() -> Self {
95 let tempdir = tempdir().expect("create tempdir");
96 let work_dir = tempdir.path().to_owned();
97 let envfile_path = work_dir.join(".env");
98 Self {
99 temp_dir: tempdir,
100 work_dir,
101 env_vars: Default::default(),
102 envfile_contents: None,
103 envfile_path,
104 }
105 }
106
107 /// Testing environment with custom envfile_contents.
108 ///
109 /// No pre-existing env_vars set. The envfile_name is set to `.env`. The
110 /// working directory is the created temporary directory.
111 pub fn init_with_envfile(contents: impl ToString) -> Self {
112 let mut test_env = Self::init();
113 test_env.set_envfile_contents(contents);
114 test_env
115 }
116
117 /// Change the name of the default `.env` file.
118 ///
119 /// It will still be placed in the root temporary directory. If you need to
120 /// put the envfile in a different directory, use
121 /// [`set_envfile_path`](TestEnv::set_envfile_path) instead.
122 pub fn set_envfile_name(&mut self, name: impl AsRef<Path>) -> &mut Self {
123 self.envfile_path = self.temp_path().join(name);
124 self
125 }
126
127 /// Change the absolute path to the envfile.
128 pub fn set_envfile_path(&mut self, path: PathBuf) -> &mut Self {
129 self.envfile_path = path;
130 self
131 }
132
133 /// Specify the contents of the envfile.
134 ///
135 /// If this is the only change to the [`TestEnv`] being made, use
136 /// [`new_with_envfile`](TestEnv::new_with_envfile).
137 ///
138 /// Setting it to an empty string will cause an empty envfile to be created
139 pub fn set_envfile_contents(&mut self, contents: impl ToString) -> &mut Self {
140 self.envfile_contents = Some(contents.to_string());
141 self
142 }
143
144 /// Set the working directory the test will run from.
145 ///
146 /// The default is the created temporary directory. This method is useful if
147 /// you wish to run a test from a subdirectory or somewhere else.
148 pub fn set_work_dir(&mut self, path: PathBuf) -> &mut Self {
149 self.work_dir = path;
150 self
151 }
152
153 /// Add an individual environment variable.
154 ///
155 /// This adds more pre-existing environment variables to the process before
156 /// any tests are run.
157 pub fn add_env_var(&mut self, key: impl ToString, value: impl ToString) -> &mut Self {
158 self.env_vars.push(KeyVal {
159 key: key.to_string(),
160 value: value.to_string(),
161 });
162 self
163 }
164
165 /// Set the pre-existing environment variables.
166 ///
167 /// These variables will get added to the process' environment before the
168 /// test is run. This overrides any previous env vars added to the
169 /// [`TestEnv`].
170 ///
171 /// If you wish to just use a slice of tuples, use
172 /// [`set_env_vars_tuple`](TestEnv::set_env_vars_tuple) instead.
173 pub fn set_env_vars(&mut self, env_vars: Vec<KeyVal>) -> &mut Self {
174 self.env_vars = env_vars;
175 self
176 }
177
178 /// Set the pre-existing environment variables using [`str`] tuples.
179 ///
180 /// These variables will get added to the process' environment before the
181 /// test is run. This overrides any previous env vars added to the
182 /// [`TestEnv`].
183 ///
184 /// If you wish to add an owned `Vec<KeyVal>` instead of `str` tuples, use
185 /// [`set_env_vars`](TestEnv::set_env_vars) instead.
186 pub fn set_env_vars_tuple(&mut self, env_vars: &[(&str, &str)]) -> &mut Self {
187 self.env_vars = env_vars
188 .iter()
189 .map(|(key, value)| KeyVal {
190 key: key.to_string(),
191 value: value.to_string(),
192 })
193 .collect();
194
195 self
196 }
197
198 /// Create a child folder within the temporary directory.
199 ///
200 /// This will not change the working directory the test is run in, or where
201 /// the envfile is created.
202 ///
203 /// Will create parent directories if they are missing.
204 pub fn add_child_dir_all(&self, rel_path: impl AsRef<Path>) -> PathBuf {
205 let rel_path = rel_path.as_ref();
206 let child_dir = self.temp_path().join(rel_path);
207 if let Err(err) = fs::create_dir_all(&child_dir) {
208 panic!(
209 "unable to create child directory: `{}` in `{}`: {}",
210 self.temp_path().display(),
211 rel_path.display(),
212 err
213 );
214 }
215 child_dir
216 }
217
218 /// Get a reference to the path of the temporary directory.
219 pub fn temp_path(&self) -> &Path {
220 self.temp_dir.path()
221 }
222
223 /// Get a reference to the working directory the test will be run from.
224 pub fn work_dir(&self) -> &Path {
225 &self.work_dir
226 }
227
228 /// Get a reference to environnement variables that will be set **before**
229 /// the test.
230 pub fn env_vars(&self) -> &[KeyVal] {
231 &self.env_vars
232 }
233
234 /// Get a reference to the string that will be placed in the envfile.
235 ///
236 /// If `None` is returned, an envfile will not be created
237 pub fn envfile_contents(&self) -> Option<&str> {
238 self.envfile_contents.as_deref()
239 }
240
241 /// Get a reference to the path of the envfile.
242 pub fn envfile_path(&self) -> &Path {
243 &self.envfile_path
244 }
245 }
246
247 impl Default for TestEnv {
248 fn default() -> Self {
249 let temp_dir = tempdir().expect("create tempdir");
250 let work_dir = temp_dir.path().to_owned();
251 let env_vars = vec![KeyVal {
252 key: TEST_EXISTING_KEY.into(),
253 value: TEST_EXISTING_VALUE.into(),
254 }];
255 let envfile_contents = Some(create_default_envfile());
256 let envfile_path = work_dir.join(".env");
257 Self {
258 temp_dir,
259 work_dir,
260 env_vars,
261 envfile_contents,
262 envfile_path,
263 }
264 }
265 }
266
267 impl From<(&str, &str)> for KeyVal {
268 fn from(kv: (&str, &str)) -> Self {
269 let (key, value) = kv;
270 Self {
271 key: key.to_string(),
272 value: value.to_string(),
273 }
274 }
275 }
276
277 impl From<(String, String)> for KeyVal {
278 fn from(kv: (String, String)) -> Self {
279 let (key, value) = kv;
280 Self { key, value }
281 }
282 }
283
284 /// Get a guarded copy of the original process' env vars.
285 fn get_env_locker() -> Arc<Mutex<EnvMap>> {
286 Arc::clone(ENV_LOCKER.get_or_init(|| {
287 let map: EnvMap = env::vars().collect();
288 Arc::new(Mutex::new(map))
289 }))
290 }
291
292 /// Reset the process' env vars back to what was in `original_env`.
293 fn reset_env(original_env: &EnvMap) {
294 // remove keys if they weren't in the original environment
295 env::vars()
296 .filter(|(key, _)| !original_env.contains_key(key))
297 .for_each(|(key, _)| env::remove_var(key));
298 // ensure original keys have their original values
299 original_env
300 .iter()
301 .for_each(|(key, value)| env::set_var(key, value));
302 }
303
304 /// Create an environment to run tests in.
305 ///
306 /// Writes the envfile, sets the working directory, and sets environment vars.
307 fn create_env(test_env: &TestEnv) {
308 // only create the envfile if its contents has been set
309 if let Some(contents) = test_env.envfile_contents() {
310 create_envfile(&test_env.envfile_path, contents);
311 }
312
313 env::set_current_dir(&test_env.work_dir).expect("setting working directory");
314
315 for KeyVal { key, value } in &test_env.env_vars {
316 env::set_var(key, value)
317 }
318 }
319
320 /// Create an envfile for use in tests.
321 fn create_envfile(path: &Path, contents: &str) {
322 if path.exists() {
323 panic!("envfile `{}` already exists", path.display())
324 }
325 // inner function to group together io::Results
326 fn create_env_file_inner(path: &Path, contents: &str) -> io::Result<()> {
327 let mut file = fs::File::create(path)?;
328 file.write_all(contents.as_bytes())?;
329 file.sync_all()
330 }
331 // call inner function
332 if let Err(err) = create_env_file_inner(path, contents) {
333 // handle any io::Result::Err
334 panic!("error creating envfile `{}`: {}", path.display(), err);
335 }
336 }