Files
reqlite/crates/app/tests/watcher.rs
T
2026-10-19 09:31:57 +02:00

79 lines
2.9 KiB
Rust

//! The file watcher reports external edits to .http files.
use std::sync::Arc;
use std::time::Duration;
use reqlite_app::action::Action;
use reqlite_app::effects::{Effect, Runner};
use reqlite_core::http::{HttpClient, HttpError, ResolvedRequest, Response};
use reqlite_core::CancelToken;
struct NoClient;
impl HttpClient for NoClient {
async fn send(&self, _r: ResolvedRequest, _c: CancelToken) -> Result<Response, HttpError> {
Err(HttpError::Other("unused".into()))
}
}
#[test]
fn reports_changes_to_http_and_env_files() {
let rt = tokio::runtime::Runtime::new().unwrap();
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
std::fs::write(root.join("a.http"), "GET /a\n").unwrap();
let (runner, mut rx) = Runner::new(rt.handle().clone(), None, Arc::new(NoClient), None, 4);
runner.run(Effect::Watch(Some(root.clone())));
std::thread::sleep(Duration::from_millis(200));
std::fs::write(root.join("a.http"), "GET /changed\n").unwrap();
std::fs::write(root.join("ignored.txt"), "x").unwrap();
std::fs::create_dir(root.join("sub")).unwrap();
std::fs::write(root.join("sub/new.http"), "GET /new\n").unwrap();
std::fs::write(root.join("http-client.env.json"), "{}").unwrap();
let mut seen = std::collections::HashMap::new();
let mut rescan = false;
rt.block_on(async {
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
while seen.len() < 2 || !rescan {
match tokio::time::timeout_at(deadline, rx.recv()).await {
Ok(Some(Action::FileChangedOnDisk { path, text })) => {
seen.insert(path, text);
}
Ok(Some(Action::Rescan)) => rescan = true,
Ok(Some(_)) => {}
_ => break,
}
}
});
assert_eq!(
seen.get(&root.join("a.http")),
Some(&Some("GET /changed\n".to_string()))
);
// A new folder triggers a rescan (its files may race the new watch).
assert!(rescan);
assert!(seen.contains_key(&root.join("http-client.env.json")));
assert!(!seen.contains_key(&root.join("ignored.txt")));
std::fs::remove_file(root.join("a.http")).unwrap();
let deleted = rt.block_on(async {
loop {
match tokio::time::timeout(Duration::from_secs(5), rx.recv()).await {
Ok(Some(Action::FileChangedOnDisk { path, text })) if path == root.join("a.http") => break text,
Ok(Some(_)) => {}
_ => panic!("no delete event"),
}
}
});
assert_eq!(deleted, None);
// Stopping the watch stops the events.
runner.run(Effect::Watch(None));
std::thread::sleep(Duration::from_millis(100));
while rx.try_recv().is_ok() {}
std::fs::write(root.join("b.http"), "GET /b\n").unwrap();
std::thread::sleep(Duration::from_millis(400));
assert!(rx.try_recv().is_err());
}