测试路径工具

This commit is contained in:
HouXiaoxuan
2023-12-19 22:09:01 +08:00
parent 5d7e0585bb
commit 26f3c84535
3 changed files with 46 additions and 9 deletions

2
.gitignore vendored
View File

@@ -31,4 +31,4 @@ Cargo.lock
.DS_Store
## for app test
.mit
mit_test_storage

View File

@@ -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);

View File

@@ -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<Vec<PathBuf>> {
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),
}
}
}
}