#env-var #variables #environment #initial #manipulate #utils

env-test-util

Just a simple tool to manipulate environment variable in tests

3 releases (stable)

1.0.1 Nov 5, 2020
0.1.0 Nov 5, 2020

#657 in Testing

Download history 698/week @ 2024-07-25 465/week @ 2024-08-01 709/week @ 2024-08-08 611/week @ 2024-08-15 566/week @ 2024-08-22 519/week @ 2024-08-29 659/week @ 2024-09-05 389/week @ 2024-09-12 450/week @ 2024-09-19 681/week @ 2024-09-26 590/week @ 2024-10-03 985/week @ 2024-10-10 766/week @ 2024-10-17 656/week @ 2024-10-24 684/week @ 2024-10-31 617/week @ 2024-11-07

2,988 downloads per month
Used in chanoma

MIT/Apache

8KB
56 lines

Env test util

Crates.io Crates.io

Build Status codecov

Just a simple tool to manipulate environment variable in tests.

Usage

When initialising the variable manager with new, the actual content will be removed and stored in initial_value. You can then set a temporary value using the method with. The environment variable will then be reset to it's initial value when it will be dropped.

Examples

use env_test_util::TempEnvVar;

std::env::set_var("MY_VARIABLE", "ORIGINAL"); // set the variable to "ORIGINAL"
let variable = TempEnvVar::new("MY_VARIABLE"); // read the variable and stores it
assert_eq!(std::env::var("MY_VARIABLE").ok(), None);
let variable = variable.with("NEW_CONTENT"); // set the environment variable with a new content
assert_eq!(std::env::var("MY_VARIABLE").ok(), Some("NEW_CONTENT".into()));
drop(variable);
assert_eq!(std::env::var("MY_VARIABLE").ok(), Some("ORIGINAL".into()));

Don't forget to assign the variable in your tests, otherwise the drop function will be called right away

use env_test_util::TempEnvVar;

std::env::set_var("MY_VARIABLE", "ORIGINAL"); // set the variable to "ORIGINAL"
TempEnvVar::new("MY_VARIABLE").with("SOMETHING_ELSE"); // read the variable and stores it
assert_eq!(std::env::var("MY_VARIABLE").ok(), Some("ORIGINAL".into()));
let _variable = TempEnvVar::new("MY_VARIABLE").with("SOMETHING_ELSE"); // Instead, store it in a variable
assert_eq!(std::env::var("MY_VARIABLE").ok(), Some("SOMETHING_ELSE".into()));

Real life example

#[test]
fn testing_conntection_database() {
    let _original_url = TempEnvVar::new("DATABASE_URL").with("postgres://wrong-url");
    let connection = Database::connect(); // something that reads the environment variable
    assert!(connection.is_err());
}

No runtime deps

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy