| Crates.io | temp-env |
| lib.rs | temp-env |
| version | 0.3.6 |
| created_at | 2021-12-03 12:19:25.445568+00 |
| updated_at | 2023-09-24 10:24:47.843967+00 |
| description | Set environment variables temporarily. |
| homepage | |
| repository | https://github.com/vmx/temp-env |
| max_upload_size | |
| id | 491707 |
| size | 39,216 |
Set environment variables temporarily.
This crate is useful for testing with different environment variables that should not interfere.
This code started as a small test helper written by @fabian-braun and @nbaztec and published by @fabian-braun on StackOverflow. @vmx found it useful and took the time to make it a proper crate.
temp_env::with_var("MY_ENV_VAR", Some("production"), || {
// Run some code where `MY_ENV_VAR` set to `"production"`.
});
temp_env::with_vars(
[
("FIRST_VAR", Some("Hello")),
("SECOND_VAR", Some("World!")),
],
|| {
// Run some code where `FIRST_VAR` is set to `"Hello"` and `SECOND_VAR` is set to
// `"World!"`.
}
);
temp_env::with_vars(
[
("FIRST_VAR", Some("Hello")),
("SECOND_VAR", None),
],
|| {
// Run some code where `FIRST_VAR` is set to `"Hello"` and `SECOND_VAR` is unset (even if
// it was set before)
}
);
Starting from version 0.3.0 you can return a value from inside the closure:
let r = temp_env::with_var("MY_ENV_VAR", Some("production"), || {
let envvar = env::var("MY_ENV_VAR").unwrap();
if envvar == "production" {
true
} else {
false
}
});
This crate sets and unsets environment variables for the currently running (Rust) process.
It leverages std::env::set_var.
The provided functions temp_env::with_* provide the following features:
Note that the crate makes use of a singleton mutex to avoid side effects between concurrently running tests. This may impact the degree of concurrency in your test execution.
async_closure: When enabled you can use async_with_var() with async closures. This feature needs at least Rust version 1.64.This project is licensed under either of
at your option.