Skip to content
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 98 additions & 2 deletions benches/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,105 @@ impl ShallowTempDir {
}
}

const DB_CLEAN_UP_ENV_VAR: &str = "DB_CLEAN_UP";

impl Drop for ShallowTempDir {
fn drop(&mut self) {
// Ignore errors
let _ = std::fs::remove_dir_all(&self.path);
let default_db_clean_up = true;
// Check if DB_CLEAN_UP is set and correctly parsed to a boolean, defaulting to true
let should_clean_up = env::var(DB_CLEAN_UP_ENV_VAR)
.map_or(default_db_clean_up, |v| {
v.parse::<bool>().unwrap_or(default_db_clean_up)
});

if should_clean_up {
if let Err(e) = std::fs::remove_dir_all(&self.path) {
eprintln!("Failed to remove temp directory: {:?}", e);
}
}
}
}

#[cfg(test)]
#[allow(non_snake_case)]
mod tests {
use super::*;

fn shallow_temp_dir__drops_if_env_var_is_set() {
// given
env::set_var(DB_CLEAN_UP_ENV_VAR, "true");
let path;
{
let dir = ShallowTempDir::new();
path = dir.path().clone();
std::fs::create_dir_all(&path).expect("Failed to create temp directory");
}
// when: out of scope, dropped

// then
assert!(!path.exists());

// clean up
env::remove_var(DB_CLEAN_UP_ENV_VAR);
}

fn shallow_temp_dir__does_not_drop_if_env_var_is_set() {
// given
env::set_var(DB_CLEAN_UP_ENV_VAR, "false");
let path;
{
let dir = ShallowTempDir::new();
path = dir.path().clone();
std::fs::create_dir_all(&path).expect("Failed to create temp directory");
}

// when: out of scope, not dropped

// then
assert!(path.exists());
// clean up manually
std::fs::remove_dir_all(path).unwrap();
env::remove_var(DB_CLEAN_UP_ENV_VAR);
}

fn shallow_temp_dir__drops_if_env_var_is_not_set() {
// given
let path;
{
let dir = ShallowTempDir::new();
path = dir.path().clone();
std::fs::create_dir_all(&path).expect("Failed to create temp directory");
}
// when: out of scope, dropped

// then
assert!(!path.exists());
}

fn shalow_temp_dir__drops_if_env_var_malformed() {
// given
env::set_var(DB_CLEAN_UP_ENV_VAR, "bing_bong");
let path;
{
let dir = ShallowTempDir::new();
path = dir.path().clone();
std::fs::create_dir_all(&path).expect("Failed to create temp directory");
}
// when: out of scope, dropped

// then
assert!(!path.exists());

// clean up
env::remove_var(DB_CLEAN_UP_ENV_VAR);
}

#[test]
fn test_shallow_temp_dir_behaviour() {
// run tests sequentially to avoid conflicts due to env var usage
shallow_temp_dir__drops_if_env_var_is_set();
shallow_temp_dir__does_not_drop_if_env_var_is_set();
shallow_temp_dir__drops_if_env_var_is_not_set();
shalow_temp_dir__drops_if_env_var_malformed();
}
}