use ix::builder::Builder;
use std::fs;
use tempfile::tempdir;
#[test]
fn test_build_preserves_existing_index_on_failure() {
let dir = tempdir().unwrap();
let root = dir.path();
fs::write(root.join("test.txt"), "hello world").unwrap();
let mut builder = Builder::new(root).unwrap();
let first_index = builder.build().unwrap();
assert!(first_index.exists());
let first_size = first_index.metadata().unwrap().len();
fs::write(root.join("test.txt"), "hello world again").unwrap();
let mut builder2 = Builder::new(root).unwrap();
let second_index = builder2.build().unwrap();
assert!(second_index.exists());
let second_size = second_index.metadata().unwrap().len();
assert_ne!(first_size, second_size);
}
#[test]
fn test_orphaned_shard_cleanup() {
let dir = tempdir().unwrap();
let root = dir.path();
let ix_dir = root.join(".ix");
fs::write(root.join("test.txt"), "hello world").unwrap();
let mut builder = Builder::new(root).unwrap();
builder.build().unwrap();
fs::write(ix_dir.join("shard.ix.run.0"), "orphan1").unwrap();
fs::write(ix_dir.join("shard.ix.merged.0.12345"), "orphan2").unwrap();
assert!(ix_dir.join("shard.ix.run.0").exists());
assert!(ix_dir.join("shard.ix.merged.0.12345").exists());
let mut builder2 = Builder::new(root).unwrap();
builder2.build().unwrap();
assert!(!ix_dir.join("shard.ix.run.0").exists());
assert!(!ix_dir.join("shard.ix.merged.0.12345").exists());
}
#[test]
fn test_backup_index_on_rebuild() {
let dir = tempdir().unwrap();
let root = dir.path();
fs::write(root.join("test.txt"), "version 1").unwrap();
let mut builder = Builder::new(root).unwrap();
let first_index = builder.build().unwrap();
assert!(first_index.exists());
fs::write(root.join("test.txt"), "version 2").unwrap();
let mut builder2 = Builder::new(root).unwrap();
let second_index = builder2.build().unwrap();
assert!(second_index.exists());
let backup_path = root.join(".ix/shard.ix.bak");
assert!(!backup_path.exists());
}
#[test]
fn test_concurrent_file_modification_grace_period() {
let dir = tempdir().unwrap();
let root = dir.path();
fs::write(root.join("test.txt"), "hello world").unwrap();
let mut builder = Builder::new(root).unwrap();
builder.build().unwrap();
fs::write(root.join("test.txt"), "modified content").unwrap();
let index_path = root.join(".ix/shard.ix");
let reader = ix::reader::Reader::open(&index_path).unwrap();
let mut executor = ix::executor::Executor::new(&reader);
let plan = ix::planner::Planner::plan("hello", false);
let result = executor.execute(&plan, &ix::executor::QueryOptions::default());
assert!(
result.is_ok(),
"Should be able to query even with recent modification"
);
}