4 releases (2 breaking)

0.3.1 Sep 29, 2022
0.3.0 Sep 15, 2022
0.2.0 Dec 9, 2021
0.1.0 Dec 3, 2021

#34 in Testing

Download history 10917/week @ 2022-10-14 9796/week @ 2022-10-21 10908/week @ 2022-10-28 8105/week @ 2022-11-04 7347/week @ 2022-11-11 7748/week @ 2022-11-18 8843/week @ 2022-11-25 7277/week @ 2022-12-02 7537/week @ 2022-12-09 6771/week @ 2022-12-16 4534/week @ 2022-12-23 5734/week @ 2022-12-30 8622/week @ 2023-01-06 7441/week @ 2023-01-13 5199/week @ 2023-01-20 5841/week @ 2023-01-27

28,474 downloads per month
Used in 36 crates (20 directly)

MIT/Apache

23KB
372 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(
    vec![
        ("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(
    vec![
        ("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–5MB
~71K SLoC