Testing with temporary directory passed as an environment variable (test in a single thread RUST_TEST_THREADS)


Because environment variables are per-process and not per thread, we cannot run the tests in threads (which is the default).


examples/testing/tempfile-with-environment-variable/Cargo.toml
[package]
name = "tempfile-with-environment-variable"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rand = "0.8.5"
tempfile = "3.9.0"

examples/testing/tempfile-with-environment-variable/.cargo/config.toml
[alias]
t = "test -- --test-threads=1"

[env]
RUST_TEST_THREADS = "1"

examples/testing/tempfile-with-environment-variable/src/main.rs
use std::fs::File;
use std::io::Write;

fn main() {}

#[allow(dead_code)]
fn add(x: i32, y: i32) -> i32 {
    let time: u64 = rand::random();
    let time = time % 3;

    std::thread::sleep(std::time::Duration::from_secs(time));

    if let Ok(file_path) = std::env::var("RESULT_PATH") {
        let mut file = File::create(&file_path).unwrap();
        println!("add({x}, {y}) file {file_path}");
        writeln!(&mut file, "{}", x + y).unwrap();
    }
    x + y
}

#[test]
fn test_add_2_3_5() {
    let tmp_dir = tempfile::tempdir().unwrap();
    println!("tmp_dir: {:?}", tmp_dir);
    let file_path = tmp_dir.path().join("result.txt");
    println!("2+3 - file_path {:?}", file_path);
    std::env::set_var("RESULT_PATH", &file_path);

    let result = add(2, 3);
    assert_eq!(result, 5);

    let result = std::fs::read_to_string(file_path).unwrap();
    assert_eq!(result, "5\n");
}

#[test]
fn test_add_4_4_8() {
    let tmp_dir = tempfile::tempdir().unwrap();
    println!("tmp_dir: {:?}", tmp_dir);
    let file_path = tmp_dir.path().join("result.txt");
    println!("4+4 - file_path {:?}", file_path);
    std::env::set_var("RESULT_PATH", &file_path);

    let result = add(4, 4);
    assert_eq!(result, 8);

    let result = std::fs::read_to_string(file_path).unwrap();
    assert_eq!(result, "8\n");
}