How to run same program multiple times with different statics/configs each time?

I wanna run the same Rust program (main.rs) multiple times, but with different values on the static variables. This is for integration testing. How do I do it?

My current (failed) attempt does something like this:


const VALUE1: [&str; 3] = ["1", "2", "3"];
const VALUE2: [&str; 3] = ["1", "2", "3"];
const VALUE3: [&str; 3] = ["1", "2", "3"];


#[tokio::test]
async fn integration_tester() {
    helpers::set_init_vars();

    let mut futures = Vec::new();
    for index in 1..=2 {
        let expected_static_values = EXPECTED_STATIC_VALUES[index];

        let future = {
            set_next_var(index);
            mock_runtime(expected_static_values)
        };

        futures.push(future);
    }

    join_all(futures).await;
}

pub fn set_init_vars() {
    env::set_var("ENV_VAR1", "VALUE1");
    env::set_var("ENV_VAR2", "VALUE2");
   [...]
    env::set_var("ENV_VAR99", "VALUE99");
}

pub fn set_next_var(index: usize) {
    let value1 = VALUE1[index];
    let value2 = VALUE2[index];
    let value3 = VALUE3[index];

    env::set_var("ENV_VAR1", value1);
    env::set_var("ENV_VAR2", value2);
    env::set_var("ENV_VAR3", value3);
}

mock_runtime(..) is basically a copy-paste of the main function of the program I'm trying to integration-test, with minor modifications. The static variables (global variables) in the program are different depending on the environment variables you insert into the program (and i wanna integration-test the program's behavior given a large variety of env combinations).

If I'm in a scenario where I need to configure my app for different environments using a global instead of passing the state around explicitly, I'd probably use a LazyLock and initialize the state inside by reading it from the environment or a config file.

I did that, but then the env values initialized in one test was carried over to the other test, so that the 2nd test used the env values of the 1st test

Each integration test file is compiled as its own crate. Like tests/tests1.rs and tests/test2.rs are compiled and run separate from each other. Can you somehow structure your test suite such that all tests in each file can work with the same configuration values? This would be a hacky workaround if you don't want to simply avoid global variables, which I think would be the best option. Just construct the config in each test function and pass it directly to your crate's API.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.