Expand description
A testing utility for creating ephemeral environments which are reset once they go out of scope.
§Examples:
Once an EphemeralEnv drops out of scope, new env vars which were created whilst it was in scope will be dropped.
use ephemeral_env::EphemeralEnv;
assert!(std::env::var("MY_ENVIRONMENT_VARIABLE").is_err());
#[cfg(feature = "sync")]
{
let mut ephemeral = EphemeralEnv::from_env_sync().unwrap();
ephemeral.set_var("MY_ENVIRONMENT_VARIABLE", "test");
assert_eq!(std::env::var("MY_ENVIRONMENT_VARIABLE").unwrap(), "test");
}
assert!(std::env::var("MY_ENVIRONMENT_VARIABLE").is_err());Similarly, once an EphemeralEnv drops out of scope, modified env vars will revert to the value they held when the EphemeralEnv was created.
use ephemeral_env::EphemeralEnv;
unsafe {
std::env::set_var("MY_ENVIRONMENT_VARIABLE", "Spanners! Shh!");
}
{
let mut ephemeral = EphemeralEnv::from_env_sync().unwrap();
ephemeral.set_var("MY_ENVIRONMENT_VARIABLE", "test");
assert_eq!(std::env::var("MY_ENVIRONMENT_VARIABLE").unwrap(), "test");
}
assert_eq!(std::env::var("MY_ENVIRONMENT_VARIABLE").unwrap(), "Spanners! Shh!");§Async interface
If you’re testing across await points then it’s inadvisable to use EphemeralEnv::from_env_sync(), as this will use a std::sync::Mutex, which isn’t Send.
Instead, ephemeral_env provides [from_env_async()], which will use Tokio’s async-compatible
Mutex instead:
use ephemeral_env::EphemeralEnv;
assert!(std::env::var("MY_ENVIRONMENT_VARIABLE").is_err());
{
let mut ephemeral = EphemeralEnv::from_env_async().unwrap();
ephemeral.set_var("MY_ENVIRONMENT_VARIABLE", "test");
// Without the async interface, this call would cause a warning to be shown, and there
// would be a potential for the mutex held by the ephemeral environment to block the
// event loop.
tokio::time::sleep(Duration::from_millis(500)).await;
assert_eq!(std::env::var("MY_ENVIRONMENT_VARIABLE").unwrap(), "test");
}
assert!(std::env::var("MY_ENVIRONMENT_VARIABLE").is_err());