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 /// 获取 dadk配置模版的路径 23 pub fn templates_dir(&self) -> PathBuf { 24 const TEMPLATES_DIR: &str = "templates"; 25 self.abs_path(TEMPLATES_DIR) 26 } 27 } 28 29 impl TestContext for DadkConfigTestContext { 30 fn setup() -> Self { 31 env_logger::try_init_from_env(env_logger::Env::default().default_filter_or("info")).ok(); 32 33 // 获取dadk-config包的根目录 34 let mut test_base_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); 35 test_base_path.pop(); 36 test_base_path.pop(); 37 test_base_path.push("dadk-config"); 38 log::debug!( 39 "DadkConfigTestContext setup: project_base_path={:?}", 40 test_base_path 41 ); 42 // 设置workdir 43 std::env::set_current_dir(&test_base_path).expect("Failed to setup test base path"); 44 45 let r = DadkConfigTestContext { test_base_path }; 46 47 r 48 } 49 } 50 51 #[cfg(test)] 52 mod tests { 53 use super::*; 54 use std::env; 55 56 #[test] 57 fn test_test_base_path() { 58 let test_context = DadkConfigTestContext::setup(); 59 let expected_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) 60 .parent() 61 .unwrap() 62 .parent() 63 .unwrap() 64 .join("dadk-config"); 65 assert_eq!(test_context.test_base_path(), &expected_path); 66 } 67 68 #[test] 69 fn test_abs_path() { 70 let test_context = DadkConfigTestContext::setup(); 71 let relative_path = "some_relative_path"; 72 let expected_path = test_context.test_base_path().join(relative_path); 73 assert_eq!(test_context.abs_path(relative_path), expected_path); 74 } 75 } 76