Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
test: cover error paths in step_commands and run_git_capture (#2566)
Maximilian Roos6632057c2dcc
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex b93a17f04..4e836b162 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -178,34 +178,38 @@ fn print_dry_run(commit_config: &worktrunk::config::CommitGenerationConfig,message: &str,) -> anyhow::Result<()> {- use std::fmt::Write as _;- let mut out = String::new();- writeln!(out, "{}", format_heading("PROMPT", None))?;- writeln!(out, "{}", prompt)?;- writeln!(out)?;- writeln!(out, "{}", format_heading("COMMAND", None))?;- match commit_config+ print_dry_run_with(prompt, commit_config, message, |s| {+ crate::help_pager::show_help_in_pager(s, true)+ })+}++/// Inner form taking an injectable pager so the fallback path is unit-testable+/// (mid-write or wait failures from `show_help_in_pager` only happen against a+/// real TTY + a misbehaving pager, which is impractical to set up in a test).+fn print_dry_run_with(+ prompt: &str,+ commit_config: &worktrunk::config::CommitGenerationConfig,+ message: &str,+ pager: impl FnOnce(&str) -> std::io::Result<()>,+) -> anyhow::Result<()> {+ let command_block = match commit_config.command.as_deref().filter(|s| !s.trim().is_empty()){- Some(cmd) => writeln!(- out,- "{}",- format_bash_with_gutter(&crate::llm::render_llm_invocation(cmd)?)- )?,- None => writeln!(- out,- "{}",- format_with_gutter("(LLM not configured — using built-in fallback)", None)- )?,- }- writeln!(out)?;- writeln!(out, "{}", format_heading("MESSAGE", None))?;+ Some(cmd) => format_bash_with_gutter(&crate::llm::render_llm_invocation(cmd)?),+ None => format_with_gutter("(LLM not configured — using built-in fallback)", None),+ };let formatted = CommitGenerator::new(commit_config).format_message_for_display(message);- writeln!(out, "{}", format_with_gutter(&formatted, None))?;+ let out = format!(+ "{prompt_heading}\n{prompt}\n\n{command_heading}\n{command_block}\n\n{message_heading}\n{message_block}\n",+ prompt_heading = format_heading("PROMPT", None),+ command_heading = format_heading("COMMAND", None),+ message_heading = format_heading("MESSAGE", None),+ message_block = format_with_gutter(&formatted, None),+ );- if let Err(e) = crate::help_pager::show_help_in_pager(&out, true) {+ if let Err(e) = pager(&out) {log::debug!("Pager failed, falling back to stdout: {}", e);println!("{}", out);}@@ -2271,6 +2275,22 @@ mod tests {assert_eq!(fs::read_to_string(&dest).unwrap(), "content");}+ /// `print_dry_run` falls back to direct stdout when the pager errors mid-write+ /// (e.g. a misbehaving pager that closes stdin before reading). The fallback path+ /// only fires against a real TTY in production; the inner form lets us drive it+ /// with a stand-in pager that always returns Err.+ #[test]+ fn test_print_dry_run_falls_back_when_pager_errors() {+ let config = worktrunk::config::CommitGenerationConfig::default();+ let result = print_dry_run_with("the prompt", &config, "the message", |_| {+ Err(std::io::Error::other("simulated pager failure"))+ });+ assert!(+ result.is_ok(),+ "fallback should swallow pager errors, got: {result:?}"+ );+ }+#[test]fn test_copy_and_remove_directory() {let tmp = tempfile::tempdir().unwrap();diff --git a/src/llm.rs b/src/llm.rsindex bb7cde4be..d360f4ef9 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -820,6 +820,20 @@ mod tests {);}+ /// `run_git_capture` must surface a non-zero exit as an error that names the `what`+ /// label and includes the captured stderr — without that, the dry-run path would+ /// feed an empty diff to the LLM on a `git` failure.+ #[test]+ fn test_run_git_capture_bails_on_nonzero_exit() {+ let cmd = Cmd::new("git").args(["frobnicate-nonexistent"]);+ let err = run_git_capture(cmd, "frobnicate").unwrap_err();+ let msg = format!("{err}");+ assert!(+ msg.contains("git frobnicate failed:"),+ "error message should name the `what` label; got: {msg}"+ );+ }+/// Single-quotes in the user's command must be escaped so the displayed string is a/// faithful, copy-pasteable shell invocation.#[test]diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 0d908173c..936566a2f 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -2569,6 +2569,91 @@ command = "cat >/dev/null && echo 'feat: combined feature work'");}+/// `--dry-run` mirrors `--stage` against a temp index by running `git add` with+/// `GIT_INDEX_FILE` pointed at the copy. If that `git add` exits non-zero, the+/// error must propagate (not silently feed an empty diff to the LLM). We+/// reproduce a non-zero exit by replacing `.git/index` with garbage — the temp+/// copy succeeds, but `git add -A` rejects the corrupt index.+#[rstest]+fn test_step_commit_dry_run_propagates_git_add_failure(repo: TestRepo) {+ fs::write(repo.root_path().join("new.txt"), "x").expect("Failed to write file");++ let index_path = repo.root_path().join(".git").join("index");+ fs::write(&index_path, b"not-a-valid-git-index").expect("Failed to corrupt index");++ let output = make_snapshot_cmd(&repo, "step", &["commit", "--dry-run"], None)+ .output()+ .expect("wt step commit --dry-run failed to spawn");+ assert!(+ !output.status.success(),+ "expected non-zero exit when git add fails; stdout:\n{}\nstderr:\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("git add -A failed"),+ "expected bail! to surface 'git add -A failed'; got stderr:\n{stderr}"+ );+}++/// `wt step squash --show-prompt` propagates template errors from+/// `build_squash_prompt`. A malformed jinja template must surface the failure+/// rather than producing an empty prompt.+#[rstest]+fn test_step_squash_show_prompt_malformed_template(repo_with_multi_commit_feature: TestRepo) {+ let repo = repo_with_multi_commit_feature;+ let feature_wt = repo.worktree_path("feature");++ let worktrunk_config = r#"+[commit.generation]+squash-template = "{% if commits"+"#;+ fs::write(repo.test_config_path(), worktrunk_config).unwrap();++ let output = make_snapshot_cmd(+ &repo,+ "step",+ &["squash", "--show-prompt"],+ Some(feature_wt),+ )+ .output()+ .expect("wt step squash --show-prompt failed to spawn");+ assert!(+ !output.status.success(),+ "expected non-zero exit on malformed template; stdout:\n{}\nstderr:\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );+}++/// `wt step squash --dry-run` propagates LLM-command failures from+/// `generate_squash_message`. The prompt renders fine, but a non-zero exit+/// from the configured command must be surfaced rather than swallowed.+#[rstest]+fn test_step_squash_dry_run_llm_failure(repo_with_multi_commit_feature: TestRepo) {+ let repo = repo_with_multi_commit_feature;+ let feature_wt = repo.worktree_path("feature");++ // `cat >/dev/null` consumes stdin first to avoid a broken-pipe race; the+ // command then exits non-zero so generate_squash_message bubbles the failure up.+ let worktrunk_config = r#"+[commit.generation]+command = "cat >/dev/null; echo 'simulated LLM failure' >&2 && exit 1"+"#;+ fs::write(repo.test_config_path(), worktrunk_config).unwrap();++ let output = make_snapshot_cmd(&repo, "step", &["squash", "--dry-run"], Some(feature_wt))+ .output()+ .expect("wt step squash --dry-run failed to spawn");+ assert!(+ !output.status.success(),+ "expected non-zero exit when LLM command fails; stdout:\n{}\nstderr:\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );+}+// =============================================================================// step rebase tests// =============================================================================