1 pub extern crate test_context; 2 3 use std::path::PathBuf; 4 5 use simple_logger::SimpleLogger; 6 use test_context::TestContext; 7 8 #[derive(Debug, Clone)] 9 pub struct BaseTestContext { 10 /// 项目的根目录 11 project_base_path: PathBuf, 12 } 13 14 impl BaseTestContext { 15 const CONFIG_V1_DIR: &'static str = "tests/data/dadk_config_v1"; 16 const FAKE_DRAGONOS_SYSROOT: &'static str = "tests/data/fake_dragonos_sysroot"; 17 const FAKE_DADK_CACHE_ROOT: &'static str = "tests/data/fake_dadk_cache_root"; 18 19 /// 获取项目的根目录 20 pub fn project_base_path(&self) -> &PathBuf { 21 &self.project_base_path 22 } 23 24 /// 获取项目目录下的文件的的绝对路径 25 pub fn abs_path(&self, relative_path: &str) -> PathBuf { 26 self.project_base_path.join(relative_path) 27 } 28 29 /// 获取`xxx.dadk`配置文件的目录 30 pub fn config_v1_dir(&self) -> PathBuf { 31 self.abs_path(Self::CONFIG_V1_DIR) 32 } 33 34 fn ensure_fake_dragonos_dir_exist(&self) { 35 let fake_dragonos_dir = self.fake_dragonos_sysroot(); 36 if !fake_dragonos_dir.exists() { 37 std::fs::create_dir_all(&fake_dragonos_dir).ok(); 38 } 39 } 40 41 fn ensure_fake_dadk_cache_root_exist(&self) { 42 std::env::set_var( 43 "DADK_CACHE_ROOT", 44 self.fake_dadk_cache_root().to_str().unwrap(), 45 ); 46 let fake_dadk_cache_root = self.fake_dadk_cache_root(); 47 if !fake_dadk_cache_root.exists() { 48 std::fs::create_dir_all(&fake_dadk_cache_root).ok(); 49 } 50 } 51 52 pub fn fake_dadk_cache_root(&self) -> PathBuf { 53 self.abs_path(Self::FAKE_DADK_CACHE_ROOT) 54 } 55 56 /// 获取假的DragonOS sysroot目录 57 pub fn fake_dragonos_sysroot(&self) -> PathBuf { 58 self.abs_path(Self::FAKE_DRAGONOS_SYSROOT) 59 } 60 } 61 62 impl TestContext for BaseTestContext { 63 fn setup() -> Self { 64 let logger = SimpleLogger::new().with_level(log::LevelFilter::Debug); 65 66 logger.init().ok(); 67 // 获取DADK项目的根目录 68 let mut project_base_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); 69 project_base_path.pop(); 70 project_base_path.pop(); 71 // 设置workdir 72 std::env::set_current_dir(&project_base_path).ok(); 73 74 let r = BaseTestContext { project_base_path }; 75 r.ensure_fake_dragonos_dir_exist(); 76 r.ensure_fake_dadk_cache_root_exist(); 77 r 78 } 79 } 80