Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

test: consolidate absence-window sleeps behind a shared SLEEP_FOR_ABSENCE_CHECK (#3206)

Maximilian Roos9be99ee21b92
diff --git a/src/testing/mod.rs b/src/testing/mod.rs
index 49e93e94f..b6e50b9c7 100644
--- a/src/testing/mod.rs
+++ b/src/testing/mod.rs
@@ -2731,6 +2731,28 @@ fn exponential_sleep(attempt: u32) {
ExponentialBackoff::default().sleep(attempt);
}
+/// Fixed window for an **absence** assertion, proving that something did
+/// *not* happen (a hook that must not fire, a marker that must not appear).
+///
+/// The polarity of the assertion decides the tool. A **presence** assertion
+/// waits for an event that *will* happen: poll with [`wait_for_file`] and
+/// friends, which return the instant the event lands and tolerate a slow CI
+/// runner via a generous timeout. An **absence** assertion has no event to
+/// wait for, so polling can't help: the only option is to wait long enough
+/// that the thing would have happened if it were going to, then assert it
+/// didn't. 500ms is the floor; a starved background process needs a wide
+/// margin for the window to be conclusive.
+///
+/// Use this constant rather than a bare `Duration::from_millis(500)` so
+/// absence sleeps are greppable and self-documenting. Never pair it with a
+/// presence assertion in the same test: a fixed sleep before a "did happen"
+/// check is the flaky pattern this constant exists to keep out of the
+/// assertion path. When the absence is *structural* (the event is gated on a
+/// condition the test never sets up, so it can't fire at all), no window is
+/// needed: poll the positive precondition instead and the absence holds by
+/// construction.
+pub const SLEEP_FOR_ABSENCE_CHECK: std::time::Duration = std::time::Duration::from_millis(500);
+
/// True when a worktree's contents have been removed — either the path
/// is gone, or it's an empty placeholder directory.
///
diff --git a/tests/CLAUDE.md b/tests/CLAUDE.md
index 18d25dc12..ffd5ddac9 100644
--- a/tests/CLAUDE.md
+++ b/tests/CLAUDE.md
@@ -141,11 +141,13 @@ silently: it passes wherever `$HOME` is writable and fails only in a sandbox
that forbids it. `config_path()` and `system_config_path()` have no guard at
all.
-## Timing Tests: Long Timeouts with Fast Polling
+## Timing Tests: Polling and Absence Windows
-**Core principle:** Use long timeouts (5+ seconds) for reliability on slow CI, but poll frequently (10-50ms) so tests complete quickly when things work.
+**The assertion's polarity picks the tool.** A *presence* assertion waits for something that will happen (a file appears, a counter ticks): poll it, so the test returns the instant the event lands. An *absence* assertion proves something did NOT happen (a hook stays silent, a marker never appears): there's no event to wait for, so hold a fixed window with `SLEEP_FOR_ABSENCE_CHECK`, then assert. The most common timing flake is pairing a fixed sleep with a presence assertion: it guesses how long the work takes and fails when load overruns the guess.
-This achieves both goals:
+### Presence: long timeouts, fast polling
+
+Use long timeouts (5+ seconds) for reliability on slow CI, but poll frequently (10-50ms) so tests complete quickly when things work:
- **No flaky failures** on slow machines - generous timeout accommodates worst-case
- **Fast tests** on normal machines - frequent polling means no unnecessary waiting
@@ -159,7 +161,7 @@ while start.elapsed() < timeout {
thread::sleep(poll_interval);
}
-// ❌ BAD: Fixed sleep (always slow, might still fail)
+// ❌ BAD: fixed sleep before a presence assertion (always slow, races under load)
thread::sleep(Duration::from_millis(500));
assert!(condition_met());
@@ -227,13 +229,22 @@ let outcome = drain_results_with_timings(
**Rule of thumb:** if your producer thread needs `thread::sleep` to line up with a deadline in the code under test, you're racing the scheduler. Reach for the callback, a channel, or a condvar instead. Fixed deadlines belong only in the safety-net role — "stop if something has truly hung" — not in the assertion path.
-**Exception - testing absence:** When verifying something did NOT happen, polling doesn't work. Use a fixed 500ms+ sleep:
+### Absence: hold a fixed window
+
+When the assertion proves a negative (`assert!(!marker.exists())`), polling can't help, because there's no event to wait for. Hold a window long enough that the thing would have happened if it were going to, then assert it didn't. Use the shared constant (defined in `src/testing/mod.rs`, re-exported via `tests/common`) so absence sleeps stay greppable and self-documenting:
```rust
-thread::sleep(Duration::from_millis(500));
+use crate::common::SLEEP_FOR_ABSENCE_CHECK;
+
+thread::sleep(SLEEP_FOR_ABSENCE_CHECK); // 500ms, the floor for an absence window
assert!(!marker_file.exists(), "Command should NOT have run");
```
+Two traps:
+
+- **Give each half its own wait.** Sleeping once and then asserting both "X happened" and "Y didn't" makes the presence half flaky. Poll for X, then hold the window for Y.
+- **Structural absence needs no window at all.** When the event is gated on a condition the test never sets up, it can't fire regardless of timing. Drop the sleep: poll the positive precondition and the absence holds by construction. A watchdog whose escalation is gated on `command.is_some()` can't escalate with no command, so the test polls for the first render and asserts `!escalated` with no window.
+
## Testing with --execute Commands
Use `--yes` to skip interactive prompts in tests. Don't pipe input to stdin.
diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rs
index 9c300876d..cb848ee56 100644
--- a/tests/integration_tests/bare_repository.rs
+++ b/tests/integration_tests/bare_repository.rs
@@ -1,7 +1,8 @@
use crate::common::{
- BareRepoTest, TestRepo, TestRepoBase, canonicalize, configure_directive_files,
- configure_git_cmd, configure_git_env, directive_files, repo, setup_temp_snapshot_settings,
- wait_for_file, wait_for_file_content, wait_for_worktree_removed, wt_command,
+ BareRepoTest, SLEEP_FOR_ABSENCE_CHECK, TestRepo, TestRepoBase, canonicalize,
+ configure_directive_files, configure_git_cmd, configure_git_env, directive_files, repo,
+ setup_temp_snapshot_settings, wait_for_file, wait_for_file_content, wait_for_worktree_removed,
+ wt_command,
};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
@@ -9,7 +10,6 @@ use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::thread;
-use std::time::Duration;
use worktrunk::shell_exec::Cmd;
#[test]
@@ -910,7 +910,7 @@ fn test_bare_repo_ignores_config_in_bare_root() {
);
// The hook from the bare root config should NOT have executed
- thread::sleep(Duration::from_millis(500));
+ thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
assert!(
!marker_path.exists(),
"Config in bare repo root should be ignored — only primary worktree config should be used"
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 23688853b..350a590dd 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -1,5 +1,5 @@
use crate::common::{
- TestRepo, make_snapshot_cmd, merge_scenario,
+ SLEEP_FOR_ABSENCE_CHECK, TestRepo, make_snapshot_cmd, merge_scenario,
mock_commands::{create_mock_cargo, create_mock_llm_auth},
repo, repo_with_alternate_primary, repo_with_feature_worktree, repo_with_main_worktree,
repo_with_multi_commit_feature, repo_with_remote, setup_snapshot_settings, wait_for_file,
@@ -4062,10 +4062,10 @@ fn test_post_merge_hook_from_rebased_in_config_does_not_run(merge_scenario: (Tes
String::from_utf8_lossy(&output.stderr)
);
- // Wait for the control (post-merge ran), then a short grace for the sibling
- // pipeline.
+ // Wait for the control (post-merge ran), then hold the absence window for
+ // the sibling pipeline before asserting it never ran.
wait_for_file(&control);
- std::thread::sleep(std::time::Duration::from_millis(200));
+ std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
assert!(
!injected.exists(),
"a post-merge that entered the invoking worktree's config only via the \
diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rs
index d93f45e70..bfc3e983b 100644
--- a/tests/integration_tests/post_start_commands.rs
+++ b/tests/integration_tests/post_start_commands.rs
@@ -1,21 +1,16 @@
use crate::common::{
- TestRepo, make_snapshot_cmd, make_snapshot_cmd_with_global_flags, repo, repo_with_remote,
- resolve_git_common_dir, set_temp_home_env, setup_snapshot_settings, wait_for_file,
- wait_for_file_content, wait_for_file_count, wait_for_file_lines, wait_for_valid_json,
+ SLEEP_FOR_ABSENCE_CHECK, TestRepo, make_snapshot_cmd, make_snapshot_cmd_with_global_flags,
+ repo, repo_with_remote, resolve_git_common_dir, set_temp_home_env, setup_snapshot_settings,
+ wait_for_file, 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;
use rstest::rstest;
use std::fs;
use std::thread;
-use std::time::Duration; // Used for SLEEP_FOR_ABSENCE_CHECK
use tempfile::TempDir;
-/// 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
///
/// Tests should write to repo.test_config_path() to pre-approve commands.
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 54c7221f2..e1b9ede67 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1,6 +1,6 @@
use crate::common::{
- BareRepoTest, TestRepo, TestRepoBase, configure_directive_files, directive_files,
- make_snapshot_cmd, repo, repo_with_remote, setup_snapshot_settings,
+ BareRepoTest, SLEEP_FOR_ABSENCE_CHECK, TestRepo, TestRepoBase, configure_directive_files,
+ directive_files, make_snapshot_cmd, repo, repo_with_remote, setup_snapshot_settings,
setup_temp_snapshot_settings, wt_command,
};
use ansi_str::AnsiStr;
@@ -8,7 +8,6 @@ use insta::assert_snapshot;
use insta_cmd::assert_cmd_snapshot;
use path_slash::PathExt as _;
use rstest::rstest;
-use std::time::Duration; // For absence checks (SLEEP_FOR_ABSENCE_CHECK pattern)
#[rstest]
fn test_remove_already_on_default(repo: TestRepo) {
@@ -2134,8 +2133,8 @@ approved-commands = ["echo 'hook ran' > {}"]
None
));
- // Wait for any potential hook execution (absence check - can't poll, use 500ms per guidelines)
- thread::sleep(Duration::from_millis(500));
+ // Give a wrongly-spawned hook time to create its marker before asserting it didn't.
+ thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
// Marker file should NOT exist - --no-hooks skips the hook
assert!(
diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rs
index ec028b8af..9cdc153ec 100644
--- a/tests/integration_tests/step_alias.rs
+++ b/tests/integration_tests/step_alias.rs
@@ -4,6 +4,10 @@ use crate::common::{
TestRepo, configure_directive_files, directive_files, make_snapshot_cmd,
make_snapshot_cmd_with_global_flags, repo, setup_snapshot_settings, wt_bin,
};
+// Used only by the `#[cfg(unix)]` signal tests below; gate the import to match,
+// or it reads as unused on Windows under `-D warnings`.
+#[cfg(unix)]
+use crate::common::SLEEP_FOR_ABSENCE_CHECK;
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::io::Write;
@@ -1441,7 +1445,7 @@ two = "sh -c 'echo start-two >> slow_two.log; sleep 30; echo done-two >> slow_tw
);
// Grace period — the killed children must NOT reach their "done" write.
- std::thread::sleep(std::time::Duration::from_millis(500));
+ std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
for log in [&one_log, &two_log] {
let contents = std::fs::read_to_string(log).unwrap_or_default();
assert!(
@@ -1501,7 +1505,7 @@ two = "sh -c 'trap \"\" INT; echo start-two >> ignored_two.log; sleep 30'"
// (the old design), within ~400 ms SIGTERM would have killed both
// children and wt would be in the process of exiting. With the new
// contract, both children keep sleeping and wt is still running.
- std::thread::sleep(std::time::Duration::from_millis(500));
+ std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
match child.try_wait().expect("try_wait failed") {
None => {
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 10384ec8a..7c38da046 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -1,8 +1,8 @@
use crate::common::{
- TestRepo, configure_directive_files, directive_files, make_snapshot_cmd,
- make_snapshot_cmd_with_global_flags, repo, repo_with_remote, set_temp_home_env,
- setup_home_snapshot_settings, setup_snapshot_settings, temp_home, wait_for_file_content,
- wt_command,
+ SLEEP_FOR_ABSENCE_CHECK, TestRepo, configure_directive_files, directive_files,
+ make_snapshot_cmd, make_snapshot_cmd_with_global_flags, repo, repo_with_remote,
+ set_temp_home_env, setup_home_snapshot_settings, setup_snapshot_settings, temp_home,
+ wait_for_file_content, wt_command,
};
use ansi_str::AnsiStr;
use insta_cmd::assert_cmd_snapshot;
@@ -1120,7 +1120,7 @@ approved-commands = ["{}"]
// post-start runs in the background; with --no-hooks it is never spawned,
// but sleep briefly so a regression that incorrectly spawns it has time to
// create the marker (per tests/CLAUDE.md "Testing absence").
- std::thread::sleep(std::time::Duration::from_millis(500));
+ std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
let repo_name = repo.root_path().file_name().unwrap().to_str().unwrap();
let worktree = repo
.root_path()
@@ -1176,7 +1176,7 @@ fn test_switch_no_config_commands_with_yes(repo: TestRepo) {
// post-start runs in the background; with --no-hooks it is never spawned,
// but sleep briefly so a regression that incorrectly spawns it has time to
// create the marker (per tests/CLAUDE.md "Testing absence").
- std::thread::sleep(std::time::Duration::from_millis(500));
+ std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
let repo_name = repo.root_path().file_name().unwrap().to_str().unwrap();
let worktree = repo
.root_path()
@@ -1250,7 +1250,7 @@ post-start = "echo post-start-from-invoking > {{ repo_path }}/post-start-marker.
);
// The base branch's committed hook must never run.
- std::thread::sleep(std::time::Duration::from_millis(500));
+ std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
assert!(
!repo.root_path().join("base-branch-marker.txt").exists(),
"the base branch's committed config must not be consulted for `--create`"
@@ -1295,7 +1295,7 @@ fn test_switch_existing_reads_invoking_worktree_config(mut repo: TestRepo) {
);
// The destination worktree's own hook must never run.
- std::thread::sleep(std::time::Duration::from_millis(500));
+ std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
assert!(
!repo.root_path().join("dest-marker.txt").exists(),
"the destination worktree's config must not be consulted"
@@ -1375,7 +1375,7 @@ fn test_switch_create_honors_project_config_path_override(mut repo: TestRepo) {
wait_for_file_content(&right);
assert_eq!(fs::read_to_string(&right).unwrap().trim(), "OVERRIDE-HOOK");
// The base ref's committed hook must never have run.
- std::thread::sleep(std::time::Duration::from_millis(500));
+ std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
assert!(
!repo.root_path().join("wrong-marker.txt").exists(),
"the base ref's committed hook must not run when the config path is overridden"
@@ -3316,7 +3316,7 @@ fn test_switch_pr_reads_invoking_worktree_config(#[from(repo_with_remote)] repo:
"INVOKING-HOOK-RAN",
"post-start should run from the invoking worktree's config"
);
- std::thread::sleep(std::time::Duration::from_millis(500));
+ std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
assert!(
!repo.root_path().join("pr-hook-marker.txt").exists(),
"the PR ref's committed config must not be consulted"
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index 049a4961d..ee9b54065 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -7,8 +7,9 @@
//! - Skipped together with project hooks via --no-hooks
use crate::common::{
- TestRepo, make_snapshot_cmd, make_snapshot_cmd_with_global_flags, repo, resolve_git_common_dir,
- setup_snapshot_settings, wait_for_file, wait_for_file_content, wait_for_file_count,
+ SLEEP_FOR_ABSENCE_CHECK, TestRepo, make_snapshot_cmd, make_snapshot_cmd_with_global_flags,
+ repo, resolve_git_common_dir, setup_snapshot_settings, wait_for_file, wait_for_file_content,
+ wait_for_file_count,
};
use insta::assert_snapshot;
use insta_cmd::assert_cmd_snapshot;
@@ -18,11 +19,6 @@ use std::fs;
use std::thread;
use std::time::Duration;
-// Note: Duration is still imported for SLEEP_FOR_ABSENCE_CHECK (testing command did NOT run)
-
-/// Wait duration when checking file absence (testing command did NOT run).
-const SLEEP_FOR_ABSENCE_CHECK: Duration = Duration::from_millis(500);
-
// ============================================================================
// User Post-Create Hook Tests
// ============================================================================
@@ -415,7 +411,7 @@ long = "sh -c 'echo start >> hook.log; sleep 30; echo done >> hook.log'"
);
// Give the (killed) hook a moment; it must not append "done"
- thread::sleep(Duration::from_millis(500));
+ thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
let mut contents = String::new();
std::fs::File::open(&hook_log)
@@ -475,7 +471,7 @@ long = "sh -c 'echo start >> hook.log; sleep 30; echo done >> hook.log'"
);
// Give the (killed) hook a moment; it must not append "done"
- thread::sleep(Duration::from_millis(500));
+ thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
let mut contents = String::new();
std::fs::File::open(&hook_log)
@@ -884,7 +880,7 @@ marker = "echo 'SHOULD_NOT_RUN' > ../no_hooks_postremove.txt"
.parent()
.unwrap()
.join("no_hooks_postremove.txt");
- thread::sleep(Duration::from_millis(500)); // Wait to ensure hook would have run if enabled
+ thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
assert!(
!marker_file.exists(),
"Post-remove hook should be skipped when --no-hooks is used"