Skip to content

Commit

Permalink
Merge branch 'refactor-tests'
Browse files Browse the repository at this point in the history
  • Loading branch information
Byron committed May 6, 2022
2 parents c7edcb1 + d5b6faa commit 0e90cac
Show file tree
Hide file tree
Showing 6 changed files with 202 additions and 129 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ coinit_speed_over_memory = []
log = "0.4"

[dev-dependencies]
serial_test = "0.6.0"
chrono = "0.4.9"
rand = "0.8.3"
once_cell = "1.7.2"
Expand Down
37 changes: 23 additions & 14 deletions src/freedesktop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,39 +117,36 @@ pub fn list() -> Result<Vec<TrashItem>, Error> {
}
};
'trash_item: for entry in read_dir {
let info_entry;
match entry {
Ok(entry) => info_entry = entry,
let info_entry = match entry {
Ok(entry) => entry,
Err(e) => {
// Another thread or process may have removed that entry by now
debug!("Tried resolving the trash info `DirEntry` but it failed with: '{}'", e);
continue;
}
}
// Entrt should really be an info file but better safe than sorry
let file_type;
match info_entry.file_type() {
Ok(f_type) => file_type = f_type,
};
// Entrty should really be an info file but better safe than sorry
let file_type = match info_entry.file_type() {
Ok(f_type) => f_type,
Err(e) => {
// Another thread or process may have removed that entry by now
debug!("Tried getting the file type of the trash info `DirEntry` but failed with: {}", e);
continue;
}
}
};
let info_path = info_entry.path();
if !file_type.is_file() {
warn!("Found an item that's not a file, among the trash info files. This is unexpected. The path to the item is: '{:?}'", info_path);
continue;
}
let info_file;
match File::open(&info_path) {
Ok(file) => info_file = file,
let info_file = match File::open(&info_path) {
Ok(file) => file,
Err(e) => {
// Another thread or process may have removed that entry by now
debug!("Tried opening the trash info '{:?}' but failed with: {}", info_path, e);
continue;
}
}
};
let id = info_path.clone().into();
let mut name = None;
let mut original_parent: Option<PathBuf> = None;
Expand Down Expand Up @@ -501,7 +498,17 @@ fn move_items_no_replace(
try_creating_placeholders(src, dst)?;

// All placeholders are in place. LET'S OVERWRITE
execute_src_to_dst_operation(src, dst, &|_| Ok(()), &|src, dst| std::fs::rename(src, dst))?;
execute_src_to_dst_operation(src, dst, &|_| Ok(()), &|src, dst| {
if let Some(parent) = dst.parent() {
if let Err(err) = std::fs::create_dir_all(parent) {
warn!(
"Failed to create destination directory. It probably already exists. {:?}",
err
);
}
}
std::fs::rename(src, dst)
})?;

// Once everything is moved, lets recursively remove the directory
if src.is_dir() {
Expand Down Expand Up @@ -746,6 +753,7 @@ fn get_mount_points() -> Result<Vec<MountPoint>, Error> {

#[cfg(test)]
mod tests {
use serial_test::serial;
use std::{
collections::{hash_map::Entry, HashMap},
env,
Expand All @@ -766,6 +774,7 @@ mod tests {
};

#[test]
#[serial]
fn test_list() {
crate::tests::init_logging();

Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use std::{env::current_dir, error};
use log::trace;

#[cfg(test)]
pub(crate) mod tests;
pub mod tests;

#[cfg(target_os = "windows")]
#[path = "windows.rs"]
Expand Down
2 changes: 2 additions & 0 deletions src/macos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,9 +229,11 @@ mod tests {
tests::{get_unique_name, init_logging},
TrashContext,
};
use serial_test::serial;
use std::fs::File;

#[test]
#[serial]
fn test_delete_with_ns_file_manager() {
init_logging();
let mut trash_ctx = TrashContext::default();
Expand Down
136 changes: 22 additions & 114 deletions src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,137 +1,40 @@
use std::fs::{create_dir, File};
use std::path::PathBuf;
use std::sync::atomic::{AtomicI64, Ordering};
mod utils {

use log::trace;
use once_cell::sync::Lazy;
use std::sync::atomic::{AtomicI64, Ordering};

use crate::{delete, delete_all};
use once_cell::sync::Lazy;

// WARNING Expecting that `cargo test` won't be invoked on the same computer more than once within
// a single millisecond
static INSTANCE_ID: Lazy<i64> = Lazy::new(|| chrono::Local::now().timestamp_millis());
static ID_OFFSET: AtomicI64 = AtomicI64::new(0);
pub fn get_unique_name() -> String {
let id = ID_OFFSET.fetch_add(1, Ordering::SeqCst);
format!("trash-test-{}-{}", *INSTANCE_ID, id)
}

pub fn init_logging() {
let _ = env_logger::builder().is_test(true).try_init();
}

#[test]
fn test_delete_file() {
init_logging();
trace!("Started test_delete_file");

let path = get_unique_name();
File::create(&path).unwrap();

delete(&path).unwrap();
assert!(File::open(&path).is_err());
trace!("Finished test_delete_file");
}

#[test]
fn test_delete_folder() {
init_logging();
trace!("Started test_delete_folder");
// WARNING Expecting that `cargo test` won't be invoked on the same computer more than once within
// a single millisecond
static INSTANCE_ID: Lazy<i64> = Lazy::new(|| chrono::Local::now().timestamp_millis());
static ID_OFFSET: AtomicI64 = AtomicI64::new(0);

let path = PathBuf::from(get_unique_name());
create_dir(&path).unwrap();
File::create(path.join("file_in_folder")).unwrap();

assert!(path.exists());
delete(&path).unwrap();
assert!(!path.exists());

trace!("Finished test_delete_folder");
}

#[test]
fn test_delete_all() {
init_logging();
trace!("Started test_delete_all");
let count: usize = 3;

let paths: Vec<_> = (0..count).map(|i| format!("test_file_to_delete_{}", i)).collect();
for path in paths.iter() {
File::create(path).unwrap();
pub fn get_unique_name() -> String {
let id = ID_OFFSET.fetch_add(1, Ordering::SeqCst);
format!("trash-test-{}-{}", *INSTANCE_ID, id)
}

delete_all(&paths).unwrap();
for path in paths.iter() {
assert!(File::open(path).is_err());
pub fn init_logging() {
let _ = env_logger::builder().is_test(true).try_init();
}
trace!("Finished test_delete_all");
}

#[cfg(unix)]
mod unix {
use log::trace;
use std::{
fs::{create_dir, remove_dir_all, remove_file, File},
os::unix::fs::symlink,
path::Path,
};

use super::{get_unique_name, init_logging};
use crate::delete;
// use crate::init_logging;

#[test]
fn test_delete_symlink() {
init_logging();
trace!("Started test_delete_symlink");
let target_path = get_unique_name();
File::create(&target_path).unwrap();

let link_path = "test_link_to_delete";
symlink(&target_path, link_path).unwrap();

delete(link_path).unwrap();
assert!(File::open(link_path).is_err());
assert!(File::open(&target_path).is_ok());
// Cleanup
remove_file(&target_path).unwrap();
trace!("Finished test_delete_symlink");
}

#[test]
fn test_delete_symlink_in_folder() {
init_logging();
trace!("Started test_delete_symlink_in_folder");
let target_path = "test_link_target_for_delete_from_folder";
File::create(target_path).unwrap();

let folder = Path::new("test_parent_folder_for_link_to_delete");
create_dir(folder).unwrap();
let link_path = folder.join("test_link_to_delete_from_folder");
symlink(target_path, &link_path).unwrap();

delete(&link_path).unwrap();
assert!(File::open(link_path).is_err());
assert!(File::open(target_path).is_ok());
// Cleanup
remove_file(target_path).unwrap();
remove_dir_all(folder).unwrap();
trace!("Finished test_delete_symlink_in_folder");
}
}
pub use utils::{get_unique_name, init_logging};

#[cfg(any(
target_os = "windows",
all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))
))]
mod os_limited {
use super::{get_unique_name, init_logging};
use serial_test::serial;
use std::collections::{hash_map::Entry, HashMap};

use super::*;
use std::fs::File;

use crate as trash;

#[test]
#[serial]
fn list() {
const MAX_SECONDS_DIFFERENCE: i64 = 10;
init_logging();
Expand Down Expand Up @@ -202,6 +105,7 @@ mod os_limited {
}

#[test]
#[serial]
fn purge() {
init_logging();
let file_name_prefix = get_unique_name();
Expand Down Expand Up @@ -233,6 +137,7 @@ mod os_limited {
}

#[test]
#[serial]
fn restore() {
init_logging();
let file_name_prefix = get_unique_name();
Expand All @@ -250,6 +155,7 @@ mod os_limited {
.into_iter()
.filter(|x| x.name.starts_with(&file_name_prefix))
.collect();
dbg!(&targets, &names);
assert_eq!(targets.len(), file_count);
trash::os_limited::restore_all(targets).unwrap();
let remaining = trash::os_limited::list()
Expand All @@ -271,6 +177,7 @@ mod os_limited {
}

#[test]
#[serial]
fn restore_collision() {
init_logging();
let file_name_prefix = get_unique_name();
Expand Down Expand Up @@ -327,6 +234,7 @@ mod os_limited {
}

#[test]
#[serial]
fn restore_twins() {
init_logging();
let file_name_prefix = get_unique_name();
Expand Down

0 comments on commit 0e90cac

Please sign in to comment.