use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use limitless_cli::models::{
CheckStatus, DiagnosticResult, EnvironmentState, HealthScore, ProjectStack,
};
use limitless_cli::modules::{
auto_fix, config::PersistenceManager, diagnostics::{mentor_messages, run_full_diagnostics},
fixes, planetary::render_planetary_diagnostics_plain, stack_detector,
};
fn fixture(sub: &str) -> String {
format!("{}/tests/fixtures/{sub}", env!("CARGO_MANIFEST_DIR"))
}
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
let stamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock")
.as_nanos();
let path =
std::env::temp_dir().join(format!("limitless_it_{label}_{}", std::process::id()).to_string() + &stamp.to_string());
fs::create_dir_all(&path).expect("create temp dir");
TempDir { path }
}
fn path(&self) -> &Path {
&self.path
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
fn copy_tree(src: &Path, dst: &Path) {
fs::create_dir_all(dst).expect("create dst dir");
for entry in fs::read_dir(src).expect("read src dir") {
let entry = entry.expect("read entry");
let target = dst.join(entry.file_name());
if entry.file_type().expect("file type").is_dir() {
copy_tree(&entry.path(), &target);
} else {
fs::copy(entry.path(), &target).expect("copy file");
}
}
}
#[test]
fn test_full_diagnostic_flow() {
let state = run_full_diagnostics(&fixture("env_sample_project"));
assert!(matches!(state.detected_stack, ProjectStack::Node { .. }));
assert!(!state.diagnostics.is_empty(), "at least one check must run");
assert!(state.env_example_exists, ".env.example fixture present");
assert!(!state.env_file_exists, "no committed .env in fixture");
assert!(state.health_score.validate().is_ok());
assert!(state.health_score.percentage <= 100);
let mentor = mentor_messages(&state.diagnostics);
assert!(
!mentor.is_empty(),
"an env warning should translate to at least one mentor hint"
);
assert_eq!(state.failed_checks(), state.health_score.failed as usize);
}
#[tokio::test]
async fn test_auto_fix_all_workflow() {
let state = EnvironmentState {
detected_stack: ProjectStack::Node {
version: "18.12.0".into(),
package_manager: "npm".into(),
},
runtime_version: Some("v18.12.0".into()),
env_file_exists: false,
env_example_exists: true,
dependencies_healthy: true,
blocked_ports: Vec::new(),
diagnostics: vec![DiagnosticResult::new(
"Env Audit",
CheckStatus::Warn,
".env.example present but .env missing",
)],
health_score: HealthScore::from_counts(0, 1, 0),
};
let dir = TempDir::new("auto_fix");
copy_tree(Path::new(&fixture("env_sample_project")), &dir.path().join("repo"));
let report = auto_fix::run_auto_fix_safe(&state, dir.path().join("repo").to_str().unwrap())
.await;
assert!(report.fixes_applied >= 1, "env copy should be applied");
assert_eq!(report.fixes_failed, 0);
assert!(
dir.path().join("repo").join(".env").exists(),
"the .env file must have been created"
);
assert!(report.is_clean() || report.after_score >= report.before_score);
assert!(report.issues_remaining.iter().all(|i| !i.is_empty()));
}
#[test]
fn test_planetary_mode_rendering() {
let results = vec![
DiagnosticResult::new(
"Dependencies",
CheckStatus::Fail,
"node_modules/ is missing",
),
DiagnosticResult::new("Env Audit", CheckStatus::Pass, ".env present"),
];
let report = render_planetary_diagnostics_plain(&results);
assert!(report.contains("PLANETARY MODE"));
assert!(report.contains("Mission Health:"), "health bar must render");
assert!(report.contains('│'), "report must be boxed");
assert!(!report.contains("\x1b["), "plain report must be ANSI-free");
}
#[test]
fn test_config_persistence() {
let dir = TempDir::new("config");
let pm = PersistenceManager::at_dir(dir.path());
let init = pm.init_config().expect("init config");
assert_eq!(init, limitless_cli::modules::config::LimitlessConfig::default());
assert!(dir.path().join("config.json").exists());
let mut config = init.clone();
config.color_enabled = false;
pm.save_config(&config).expect("save config");
assert_eq!(
pm.load_config().expect("load config").expect("some config"),
config,
"config must round-trip"
);
let stats = pm.load_stats().expect("load stats");
assert_eq!(stats.diagnostics_run, 0, "fresh stats are zeroed");
let mut stats = stats;
stats.record_diagnostic(1);
pm.save_stats(&stats).expect("save stats");
let loaded = pm.load_stats().expect("load stats again");
assert_eq!(loaded.diagnostics_run, 1, "stats must round-trip");
assert!(dir.path().join("stats.json").exists());
let cache = EnvironmentState {
detected_stack: ProjectStack::Node {
version: "18.12.0".into(),
package_manager: "npm".into(),
},
runtime_version: Some("v18.12.0".into()),
env_file_exists: true,
env_example_exists: true,
dependencies_healthy: true,
blocked_ports: Vec::new(),
diagnostics: vec![DiagnosticResult::new("Env Audit", CheckStatus::Pass, "ok")],
health_score: HealthScore::from_counts(1, 0, 0),
};
pm.cache_diagnostics(&cache).expect("cache state");
let cached = pm.get_cached_diagnostics().expect("cached state present");
assert_eq!(cached, cache, "cache must round-trip");
assert!(dir.path().join("cache.json").exists());
}
#[test]
fn test_go_and_java_stack_detection() {
let dir = TempDir::new("go_stack");
fs::write(dir.path().join("go.mod"), "module example.com/test\n\ngo 1.22\n").unwrap();
let stack = stack_detector::detect_stack(dir.path().to_str().unwrap());
assert!(matches!(stack, ProjectStack::Go { .. }));
assert_eq!(stack.label(), "Go");
let java_dir = TempDir::new("java_stack");
fs::write(java_dir.path().join("pom.xml"), "<project></project>\n").unwrap();
let java_stack = stack_detector::detect_stack(java_dir.path().to_str().unwrap());
assert!(matches!(java_stack, ProjectStack::Java { .. }));
assert_eq!(java_stack.label(), "Java");
}
#[test]
fn test_dynamic_package_manager_fixes() {
let pnpm_stack = ProjectStack::Node {
version: "20.0.0".into(),
package_manager: "pnpm".into(),
};
let fix = fixes::install_fix_for_stack(&pnpm_stack).expect("install fix");
if let fixes::FixCommand::RunCommand { cmd, args } = fix.command {
assert_eq!(cmd, "pnpm");
assert_eq!(args, vec!["install"]);
} else {
panic!("expected RunCommand");
}
let yarn_stack = ProjectStack::Node {
version: "20.0.0".into(),
package_manager: "yarn".into(),
};
let fix_yarn = fixes::install_fix_for_stack(&yarn_stack).expect("install fix");
if let fixes::FixCommand::RunCommand { cmd, args } = fix_yarn.command {
assert_eq!(cmd, "yarn");
assert_eq!(args, vec!["install"]);
} else {
panic!("expected RunCommand");
}
}