diff --git a/.gitignore b/.gitignore index 28b4735..d0c786e 100644 --- a/.gitignore +++ b/.gitignore @@ -31,4 +31,4 @@ Cargo.lock .DS_Store ## for app test -.mit \ No newline at end of file +mit_test_storage \ No newline at end of file diff --git a/src/store.rs b/src/store.rs index f0eb4cf..ed53d59 100644 --- a/src/store.rs +++ b/src/store.rs @@ -12,9 +12,7 @@ impl Store { panic!("不是合法的mit仓库"); } let store_path = util::get_storage_path().unwrap(); - Store { - store_path, - } + Store { store_path } } pub fn load(&self, hash: &String) -> String { /* 读取文件内容 */ @@ -43,15 +41,26 @@ impl Store { } #[cfg(test)] mod tests { + use crate::commands::init; + use super::*; #[test] - fn test_new() { + fn test_new_success() { + util::setup_test_with_mit(); + let _ = Store::new(); + } + + #[test] + #[should_panic] + fn test_new_fail() { + util::setup_test_without_mit(); let _ = Store::new(); } #[test] fn test_save_and_load() { + let _ = util::setup_test_with_mit(); let store = Store::new(); let content = "hello world".to_string(); let hash = store.save(&content); diff --git a/src/utils/util.rs b/src/utils/util.rs index 749bafe..6be7ea0 100644 --- a/src/utils/util.rs +++ b/src/utils/util.rs @@ -1,8 +1,35 @@ -use std::{fs, io}; -use std::path::{Path, PathBuf}; use sha1::{Digest, Sha1}; +use std::path::{Path, PathBuf}; +use std::{fs, io}; pub const ROOT_DIR: &str = ".mit"; +pub const TEST_DIR: &str = "mit_test_storage"; // 执行测试的储存库 + +pub fn setup_test_dir() { + let path = std::env::var("CARGO_MANIFEST_DIR").unwrap(); + let mut path = PathBuf::from(path); + path.push(TEST_DIR); + if !path.exists() { + fs::create_dir(&path).unwrap(); + } + std::env::set_current_dir(&path).unwrap(); +} + +pub fn setup_test_with_mit() { + // 将执行目录切换到测试目录 + setup_test_dir(); + let _ = crate::commands::init::init(); +} + +pub fn setup_test_without_mit() { + // 将执行目录切换到测试目录,并清除测试目录下的.mit目录 + setup_test_dir(); + let mut path = std::env::current_dir().unwrap(); + path.push(ROOT_DIR); + if path.exists() { + fs::remove_dir_all(&path).unwrap(); + } +} pub fn calc_hash(data: &String) -> String { let mut hasher = Sha1::new(); @@ -63,7 +90,8 @@ pub fn list_files(path: &Path) -> io::Result> { let mut files = Vec::new(); if path.is_dir() { - if path.file_name().unwrap_or_default() == ROOT_DIR { // 跳过 .mit 目录 + if path.file_name().unwrap_or_default() == ROOT_DIR { + // 跳过 .mit 目录 return Ok(files); } for entry in fs::read_dir(path)? { @@ -148,4 +176,4 @@ mod tests { Err(err) => println!("{}", err), } } -} \ No newline at end of file +}