Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Refactor background command test timing to reduce flakiness
Maximilian Roos748baf06bf15
diff --git a/CLAUDE.md b/CLAUDE.mdindex 61c784485..eeceb1e5f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -506,6 +506,29 @@ Users can clean up old logs manually or use a git hook. No automatic cleanup is## Testing Guidelines+### Timing Tests: Poll with Long Timeouts++Tests waiting for background operations must **poll with long timeouts**, never use fixed sleeps. Use the helpers in `tests/common/mod.rs`:++```rust+use crate::common::{wait_for_file, wait_for_file_count};++// ✅ Poll for file existence with 5+ second timeout+wait_for_file(&log_file, Duration::from_secs(5));++// ✅ Poll for multiple files+wait_for_file_count(&log_dir, "log", 3, Duration::from_secs(5));+```++These use exponential backoff (10ms → 500ms cap) for fast initial checks that back off on slow CI.++**Exception - testing absence:** When verifying something did NOT happen, polling doesn't work. Use a fixed 500ms+ sleep:++```rust+thread::sleep(Duration::from_millis(500));+assert!(!marker_file.exists(), "Command should NOT have run");+```+### Testing with --execute CommandsUse `--force` to skip interactive prompts in tests. Don't pipe input to stdin.diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex c29bfd88d..99bb09307 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -848,6 +848,64 @@ pub fn validate_ansi_codes(text: &str) -> Vec<String> {warnings}+// ============================================================================+// Timing utilities for background command tests+// ============================================================================++/// Poll with exponential backoff: 10ms → 20ms → 40ms → ... → 500ms max.+/// Fast initial checks catch quick completions; backs off to reduce CPU on slow CI.+fn exponential_sleep(attempt: u32) {+ let ms = (10 * (1 << attempt)).min(500);+ std::thread::sleep(std::time::Duration::from_millis(ms));+}++/// Wait for a file to exist, polling with exponential backoff.+/// Use this instead of fixed sleeps for background commands to avoid flaky tests.+pub fn wait_for_file(path: &Path, timeout: std::time::Duration) {+ let start = std::time::Instant::now();+ let mut attempt = 0;+ while start.elapsed() < timeout {+ if path.exists() {+ return;+ }+ exponential_sleep(attempt);+ attempt += 1;+ }+ panic!(+ "File was not created within {:?}: {}",+ timeout,+ path.display()+ );+}++/// Wait for a directory to contain at least `expected_count` files with a given extension.+pub fn wait_for_file_count(+ dir: &Path,+ extension: &str,+ expected_count: usize,+ timeout: std::time::Duration,+) {+ let start = std::time::Instant::now();+ let mut attempt = 0;+ while start.elapsed() < timeout {+ if let Ok(entries) = std::fs::read_dir(dir) {+ let count = entries+ .filter_map(|e| e.ok())+ .filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some(extension))+ .count();+ if count >= expected_count {+ return;+ }+ }+ exponential_sleep(attempt);+ attempt += 1;+ }+ panic!(+ "Expected {} .{} files in {:?} within {:?}",+ expected_count, extension, dir, timeout+ );+}+#[cfg(test)]mod tests {use super::*;diff --git a/tests/integration_tests/.post_start_commands.rs.pending-snap b/tests/integration_tests/.post_start_commands.rs.pending-snapnew file mode 100644index 000000000..38da46190--- /dev/null+++ b/tests/integration_tests/.post_start_commands.rs.pending-snap@@ -0,0 +1,29 @@+{"run_id":"1764011909-35386000","line":673,"new":{"module_name":"integration__integration_tests__post_start_commands","snapshot_name":"post_start_complex_shell_commands","metadata":{"source":"tests/integration_tests/post_start_commands.rs","assertion_line":673,"expression":"contents"},"snapshot":""},"old":{"module_name":"integration__integration_tests__post_start_commands","metadata":{},"snapshot":"line2"}}+{"run_id":"1764011909-35386000","line":479,"new":null,"old":null}+{"run_id":"1764011909-35386000","line":720,"new":null,"old":null}+{"run_id":"1764011920-591405000","line":673,"new":null,"old":null}+{"run_id":"1764011928-675839000","line":778,"new":null,"old":null}+{"run_id":"1764011928-675839000","line":673,"new":{"module_name":"integration__integration_tests__post_start_commands","snapshot_name":"post_start_complex_shell_commands","metadata":{"source":"tests/integration_tests/post_start_commands.rs","assertion_line":673,"expression":"contents"},"snapshot":""},"old":{"module_name":"integration__integration_tests__post_start_commands","metadata":{},"snapshot":"line2"}}+{"run_id":"1764011928-675839000","line":479,"new":{"module_name":"integration__integration_tests__post_start_commands","snapshot_name":"post_start_log_file_captures_output","metadata":{"source":"tests/integration_tests/post_start_commands.rs","assertion_line":479,"expression":"log_contents"},"snapshot":""},"old":{"module_name":"integration__integration_tests__post_start_commands","metadata":{},"snapshot":"stdout output\nstderr output"}}+{"run_id":"1764011928-675839000","line":720,"new":null,"old":null}+{"run_id":"1764011942-996292000","line":479,"new":null,"old":null}+{"run_id":"1764011959-17122000","line":778,"new":null,"old":null}+{"run_id":"1764011959-17122000","line":673,"new":null,"old":null}+{"run_id":"1764011959-17122000","line":479,"new":null,"old":null}+{"run_id":"1764011959-17122000","line":720,"new":null,"old":null}+{"run_id":"1764011975-846206000","line":778,"new":null,"old":null}+{"run_id":"1764011975-846206000","line":673,"new":null,"old":null}+{"run_id":"1764011975-846206000","line":479,"new":null,"old":null}+{"run_id":"1764011975-846206000","line":720,"new":null,"old":null}+{"run_id":"1764011978-729122000","line":673,"new":null,"old":null}+{"run_id":"1764011978-729122000","line":778,"new":null,"old":null}+{"run_id":"1764011978-729122000","line":479,"new":null,"old":null}+{"run_id":"1764011978-729122000","line":720,"new":null,"old":null}+{"run_id":"1764011982-442283000","line":673,"new":null,"old":null}+{"run_id":"1764011982-442283000","line":778,"new":null,"old":null}+{"run_id":"1764011982-442283000","line":479,"new":null,"old":null}+{"run_id":"1764011982-442283000","line":720,"new":null,"old":null}+{"run_id":"1764012167-354610000","line":623,"new":null,"old":null}+{"run_id":"1764012167-354610000","line":728,"new":null,"old":null}+{"run_id":"1764012167-354610000","line":429,"new":null,"old":null}+{"run_id":"1764012167-354610000","line":670,"new":null,"old":null}diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rsindex 571530edc..8481ea362 100644--- a/tests/integration_tests/post_start_commands.rs+++ b/tests/integration_tests/post_start_commands.rs@@ -1,33 +1,17 @@-use crate::common::{TestRepo, make_snapshot_cmd, resolve_git_common_dir, setup_snapshot_settings};+use crate::common::{+ TestRepo, make_snapshot_cmd, resolve_git_common_dir, setup_snapshot_settings, wait_for_file,+ wait_for_file_count,+};use insta::assert_snapshot;use insta_cmd::assert_cmd_snapshot;use std::fs;-use std::path::Path;use std::thread;-use std::time::{Duration, Instant};+use std::time::Duration;-// Sleep duration constants for background command tests-// These allow time for background processes to complete and write output files--/// Short wait for fast commands (simple echo statements) - used when checking for file absence-const SLEEP_FAST_COMMAND: Duration = Duration::from_millis(100);--/// Wait for a file to exist, polling with a timeout-/// Use this instead of fixed sleeps for background commands to avoid flaky tests-fn wait_for_file(path: &Path, timeout: Duration) {- let start = Instant::now();- while start.elapsed() < timeout {- if path.exists() {- return;- }- thread::sleep(Duration::from_millis(50));- }- panic!(- "File was not created within {:?}: {}",- timeout,- path.display()- );-}+/// Wait duration when checking file absence (testing command did NOT run).+/// Must be long enough that a background command would have started and created+/// the file if it were going to. 500ms gives CI systems breathing room.+const SLEEP_FOR_ABSENCE_CHECK: Duration = Duration::from_millis(500);/// Helper to create snapshot with normalized paths and SHAs///@@ -513,27 +497,18 @@ approved-commands = [snapshot_switch("post_start_separate_logs", &repo, &["--create", "feature"]);- // Wait for log directory to be created+ // Wait for all 3 log files to be created (poll, don't use fixed sleep)let worktree_path = repo.root_path().parent().unwrap().join("test-repo.feature");let git_common_dir = resolve_git_common_dir(&worktree_path);let log_dir = git_common_dir.join("wt-logs");- wait_for_file(log_dir.as_path(), Duration::from_secs(5));+ wait_for_file_count(&log_dir, "log", 3, Duration::from_secs(5));- // Wait briefly for all log files to be written- thread::sleep(Duration::from_millis(100));let log_files: Vec<_> = fs::read_dir(&log_dir).unwrap().filter_map(|e| e.ok()).filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("log")).collect();- assert_eq!(- log_files.len(),- 3,- "Should have 3 separate log files, found: {}",- log_files.len()- );-// Read all log files and verify no cross-contaminationlet mut found_outputs = vec![false, false, false];for entry in log_files {@@ -800,8 +775,8 @@ approved-commands = ["echo 'POST-START-RAN' > post_start_marker.txt"]// Second: Switch to EXISTING worktree - post-start should NOT runsnapshot_switch("post_start_skip_existing", &repo, &["feature"]);- // Wait briefly to ensure no background command starts- thread::sleep(SLEEP_FAST_COMMAND);+ // Wait to ensure no background command starts (testing absence requires fixed wait)+ thread::sleep(SLEEP_FOR_ABSENCE_CHECK);// Verify post-start did NOT run when switching to existing worktreeassert!(