9 releases

0.3.6 Sep 24, 2023
0.3.5 Sep 1, 2023
0.3.4 Apr 19, 2023
0.3.3 Mar 22, 2023
0.1.0 Dec 3, 2021

#20 in Testing

Download history 17734/week @ 2024-01-28 19485/week @ 2024-02-04 18124/week @ 2024-02-11 22319/week @ 2024-02-18 21801/week @ 2024-02-25 22205/week @ 2024-03-03 22088/week @ 2024-03-10 24978/week @ 2024-03-17 21821/week @ 2024-03-24 20687/week @ 2024-03-31 22464/week @ 2024-04-07 23612/week @ 2024-04-14 26978/week @ 2024-04-21 23888/week @ 2024-04-28 27373/week @ 2024-05-05 32027/week @ 2024-05-12

111,763 downloads per month
Used in 78 crates (62 directly)

MIT/Apache

26KB
415 lines

temp-env

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.

Examples

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
    }
});

How does it work?

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:

  • Avoid interference when running concurrently
  • Reset previously set env variables back to their original value upon completion, also in case of panic
  • Temporarily unsetting env variables

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.

Features

  • async_closure: When enabled you can use async_with_var() with async closures. This feature needs at least Rust version 1.64.

License

This project is licensed under either of

at your option.

Dependencies

~0.4–5.5MB
~13K SLoC