Crate env_lock

Source
Expand description

Lock environment variables to prevent simultaneous access. Use lock_env to set values for whatever environment variables you intend to access in your test. This will return a guard that, when dropped, will revert the environment to its initial state. The guard uses a Mutex underneath to ensure that multiple tests within the same process can’t access it at the same time.

let var = "ENV_LOCK_TEST_VARIABLE";
assert!(env::var(var).is_err());

let guard = env_lock::lock_env([(var, Some("hello!"))]);
assert_eq!(env::var(var).unwrap(), "hello!");
drop(guard);

assert!(env::var(var).is_err());

You can also lock the current working directory, which is another form of mutable global state.

let old_dir = env::current_dir().unwrap();
let new_dir = old_dir.parent().unwrap();
let guard = env_lock::lock_current_dir(new_dir).unwrap();
assert_eq!(env::current_dir().unwrap(), new_dir);
drop(guard);

assert_eq!(env::current_dir().unwrap(), old_dir);

Structs§

CurrentDirGuard
A guard used to indicate that the current working directory is locked. Returned by lock_current_dir. This will restore and unlock the working directory on drop.
EnvGuard
A guard used to indicate that the current process environment is locked. Returned by lock_env. This will restore and unlock the environment on drop.

Enums§

CurrentDirError
Context for an error that can occur while locking the current directory. Both the get and the set can fail; this error tells you which one failed. Use Error::source to get the underlying error.

Functions§

lock_current_dir
Set the working directory for the current process. The working directory is a form of global mutable state, so this use a mutex to ensure that only one mutation can be made at a time. This returns a guard that, when dropped, will revert the working directory to its previous value and release the lock on it.
lock_env
Lock the environment and set each given variable to its corresponding value. If the environment is already locked, this will block until the lock can be acquired. The returned guard will keep the environment locked so the calling test has exclusive access to it. Upon being dropped, the old environment values will be restored and then the environment will be unlocked.