1 use std::path::PathBuf; 2 3 use test_context::TestContext; 4 5 #[derive(Debug, Clone)] 6 pub struct DadkConfigTestContext { 7 /// 项目的根目录 8 test_base_path: PathBuf, 9 } 10 11 impl DadkConfigTestContext { 12 /// 获取项目的根目录 13 pub fn test_base_path(&self) -> &PathBuf { 14 &self.test_base_path 15 } 16 17 /// 获取项目目录下的文件的的绝对路径 18 pub fn abs_path(&self, relative_path: &str) -> PathBuf { 19 self.test_base_path.join(relative_path) 20 } 21 } 22 23 impl TestContext for DadkConfigTestContext { 24 fn setup() -> Self { 25 env_logger::try_init_from_env(env_logger::Env::default().default_filter_or("info")).ok(); 26 27 // 获取dadk-config包的根目录 28 let mut test_base_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); 29 test_base_path.pop(); 30 test_base_path.pop(); 31 test_base_path.push("dadk-config"); 32 log::debug!( 33 "DadkConfigTestContext setup: project_base_path={:?}", 34 test_base_path 35 ); 36 // 设置workdir 37 std::env::set_current_dir(&test_base_path).expect("Failed to setup test base path"); 38 39 let r = DadkConfigTestContext { test_base_path }; 40 41 r 42 } 43 } 44 45 #[cfg(test)] 46 mod tests { 47 use super::*; 48 use std::env; 49 50 #[test] 51 fn test_test_base_path() { 52 let test_context = DadkConfigTestContext::setup(); 53 let expected_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) 54 .parent() 55 .unwrap() 56 .parent() 57 .unwrap() 58 .join("dadk-config"); 59 assert_eq!(test_context.test_base_path(), &expected_path); 60 } 61 62 #[test] 63 fn test_abs_path() { 64 let test_context = DadkConfigTestContext::setup(); 65 let relative_path = "some_relative_path"; 66 let expected_path = test_context.test_base_path().join(relative_path); 67 assert_eq!(test_context.abs_path(relative_path), expected_path); 68 } 69 } 70