use parking_lot::Mutex;
use std::fs;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use symforge::live_index::LiveIndex;
use symforge::watcher::{WatcherInfo, WatcherState, run_watcher};
use tempfile::TempDir;
fn write_file(dir: &Path, name: &str, content: &str) {
let path = dir.join(name);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).unwrap();
}
fs::write(path, content).unwrap();
}
async fn spawn_watcher(
dir: &TempDir,
shared: &symforge::live_index::SharedIndex,
) -> Arc<Mutex<WatcherInfo>> {
let watcher_info = Arc::new(Mutex::new(WatcherInfo::default()));
let root = dir.path().to_path_buf();
let index_clone = Arc::clone(shared);
let info_clone = Arc::clone(&watcher_info);
tokio::spawn(async move {
run_watcher(root, index_clone, info_clone).await;
});
tokio::time::sleep(Duration::from_millis(100)).await;
watcher_info
}
async fn wait_debounce() {
tokio::time::sleep(Duration::from_millis(500)).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_detects_modify_and_updates_index() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
write_file(dir.path(), "src/hello.rs", "fn hello() {}");
let shared = LiveIndex::load(dir.path()).unwrap();
{
let index = shared.read();
let file = index
.get_file("src/hello.rs")
.expect("src/hello.rs should be indexed");
let names: Vec<&str> = file.symbols.iter().map(|s| s.name.as_str()).collect();
assert!(
names.contains(&"hello"),
"initial symbol 'hello' should exist: {names:?}"
);
}
let _watcher_info = spawn_watcher(&dir, &shared).await;
write_file(dir.path(), "src/hello.rs", "fn hello_world() {}");
wait_debounce().await;
{
let index = shared.read();
let file = index
.get_file("src/hello.rs")
.expect("src/hello.rs should still be in index");
let names: Vec<&str> = file.symbols.iter().map(|s| s.name.as_str()).collect();
assert!(
names.contains(&"hello_world"),
"FRSH-01/03/06: updated symbol 'hello_world' should be in index after edit, got: {names:?}"
);
assert!(
!names.contains(&"hello"),
"FRSH-06: old symbol 'hello' must be gone after overwrite, got: {names:?}"
);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_indexes_new_file() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
write_file(dir.path(), "src/existing.rs", "fn existing() {}");
let shared = LiveIndex::load(dir.path()).unwrap();
let initial_count = shared.read().file_count();
let _watcher_info = spawn_watcher(&dir, &shared).await;
write_file(dir.path(), "src/new_file.rs", "fn new_function() {}");
wait_debounce().await;
{
let index = shared.read();
let new_count = index.file_count();
assert_eq!(
new_count,
initial_count + 1,
"FRSH-04: file_count should have increased by 1 after creating new_file.rs"
);
let file = index
.get_file("src/new_file.rs")
.expect("FRSH-04: src/new_file.rs should be in index after create");
let names: Vec<&str> = file.symbols.iter().map(|s| s.name.as_str()).collect();
assert!(
names.contains(&"new_function"),
"FRSH-04: new file should have 'new_function' symbol, got: {names:?}"
);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_removes_deleted_file() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
write_file(dir.path(), "src/to_delete.rs", "fn doomed() {}");
write_file(dir.path(), "src/stable.rs", "fn keeper() {}");
let shared = LiveIndex::load(dir.path()).unwrap();
{
let index = shared.read();
assert_eq!(index.file_count(), 2, "should have 2 files initially");
assert!(
index.get_file("src/to_delete.rs").is_some(),
"src/to_delete.rs should be in index before delete"
);
}
let _watcher_info = spawn_watcher(&dir, &shared).await;
fs::remove_file(dir.path().join("src/to_delete.rs")).unwrap();
wait_debounce().await;
{
let index = shared.read();
assert!(
index.get_file("src/to_delete.rs").is_none(),
"FRSH-05: src/to_delete.rs should be removed from index after deletion"
);
assert_eq!(
index.file_count(),
1,
"FRSH-05: file_count should decrease to 1 after deletion"
);
assert!(
index.get_file("src/stable.rs").is_some(),
"src/stable.rs should still be in index after unrelated file was deleted"
);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_hash_skip_on_noop_write() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
let content = "fn stable() {}";
write_file(dir.path(), "src/stable.rs", content);
let shared = LiveIndex::load(dir.path()).unwrap();
let initial_symbols: Vec<String> = {
let index = shared.read();
let file = index.get_file("src/stable.rs").unwrap();
file.symbols.iter().map(|s| s.name.clone()).collect()
};
let watcher_info = spawn_watcher(&dir, &shared).await;
let events_before = watcher_info.lock().events_processed;
write_file(dir.path(), "src/stable.rs", content);
wait_debounce().await;
{
let index = shared.read();
let file = index
.get_file("src/stable.rs")
.expect("src/stable.rs should still be indexed after noop write");
let after_symbols: Vec<String> = file.symbols.iter().map(|s| s.name.clone()).collect();
assert_eq!(
initial_symbols, after_symbols,
"hash-skip: symbols should be unchanged after writing identical content"
);
}
let events_after = watcher_info.lock().events_processed;
let _ = events_before; let _ = events_after;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_enoent_handled_gracefully() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
write_file(dir.path(), "src/fragile.rs", "fn at_risk() {}");
write_file(dir.path(), "src/anchor.rs", "fn anchor() {}");
let shared = LiveIndex::load(dir.path()).unwrap();
let watcher_info = spawn_watcher(&dir, &shared).await;
fs::remove_file(dir.path().join("src/fragile.rs")).unwrap();
wait_debounce().await;
{
let index = shared.read();
assert!(
index.get_file("src/fragile.rs").is_none(),
"RELY-03: fragile.rs should be removed from index after deletion"
);
}
{
let info = watcher_info.lock();
assert_eq!(
info.state,
WatcherState::Active,
"RELY-03: watcher should remain Active after ENOENT; got: {:?}",
info.state
);
}
}
#[test]
fn test_single_file_reparse_under_50ms() {
use std::time::Instant;
use symforge::domain::LanguageId;
use symforge::parsing;
let source = r#"
/// A moderately complex function for benchmarking the parser.
pub fn compute_sum(items: &[u32]) -> u32 {
let mut total = 0u32;
for &item in items {
if item % 2 == 0 {
total += item;
} else {
total = total.saturating_add(item * 2);
}
}
total
}
pub struct Accumulator {
values: Vec<u32>,
threshold: u32,
}
impl Accumulator {
pub fn new(threshold: u32) -> Self {
Self { values: Vec::new(), threshold }
}
pub fn push(&mut self, val: u32) {
self.values.push(val);
}
pub fn result(&self) -> u32 {
self.values.iter().copied().sum()
}
}
"#;
let bytes = source.as_bytes();
let start = Instant::now();
let _result = parsing::process_file("bench.rs", bytes, LanguageId::Rust);
let elapsed = start.elapsed();
assert!(
elapsed < Duration::from_millis(50),
"FRSH-02: single-file re-parse must complete in <50ms, took {}ms",
elapsed.as_millis()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_state_reports_active() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
write_file(dir.path(), "src/code.rs", "fn main() {}");
let shared = LiveIndex::load(dir.path()).unwrap();
let watcher_info = spawn_watcher(&dir, &shared).await;
tokio::time::sleep(Duration::from_millis(200)).await;
let state = watcher_info.lock().state.clone();
assert_eq!(
state,
WatcherState::Active,
"watcher state should be Active after initialization, got: {:?}",
state
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_ignores_non_source_files() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
write_file(dir.path(), "src/code.rs", "fn main() {}");
let shared = LiveIndex::load(dir.path()).unwrap();
let initial_count = shared.read().file_count();
let _watcher_info = spawn_watcher(&dir, &shared).await;
write_file(dir.path(), "notes.txt", "some notes");
write_file(dir.path(), "data.csv", "a,b,c");
wait_debounce().await;
{
let index = shared.read();
assert_eq!(
index.file_count(),
initial_count,
"watcher should not index non-source files; count should remain {initial_count}, got {}",
index.file_count()
);
assert!(
index.get_file("notes.txt").is_none(),
"notes.txt should NOT be in the index (unsupported extension)"
);
assert!(
index.get_file("data.csv").is_none(),
"data.csv should NOT be in the index (unsupported extension)"
);
}
}