Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Fix flaky tests by replacing fixed sleeps with polling (#124)
Maximilian Roosbc8c4b1f0489
diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex a67938018..f6eec7aa1 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -1124,6 +1124,30 @@ pub fn wait_for_file_lines(path: &Path, expected_lines: usize, timeout: std::tim);}+/// Wait for a file to contain valid JSON, polling with exponential backoff.+/// Use when a background process writes JSON that may be partially written.+pub fn wait_for_valid_json(path: &Path, timeout: std::time::Duration) -> serde_json::Value {+ let start = std::time::Instant::now();+ let mut attempt = 0;+ let mut last_error = String::new();+ while start.elapsed() < timeout {+ if let Ok(content) = std::fs::read_to_string(path) {+ match serde_json::from_str(&content) {+ Ok(json) => return json,+ Err(e) => last_error = format!("{e} (content: {content})"),+ }+ }+ exponential_sleep(attempt);+ attempt += 1;+ }+ panic!(+ "File did not contain valid JSON within {:?}: {}\nLast error: {}",+ timeout,+ path.display(),+ last_error+ );+}+/// Convert Unix timestamp to ISO 8601 format for consistent git date handling////// Git interprets `@timestamp` format inconsistently across versions and platforms.diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rsindex 3a2be4d80..406ad7bce 100644--- a/tests/integration_tests/post_start_commands.rs+++ b/tests/integration_tests/post_start_commands.rs@@ -1,6 +1,6 @@use crate::common::{TestRepo, make_snapshot_cmd, resolve_git_common_dir, setup_snapshot_settings, wait_for_file,- wait_for_file_content, wait_for_file_count, wait_for_file_lines,+ wait_for_file_content, wait_for_file_count, wait_for_file_lines, wait_for_valid_json,};use insta::assert_snapshot;use insta_cmd::assert_cmd_snapshot;@@ -581,21 +581,10 @@ approved-commands = ["cat > context.json"]String::from_utf8_lossy(&output.stderr));- // Find the worktree and wait for the background command to write the file+ // Find the worktree and wait for valid JSON (polls until cat finishes writing)let worktree_path = repo.root_path().parent().unwrap().join("repo.bg-json");let json_file = worktree_path.join("context.json");-- // Wait for file to exist and have content (cat creates empty file immediately)- wait_for_file(&json_file, Duration::from_secs(5));-- // Give time for printf to pipe through- thread::sleep(Duration::from_millis(500));-- let contents = fs::read_to_string(&json_file).unwrap();-- // Parse and verify the JSON- let json: serde_json::Value = serde_json::from_str(&contents)- .unwrap_or_else(|e| panic!("Should be valid JSON: {}\nContents: {}", e, contents));+ let json = wait_for_valid_json(&json_file, Duration::from_secs(5));assert_eq!(json["branch"].as_str(),diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex aafe6b77d..f1975e1f0 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -1008,8 +1008,8 @@ approved-commands = ["echo 'hook ran' > {}"]None,);- // Wait a bit for any potential hook execution- thread::sleep(Duration::from_millis(100));+ // Wait for any potential hook execution (absence check - can't poll, use 500ms per guidelines)+ thread::sleep(Duration::from_millis(500));// Marker file should NOT exist - --no-verify skips the hookassert!(diff --git a/tests/integration_tests/select.rs b/tests/integration_tests/select.rsindex 5c90f6fc7..560243611 100644--- a/tests/integration_tests/select.rs+++ b/tests/integration_tests/select.rs@@ -198,9 +198,16 @@ fn exec_in_pty_with_input_sequence(// Drop writer to signal EOF on stdindrop(writer);- // Give the process a moment to exit gracefully, then kill if needed- std::thread::sleep(Duration::from_millis(100));- let _ = child.kill();+ // Poll for process exit (fast polling, long timeout for CI)+ let start = std::time::Instant::now();+ let timeout = Duration::from_secs(5);+ while start.elapsed() < timeout {+ if child.try_wait().unwrap().is_some() {+ break;+ }+ std::thread::sleep(Duration::from_millis(10));+ }+ let _ = child.kill(); // Kill if still running after timeout// Drain any remaining outputdrain_output(&rx, &mut parser, &mut raw_output);diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex b4371260f..5c1e66a95 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -6,7 +6,9 @@//! - Don't require approval//! - Skipped together with project hooks via --no-verify-use crate::common::{TestRepo, make_snapshot_cmd, setup_snapshot_settings, wait_for_file};+use crate::common::{+ TestRepo, make_snapshot_cmd, setup_snapshot_settings, wait_for_file, wait_for_file_content,+};use insta_cmd::assert_cmd_snapshot;use std::fs;use std::process::Command;@@ -212,10 +214,10 @@ bg = "echo 'USER_POST_START_RAN' > user_bg_marker.txt"snapshot_switch("user_post_start_executes", &repo, &["--create", "feature"]);- // Wait for background hook to complete+ // Wait for background hook to complete and write contentlet worktree_path = repo.root_path().parent().unwrap().join("repo.feature");let marker_file = worktree_path.join("user_bg_marker.txt");- wait_for_file(&marker_file, Duration::from_secs(5));+ wait_for_file_content(&marker_file, Duration::from_secs(5));let contents = fs::read_to_string(&marker_file).unwrap();assert!(