Skip to content

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

Add unit tests to improve code coverage (#218)

Maximilian Roosd881eabda192
diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index 7aebe9b12..a1b81fa98 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -202,7 +202,9 @@ jobs:
- run: cargo llvm-cov clean --workspace
- name: 📊 Generate coverage report
- run: cargo llvm-cov --cobertura --output-path=cobertura.xml
+ env:
+ NEXTEST_NO_INPUT_HANDLER: 1
+ run: cargo llvm-cov --features shell-integration-tests --cobertura --output-path=cobertura.xml
- name: Upload code coverage results
uses: actions/upload-artifact@v6
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index e3dc224f5..ea1aae84d 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -218,3 +218,59 @@ impl CommitOptions<'_> {
.commit_staged_changes(self.show_no_squash_note, self.stage_mode)
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use worktrunk::config::CommitGenerationConfig;
+
+ #[test]
+ fn test_format_message_for_display_single_line() {
+ let config = CommitGenerationConfig::default();
+ let generator = CommitGenerator::new(&config);
+ let result = generator.format_message_for_display("Simple commit message");
+ // Should contain the message text with styling
+ assert!(result.contains("Simple commit message"));
+ // Should be styled (output differs from plain input)
+ assert!(result.len() > "Simple commit message".len());
+ }
+
+ #[test]
+ fn test_format_message_for_display_multiline() {
+ let config = CommitGenerationConfig::default();
+ let generator = CommitGenerator::new(&config);
+ let result = generator.format_message_for_display("First line\nSecond line\nThird line");
+ assert!(result.contains("First line"));
+ assert!(result.contains("Second line"));
+ assert!(result.contains("Third line"));
+ }
+
+ #[test]
+ fn test_format_message_for_display_empty() {
+ let config = CommitGenerationConfig::default();
+ let generator = CommitGenerator::new(&config);
+ let result = generator.format_message_for_display("");
+ assert_eq!(result, "");
+ }
+
+ #[test]
+ fn test_commit_options_new() {
+ // CommitOptions::new requires a CommandContext, which requires a Repository.
+ // Instead, test the struct fields directly
+ let stage_mode = StageMode::default();
+ assert!(matches!(stage_mode, StageMode::All));
+ }
+
+ #[test]
+ fn test_stage_mode_variants() {
+ // Test that all StageMode variants can be matched
+ let modes = [StageMode::All, StageMode::Tracked, StageMode::None];
+ for mode in modes {
+ match mode {
+ StageMode::All => assert_eq!(format!("{:?}", mode), "All"),
+ StageMode::Tracked => assert_eq!(format!("{:?}", mode), "Tracked"),
+ StageMode::None => assert_eq!(format!("{:?}", mode), "None"),
+ }
+ }
+ }
+}
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index b9feed05d..22daf3b1b 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -985,3 +985,85 @@ pub fn handle_show_theme() -> Result<(), String> {
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_uninstall_action_description() {
+ assert_eq!(UninstallAction::Removed.description(), "Removed");
+ assert_eq!(UninstallAction::WouldRemove.description(), "Will remove");
+ }
+
+ #[test]
+ fn test_uninstall_action_emoji() {
+ assert_eq!(UninstallAction::Removed.emoji(), SUCCESS_EMOJI);
+ assert_eq!(UninstallAction::WouldRemove.emoji(), PROGRESS_EMOJI);
+ }
+
+ #[test]
+ fn test_config_action_description() {
+ assert_eq!(ConfigAction::Added.description(), "Added");
+ assert_eq!(
+ ConfigAction::AlreadyExists.description(),
+ "Already configured"
+ );
+ assert_eq!(ConfigAction::Created.description(), "Created");
+ assert_eq!(ConfigAction::WouldAdd.description(), "Will add");
+ assert_eq!(ConfigAction::WouldCreate.description(), "Will create");
+ }
+
+ #[test]
+ fn test_config_action_emoji() {
+ assert_eq!(ConfigAction::Added.emoji(), SUCCESS_EMOJI);
+ assert_eq!(ConfigAction::Created.emoji(), SUCCESS_EMOJI);
+ assert_eq!(ConfigAction::AlreadyExists.emoji(), INFO_EMOJI);
+ assert_eq!(ConfigAction::WouldAdd.emoji(), PROGRESS_EMOJI);
+ assert_eq!(ConfigAction::WouldCreate.emoji(), PROGRESS_EMOJI);
+ }
+
+ #[test]
+ fn test_has_integration_pattern() {
+ assert!(has_integration_pattern("wt init bash"));
+ assert!(has_integration_pattern("WT INIT zsh")); // Case insensitive
+ assert!(has_integration_pattern("wt config shell init"));
+ assert!(!has_integration_pattern("echo hello"));
+ assert!(!has_integration_pattern("wt merge"));
+ }
+
+ #[test]
+ fn test_is_integration_line() {
+ // Valid integration lines
+ assert!(is_integration_line("eval \"$(wt init bash)\""));
+ assert!(is_integration_line(" eval \"$(wt init zsh)\" "));
+ assert!(is_integration_line(
+ "if [ -n \"$BASH_VERSION\" ]; then eval \"$(wt init bash)\"; fi"
+ ));
+ assert!(is_integration_line("source <(wt init fish)"));
+
+ // Not integration lines (comments)
+ assert!(!is_integration_line("# eval \"$(wt init bash)\""));
+ assert!(!is_integration_line(" # wt init zsh"));
+
+ // Not integration lines (no eval/source/if)
+ assert!(!is_integration_line("wt init bash"));
+ assert!(!is_integration_line("echo wt init bash"));
+ }
+
+ #[test]
+ fn test_fish_completion_content() {
+ let content = fish_completion_content("wt");
+ assert!(content.contains("# worktrunk completions for fish"));
+ assert!(content.contains("--command wt"));
+ assert!(content.contains("COMPLETE=fish"));
+ assert!(content.contains("WORKTRUNK_BIN"));
+ }
+
+ #[test]
+ fn test_fish_completion_content_custom_cmd() {
+ let content = fish_completion_content("myapp");
+ assert!(content.contains("--command myapp"));
+ assert!(content.contains("type -P myapp"));
+ }
+}
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index a497252b4..3e0b9245d 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -335,3 +335,41 @@ pub fn run_hook_with_filter(
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_hook_source_label_prefix() {
+ assert_eq!(HookSource::User.label_prefix(), "user");
+ assert_eq!(HookSource::Project.label_prefix(), "project");
+ }
+
+ #[test]
+ fn test_hook_source_format_label() {
+ assert_eq!(
+ HookSource::User.format_label(HookType::PreMerge),
+ "user pre-merge"
+ );
+ assert_eq!(
+ HookSource::Project.format_label(HookType::PostCreate),
+ "project post-create"
+ );
+ assert_eq!(
+ HookSource::User.format_label(HookType::PreCommit),
+ "user pre-commit"
+ );
+ }
+
+ #[test]
+ fn test_hook_failure_strategy_copy() {
+ let strategy = HookFailureStrategy::FailFast;
+ let copied = strategy; // Copy trait
+ assert!(matches!(copied, HookFailureStrategy::FailFast));
+
+ let warn = HookFailureStrategy::Warn;
+ let copied_warn = warn;
+ assert!(matches!(copied_warn, HookFailureStrategy::Warn));
+ }
+}
diff --git a/src/commands/list/columns.rs b/src/commands/list/columns.rs
index b6a8060af..66eea22fd 100644
--- a/src/commands/list/columns.rs
+++ b/src/commands/list/columns.rs
@@ -111,6 +111,7 @@ pub const COLUMN_SPECS: &[ColumnSpec] = &[
#[cfg(test)]
mod tests {
use super::*;
+ use std::collections::HashSet;
#[test]
fn columns_are_ordered_and_unique() {
@@ -165,4 +166,117 @@ mod tests {
}
}
}
+
+ #[test]
+ fn test_column_kind_debug() {
+ // Test Debug trait implementation
+ assert_eq!(format!("{:?}", ColumnKind::Gutter), "Gutter");
+ assert_eq!(format!("{:?}", ColumnKind::Branch), "Branch");
+ assert_eq!(format!("{:?}", ColumnKind::Status), "Status");
+ assert_eq!(format!("{:?}", ColumnKind::Message), "Message");
+ }
+
+ #[test]
+ fn test_column_kind_copy() {
+ let kind = ColumnKind::Branch;
+ let copied1 = kind; // Copy trait
+ let copied2 = kind;
+ assert_eq!(kind, copied1);
+ assert_eq!(kind, copied2);
+ }
+
+ #[test]
+ fn test_column_kind_hash() {
+ let mut set = HashSet::new();
+ set.insert(ColumnKind::Branch);
+ set.insert(ColumnKind::Path);
+ assert!(set.contains(&ColumnKind::Branch));
+ assert!(set.contains(&ColumnKind::Path));
+ assert!(!set.contains(&ColumnKind::Message));
+ }
+
+ #[test]
+ fn test_diff_variant_debug() {
+ assert_eq!(format!("{:?}", DiffVariant::Signs), "Signs");
+ assert_eq!(format!("{:?}", DiffVariant::Arrows), "Arrows");
+ assert_eq!(
+ format!("{:?}", DiffVariant::UpstreamArrows),
+ "UpstreamArrows"
+ );
+ }
+
+ #[test]
+ fn test_diff_variant_copy() {
+ let variant = DiffVariant::Signs;
+ let copied1 = variant; // Copy trait
+ let copied2 = variant;
+ assert_eq!(variant, copied1);
+ assert_eq!(variant, copied2);
+ }
+
+ #[test]
+ fn test_column_spec_new() {
+ let spec = ColumnSpec::new(ColumnKind::Branch, "Branch", 1, None, 1);
+ assert_eq!(spec.kind, ColumnKind::Branch);
+ assert_eq!(spec.header, "Branch");
+ assert_eq!(spec.base_priority, 1);
+ assert!(spec.requires_task.is_none());
+ assert_eq!(spec.display_index, 1);
+ }
+
+ #[test]
+ fn test_column_spec_with_required_task() {
+ let spec = ColumnSpec::new(
+ ColumnKind::BranchDiff,
+ "main…±",
+ 5,
+ Some(TaskKind::BranchDiff),
+ 5,
+ );
+ assert_eq!(spec.kind, ColumnKind::BranchDiff);
+ assert_eq!(spec.requires_task, Some(TaskKind::BranchDiff));
+ }
+
+ #[test]
+ fn test_column_spec_debug() {
+ let spec = ColumnSpec::new(ColumnKind::Path, "Path", 6, None, 6);
+ let debug_str = format!("{:?}", spec);
+ assert!(debug_str.contains("ColumnSpec"));
+ assert!(debug_str.contains("Path"));
+ }
+
+ #[test]
+ fn test_column_spec_copy() {
+ let spec = ColumnSpec::new(ColumnKind::Time, "Age", 10, None, 10);
+ let copied = spec; // Copy trait - should work without clone
+ assert_eq!(spec.kind, copied.kind);
+ assert_eq!(spec.header, copied.header);
+ assert_eq!(spec.base_priority, copied.base_priority);
+ }
+
+ #[test]
+ fn test_column_specs_priorities_are_unique() {
+ // Each column should have a unique base_priority
+ let priorities: Vec<u8> = COLUMN_SPECS.iter().map(|c| c.base_priority).collect();
+ let unique: HashSet<u8> = priorities.iter().cloned().collect();
+ assert_eq!(
+ priorities.len(),
+ unique.len(),
+ "base_priority values should be unique"
+ );
+ }
+
+ #[test]
+ fn test_column_specs_headers_are_non_empty() {
+ // All columns except Gutter should have non-empty headers
+ for spec in COLUMN_SPECS {
+ if spec.kind != ColumnKind::Gutter {
+ assert!(
+ !spec.header.is_empty(),
+ "{:?} should have a non-empty header",
+ spec.kind
+ );
+ }
+ }
+ }
}
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index eb2f11dbe..74c342026 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -748,6 +748,211 @@ mod tests {
use std::path::PathBuf;
use worktrunk::git::LineDiff;
+ #[test]
+ fn test_fit_header() {
+ // Data wider than header - return data width
+ assert_eq!(fit_header("Age", 10), 10);
+
+ // Header wider than data - return header width
+ assert_eq!(fit_header("Branch", 3), 6);
+
+ // Empty data - return header width
+ assert_eq!(fit_header("Status", 0), 6);
+
+ // Equal widths
+ assert_eq!(fit_header("Path", 4), 4);
+ }
+
+ #[test]
+ fn test_try_allocate() {
+ // First column doesn't need spacing
+ let mut remaining = 100;
+ let allocated = try_allocate(&mut remaining, 20, 2, true);
+ assert_eq!(allocated, 20);
+ assert_eq!(remaining, 80);
+
+ // Subsequent columns need spacing
+ let allocated = try_allocate(&mut remaining, 15, 2, false);
+ assert_eq!(allocated, 15);
+ assert_eq!(remaining, 63); // 80 - 15 - 2
+
+ // Zero width returns 0
+ let mut remaining = 50;
+ assert_eq!(try_allocate(&mut remaining, 0, 2, false), 0);
+ assert_eq!(remaining, 50);
+
+ // Insufficient space returns 0
+ let mut remaining = 10;
+ assert_eq!(try_allocate(&mut remaining, 20, 2, false), 0);
+ assert_eq!(remaining, 10);
+ }
+
+ #[test]
+ fn test_column_kind_has_data() {
+ let all_true = ColumnDataFlags {
+ status: true,
+ working_diff: true,
+ ahead_behind: true,
+ branch_diff: true,
+ upstream: true,
+ ci_status: true,
+ };
+ let all_false = ColumnDataFlags {
+ status: false,
+ working_diff: false,
+ ahead_behind: false,
+ branch_diff: false,
+ upstream: false,
+ ci_status: false,
+ };
+
+ // Always-have-data columns
+ assert!(ColumnKind::Gutter.has_data(&all_false));
+ assert!(ColumnKind::Branch.has_data(&all_false));
+ assert!(ColumnKind::Path.has_data(&all_false));
+ assert!(ColumnKind::Time.has_data(&all_false));
+ assert!(ColumnKind::Commit.has_data(&all_false));
+ assert!(ColumnKind::Message.has_data(&all_false));
+
+ // Flag-dependent columns
+ assert!(ColumnKind::Status.has_data(&all_true));
+ assert!(!ColumnKind::Status.has_data(&all_false));
+ assert!(ColumnKind::WorkingDiff.has_data(&all_true));
+ assert!(!ColumnKind::WorkingDiff.has_data(&all_false));
+ assert!(ColumnKind::AheadBehind.has_data(&all_true));
+ assert!(!ColumnKind::AheadBehind.has_data(&all_false));
+ assert!(ColumnKind::BranchDiff.has_data(&all_true));
+ assert!(!ColumnKind::BranchDiff.has_data(&all_false));
+ assert!(ColumnKind::Upstream.has_data(&all_true));
+ assert!(!ColumnKind::Upstream.has_data(&all_false));
+ assert!(ColumnKind::CiStatus.has_data(&all_true));
+ assert!(!ColumnKind::CiStatus.has_data(&all_false));
+ }
+
+ #[test]
+ fn test_column_kind_diff_display_config() {
+ // Diff columns have config
+ assert!(ColumnKind::WorkingDiff.diff_display_config().is_some());
+ assert!(ColumnKind::BranchDiff.diff_display_config().is_some());
+ assert!(ColumnKind::AheadBehind.diff_display_config().is_some());
+ assert!(ColumnKind::Upstream.diff_display_config().is_some());
+
+ // Non-diff columns don't have config
+ assert!(ColumnKind::Branch.diff_display_config().is_none());
+ assert!(ColumnKind::Status.diff_display_config().is_none());
+ assert!(ColumnKind::Path.diff_display_config().is_none());
+ assert!(ColumnKind::Time.diff_display_config().is_none());
+ assert!(ColumnKind::Message.diff_display_config().is_none());
+ assert!(ColumnKind::Commit.diff_display_config().is_none());
+ assert!(ColumnKind::CiStatus.diff_display_config().is_none());
+
+ // Check variants
+ let working = ColumnKind::WorkingDiff.diff_display_config().unwrap();
+ assert!(matches!(working.variant, DiffVariant::Signs));
+
+ let ahead = ColumnKind::AheadBehind.diff_display_config().unwrap();
+ assert!(matches!(ahead.variant, DiffVariant::Arrows));
+
+ let upstream = ColumnKind::Upstream.diff_display_config().unwrap();
+ assert!(matches!(upstream.variant, DiffVariant::UpstreamArrows));
+ }
+
+ #[test]
+ fn test_column_ideal_text() {
+ // Zero width returns None
+ assert!(ColumnIdeal::text(0).is_none());
+
+ // Non-zero width returns Some with text format
+ let ideal = ColumnIdeal::text(10).unwrap();
+ assert_eq!(ideal.width, 10);
+ assert!(matches!(ideal.format, ColumnFormat::Text));
+ }
+
+ #[test]
+ fn test_column_ideal_diff() {
+ // Zero total returns None
+ let zero_widths = DiffWidths {
+ total: 0,
+ positive_digits: 0,
+ negative_digits: 0,
+ };
+ assert!(ColumnIdeal::diff(zero_widths, ColumnKind::WorkingDiff).is_none());
+
+ // Non-zero returns Some with diff format
+ let widths = DiffWidths {
+ total: 9,
+ positive_digits: 3,
+ negative_digits: 3,
+ };
+ let ideal = ColumnIdeal::diff(widths, ColumnKind::WorkingDiff).unwrap();
+ assert_eq!(ideal.width, 9);
+ assert!(matches!(ideal.format, ColumnFormat::Diff(_)));
+ }
+
+ #[test]
+ fn test_column_kind_ideal() {
+ let widths = ColumnWidths {
+ branch: 15,
+ status: 8,
+ time: 4,
+ ci_status: 2,
+ message: 50,
+ ahead_behind: DiffWidths {
+ total: 7,
+ positive_digits: 2,
+ negative_digits: 2,
+ },
+ working_diff: DiffWidths {
+ total: 9,
+ positive_digits: 3,
+ negative_digits: 3,
+ },
+ branch_diff: DiffWidths {
+ total: 9,
+ positive_digits: 3,
+ negative_digits: 3,
+ },
+ upstream: DiffWidths {
+ total: 7,
+ positive_digits: 2,
+ negative_digits: 2,
+ },
+ };
+
+ // Text columns
+ assert_eq!(
+ ColumnKind::Gutter.ideal(&widths, 20, 8).map(|i| i.width),
+ Some(2)
+ );
+ assert_eq!(
+ ColumnKind::Branch.ideal(&widths, 20, 8).map(|i| i.width),
+ Some(15)
+ );
+ assert_eq!(
+ ColumnKind::Status.ideal(&widths, 20, 8).map(|i| i.width),
+ Some(8)
+ );
+ assert_eq!(
+ ColumnKind::Path.ideal(&widths, 20, 8).map(|i| i.width),
+ Some(20)
+ );
+ assert_eq!(
+ ColumnKind::Time.ideal(&widths, 20, 8).map(|i| i.width),
+ Some(4)
+ );
+ assert_eq!(
+ ColumnKind::Commit.ideal(&widths, 20, 8).map(|i| i.width),
+ Some(8)
+ );
+
+ // Message returns None (handled specially)
+ assert!(ColumnKind::Message.ideal(&widths, 20, 8).is_none());
+
+ // Diff columns
+ assert!(ColumnKind::WorkingDiff.ideal(&widths, 20, 8).is_some());
+ assert!(ColumnKind::AheadBehind.ideal(&widths, 20, 8).is_some());
+ }
+
#[test]
fn test_pre_allocated_width_estimates() {
// Test that build_estimated_widths() returns correct pre-allocated estimates
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index adaef524f..f1085d640 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -366,3 +366,138 @@ pub(crate) fn format_summary_message(
.join(", ");
format!("{INFO_EMOJI} {dim}Showing {summary}{dim:#}")
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_summary_metrics_default() {
+ let metrics = SummaryMetrics::default();
+ assert_eq!(metrics.worktrees, 0);
+ assert_eq!(metrics.local_branches, 0);
+ assert_eq!(metrics.remote_branches, 0);
+ assert_eq!(metrics.dirty_worktrees, 0);
+ assert_eq!(metrics.ahead_items, 0);
+ }
+
+ #[test]
+ fn test_summary_metrics_summary_parts_single_worktree() {
+ let metrics = SummaryMetrics {
+ worktrees: 1,
+ local_branches: 0,
+ remote_branches: 0,
+ dirty_worktrees: 0,
+ ahead_items: 0,
+ };
+ let parts = metrics.summary_parts(false, 0);
+ assert_eq!(parts, vec!["1 worktree"]);
+ }
+
+ #[test]
+ fn test_summary_metrics_summary_parts_multiple_worktrees() {
+ let metrics = SummaryMetrics {
+ worktrees: 3,
+ local_branches: 0,
+ remote_branches: 0,
+ dirty_worktrees: 0,
+ ahead_items: 0,
+ };
+ let parts = metrics.summary_parts(false, 0);
+ assert_eq!(parts, vec!["3 worktrees"]);
+ }
+
+ #[test]
+ fn test_summary_metrics_summary_parts_with_branches() {
+ let metrics = SummaryMetrics {
+ worktrees: 2,
+ local_branches: 5,
+ remote_branches: 10,
+ dirty_worktrees: 0,
+ ahead_items: 0,
+ };
+ let parts = metrics.summary_parts(true, 0);
+ assert_eq!(
+ parts,
+ vec!["2 worktrees", "5 branches", "10 remote branches"]
+ );
+ }
+
+ #[test]
+ fn test_summary_metrics_summary_parts_with_dirty() {
+ let metrics = SummaryMetrics {
+ worktrees: 3,
+ local_branches: 0,
+ remote_branches: 0,
+ dirty_worktrees: 2,
+ ahead_items: 0,
+ };
+ let parts = metrics.summary_parts(false, 0);
+ assert_eq!(parts, vec!["3 worktrees", "2 with changes"]);
+ }
+
+ #[test]
+ fn test_summary_metrics_summary_parts_with_ahead() {
+ let metrics = SummaryMetrics {
+ worktrees: 2,
+ local_branches: 0,
+ remote_branches: 0,
+ dirty_worktrees: 0,
+ ahead_items: 1,
+ };
+ let parts = metrics.summary_parts(false, 0);
+ assert_eq!(parts, vec!["2 worktrees", "1 ahead"]);
+ }
+
+ #[test]
+ fn test_summary_metrics_summary_parts_with_hidden_columns() {
+ let metrics = SummaryMetrics {
+ worktrees: 1,
+ local_branches: 0,
+ remote_branches: 0,
+ dirty_worktrees: 0,
+ ahead_items: 0,
+ };
+ let parts = metrics.summary_parts(false, 1);
+ assert_eq!(parts, vec!["1 worktree", "1 column hidden"]);
+
+ let parts = metrics.summary_parts(false, 3);
+ assert_eq!(parts, vec!["1 worktree", "3 columns hidden"]);
+ }
+
+ #[test]
+ fn test_summary_metrics_summary_parts_branches_no_local() {
+ let metrics = SummaryMetrics {
+ worktrees: 2,
+ local_branches: 0,
+ remote_branches: 5,
+ dirty_worktrees: 0,
+ ahead_items: 0,
+ };
+ let parts = metrics.summary_parts(true, 0);
+ assert_eq!(parts, vec!["2 worktrees", "5 remote branches"]);
+ }
+
+ #[test]
+ fn test_summary_metrics_summary_parts_all_features() {
+ let metrics = SummaryMetrics {
+ worktrees: 5,
+ local_branches: 3,
+ remote_branches: 8,
+ dirty_worktrees: 2,
+ ahead_items: 4,
+ };
+ let parts = metrics.summary_parts(true, 2);
+ assert_eq!(
+ parts,
+ vec![
+ "5 worktrees",
+ "3 branches",
+ "8 remote branches",
+ "2 with changes",
+ "4 ahead",
+ "2 columns hidden"
+ ]
+ );
+ }
+}
diff --git a/src/commands/list/progressive_table.rs b/src/commands/list/progressive_table.rs
index e9b56e2ee..2ce9e381c 100644
--- a/src/commands/list/progressive_table.rs
+++ b/src/commands/list/progressive_table.rs
@@ -248,4 +248,131 @@ mod tests {
table.update_footer("done".into()).unwrap();
assert_eq!(table.lines.last().unwrap(), "done");
}
+
+ #[test]
+ fn test_truncation_applied() {
+ let long_header = "this is a very long header that exceeds width".to_string();
+ let skeletons = vec!["short".to_string()];
+ let footer = "loading...".to_string();
+
+ let table = ProgressiveTable::new(long_header.clone(), skeletons, footer, 20);
+
+ // Header should be truncated (shorter than original)
+ assert!(
+ table.lines[0].len() < long_header.len(),
+ "Header '{}' should be shorter than '{}'",
+ table.lines[0],
+ long_header
+ );
+ }
+
+ #[test]
+ fn test_update_footer_no_change() {
+ let header = "header".to_string();
+ let skeletons = vec!["row0".to_string()];
+ let footer = "loading".to_string();
+
+ let mut table = ProgressiveTable::new(header, skeletons, footer.clone(), 80);
+
+ // First footer should match
+ assert_eq!(table.lines.last().unwrap(), &footer);
+
+ // Update with same content should be a no-op
+ table.update_footer(footer.clone()).unwrap();
+ assert_eq!(table.lines.last().unwrap(), &footer);
+ }
+
+ #[test]
+ fn test_is_tty_returns_value() {
+ let table = ProgressiveTable::new(
+ "header".to_string(),
+ vec!["row".to_string()],
+ "footer".to_string(),
+ 80,
+ );
+
+ // In test environment, stderr is typically not a TTY
+ // Just ensure the method can be called without panicking
+ let _is_tty = table.is_tty();
+ }
+
+ #[test]
+ fn test_row_count_tracking() {
+ let table = ProgressiveTable::new(
+ "h".to_string(),
+ vec!["a".to_string(), "b".to_string(), "c".to_string()],
+ "f".to_string(),
+ 80,
+ );
+
+ assert_eq!(table.row_count, 3);
+ }
+
+ #[test]
+ fn test_update_row_bounds_check() {
+ let mut table = ProgressiveTable::new(
+ "header".to_string(),
+ vec!["row0".to_string(), "row1".to_string()],
+ "footer".to_string(),
+ 80,
+ );
+
+ // Should not panic when updating out-of-bounds row
+ table
+ .update_row(10, "should be ignored".to_string())
+ .unwrap();
+
+ // Original rows should be unchanged
+ assert_eq!(table.lines[1], "row0");
+ assert_eq!(table.lines[2], "row1");
+ }
+
+ #[test]
+ fn test_finalize_tty_updates_footer() {
+ let mut table = ProgressiveTable::new(
+ "header".to_string(),
+ vec!["row".to_string()],
+ "loading...".to_string(),
+ 80,
+ );
+
+ // In non-TTY test environment, finalize_tty should still update footer internally
+ table.finalize_tty("Complete!".to_string()).unwrap();
+
+ // Note: In non-TTY mode, finalize_tty returns early, so footer won't change
+ // This tests that the method doesn't panic
+ }
+
+ #[test]
+ fn test_finalize_non_tty() {
+ let table = ProgressiveTable::new(
+ "header".to_string(),
+ vec!["row".to_string()],
+ "loading".to_string(),
+ 80,
+ );
+
+ let final_lines = vec![
+ "Final Header".to_string(),
+ "Final Row".to_string(),
+ "".to_string(),
+ "Complete".to_string(),
+ ];
+
+ // Should not panic (writes to stderr which may fail in some test envs)
+ let _ = table.finalize_non_tty(final_lines);
+ }
+
+ #[test]
+ fn test_render_initial_non_tty() {
+ let table = ProgressiveTable::new(
+ "header".to_string(),
+ vec!["row".to_string()],
+ "footer".to_string(),
+ 80,
+ );
+
+ // In non-TTY mode, render_initial should be a no-op
+ table.render_initial().unwrap();
+ }
}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 1a0c89611..9e8e8a1d1 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -88,3 +88,33 @@ pub fn show_diffstat(repo: &worktrunk::git::Repository, range: &str) -> anyhow::
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_format_command_label_with_name() {
+ let result = format_command_label("post-create", Some("install"));
+ assert!(result.contains("Running"));
+ assert!(result.contains("post-create"));
+ assert!(result.contains("install"));
+ }
+
+ #[test]
+ fn test_format_command_label_without_name() {
+ let result = format_command_label("pre-merge", None);
+ assert_eq!(result, "Running pre-merge");
+ }
+
+ #[test]
+ fn test_format_command_label_various_types() {
+ let result = format_command_label("post-start", Some("build"));
+ assert!(result.contains("post-start"));
+ assert!(result.contains("build"));
+
+ let result = format_command_label("pre-commit", None);
+ assert!(result.contains("pre-commit"));
+ assert!(!result.contains("None"));
+ }
+}
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 1623c0d72..bc2e5e20f 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -285,4 +285,25 @@ mod tests {
assert_eq!(sanitize_for_filename("CONSOLE"), "CONSOLE");
assert_eq!(sanitize_for_filename("COM10"), "COM10");
}
+
+ #[test]
+ fn test_posix_command_separator() {
+ // Commands ending with newline don't need separator
+ assert_eq!(posix_command_separator("echo hello\n"), "");
+
+ // Commands ending with semicolon don't need separator
+ assert_eq!(posix_command_separator("echo hello;"), "");
+
+ // Commands without trailing newline/semicolon need separator
+ assert_eq!(posix_command_separator("echo hello"), ";");
+
+ // Empty command needs separator
+ assert_eq!(posix_command_separator(""), ";");
+
+ // Commands with internal newlines but not trailing
+ assert_eq!(posix_command_separator("echo\nhello"), ";");
+
+ // Commands with internal semicolons but not trailing
+ assert_eq!(posix_command_separator("echo; hello"), ";");
+ }
}
diff --git a/src/commands/project_config.rs b/src/commands/project_config.rs
index c66730c8d..3d16c5423 100644
--- a/src/commands/project_config.rs
+++ b/src/commands/project_config.rs
@@ -22,3 +22,99 @@ pub fn collect_commands_for_hooks(
}
commands
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn make_project_config_with_hooks() -> ProjectConfig {
+ // Use TOML deserialization to create ProjectConfig
+ let toml_content = r#"
+post-create = "npm install"
+pre-merge = "cargo test"
+"#;
+ toml::from_str(toml_content).unwrap()
+ }
+
+ #[test]
+ fn test_collect_commands_for_hooks_empty_hooks() {
+ let config = make_project_config_with_hooks();
+ let commands = collect_commands_for_hooks(&config, &[]);
+ assert!(commands.is_empty());
+ }
+
+ #[test]
+ fn test_collect_commands_for_hooks_single_hook() {
+ let config = make_project_config_with_hooks();
+ let commands = collect_commands_for_hooks(&config, &[HookType::PostCreate]);
+ assert_eq!(commands.len(), 1);
+ assert_eq!(commands[0].template, "npm install");
+ }
+
+ #[test]
+ fn test_collect_commands_for_hooks_multiple_hooks() {
+ let config = make_project_config_with_hooks();
+ let commands =
+ collect_commands_for_hooks(&config, &[HookType::PostCreate, HookType::PreMerge]);
+ assert_eq!(commands.len(), 2);
+ assert_eq!(commands[0].template, "npm install");
+ assert_eq!(commands[1].template, "cargo test");
+ }
+
+ #[test]
+ fn test_collect_commands_for_hooks_missing_hook() {
+ let config = make_project_config_with_hooks();
+ let commands = collect_commands_for_hooks(&config, &[HookType::PostStart]);
+ assert!(commands.is_empty());
+ }
+
+ #[test]
+ fn test_collect_commands_for_hooks_order_preserved() {
+ let config = make_project_config_with_hooks();
+ // Order should match the order of hooks provided
+ let commands =
+ collect_commands_for_hooks(&config, &[HookType::PreMerge, HookType::PostCreate]);
+ assert_eq!(commands.len(), 2);
+ assert_eq!(commands[0].template, "cargo test");
+ assert_eq!(commands[1].template, "npm install");
+ }
+
+ #[test]
+ fn test_collect_commands_for_hooks_all_hook_types() {
+ let config = ProjectConfig::default();
+ // All hooks should work even when empty
+ let hooks = [
+ HookType::PostCreate,
+ HookType::PostStart,
+ HookType::PreCommit,
+ HookType::PreMerge,
+ HookType::PostMerge,
+ HookType::PreRemove,
+ ];
+ let commands = collect_commands_for_hooks(&config, &hooks);
+ assert!(commands.is_empty());
+ }
+
+ #[test]
+ fn test_collect_commands_for_hooks_named_commands() {
+ let toml_content = r#"
+[post-create]
+install = "npm install"
+build = "npm run build"
+"#;
+ let config: ProjectConfig = toml::from_str(toml_content).unwrap();
+ let commands = collect_commands_for_hooks(&config, &[HookType::PostCreate]);
+ assert_eq!(commands.len(), 2);
+ // Named commands preserve order from TOML
+ assert_eq!(commands[0].name, Some("install".to_string()));
+ assert_eq!(commands[1].name, Some("build".to_string()));
+ }
+
+ #[test]
+ fn test_collect_commands_for_hooks_phase_is_set() {
+ let config = make_project_config_with_hooks();
+ let commands = collect_commands_for_hooks(&config, &[HookType::PostCreate]);
+ assert_eq!(commands.len(), 1);
+ assert_eq!(commands[0].phase, HookType::PostCreate);
+ }
+}
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index ac5316487..6828b7a70 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -517,4 +517,56 @@ mod tests {
// Should include new.txt, old path is simply not added
assert_eq!(result, vec!["new.txt"]);
}
+
+ #[test]
+ fn test_auto_stage_warning_from_status_untracked() {
+ let warning = AutoStageWarning::from_status("?? new.txt\0");
+ assert_eq!(warning.files, vec!["new.txt"]);
+ }
+
+ #[test]
+ fn test_auto_stage_warning_from_status_multiple_untracked() {
+ let warning = AutoStageWarning::from_status("?? file1.txt\0?? file2.txt\0?? file3.txt\0");
+ assert_eq!(warning.files, vec!["file1.txt", "file2.txt", "file3.txt"]);
+ }
+
+ #[test]
+ fn test_auto_stage_warning_from_status_ignores_modified() {
+ // Only untracked files should be collected
+ let warning = AutoStageWarning::from_status(" M modified.txt\0?? untracked.txt\0");
+ assert_eq!(warning.files, vec!["untracked.txt"]);
+ }
+
+ #[test]
+ fn test_auto_stage_warning_from_status_ignores_staged() {
+ let warning = AutoStageWarning::from_status("M staged.txt\0?? untracked.txt\0");
+ assert_eq!(warning.files, vec!["untracked.txt"]);
+ }
+
+ #[test]
+ fn test_auto_stage_warning_from_status_empty() {
+ let warning = AutoStageWarning::from_status("");
+ assert!(warning.files.is_empty());
+ }
+
+ #[test]
+ fn test_auto_stage_warning_from_status_skips_rename_old_path() {
+ // Rename entries have old path as second NUL-separated field
+ let warning = AutoStageWarning::from_status("R new.txt\0old.txt\0?? untracked.txt\0");
+ // Should only have untracked file, not the rename paths
+ assert_eq!(warning.files, vec!["untracked.txt"]);
+ }
+
+ #[test]
+ fn test_auto_stage_warning_from_status_with_spaces() {
+ let warning = AutoStageWarning::from_status("?? file with spaces.txt\0");
+ assert_eq!(warning.files, vec!["file with spaces.txt"]);
+ }
+
+ #[test]
+ fn test_auto_stage_warning_from_status_no_untracked() {
+ // All files are tracked (modified, staged, etc.)
+ let warning = AutoStageWarning::from_status(" M file1.txt\0M file2.txt\0");
+ assert!(warning.files.is_empty());
+ }
}
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index 59bbdbdfb..154164550 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -898,3 +898,56 @@ fn expand_command_template(template: &str, ctx: &CommandContext, hook_type: Hook
worktrunk::config::expand_template(template, &vars, true)
.unwrap_or_else(|_| template.to_string())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_squash_result_variants() {
+ // Test Debug implementation
+ let result = SquashResult::Squashed;
+ let debug = format!("{:?}", result);
+ assert!(debug.contains("Squashed"));
+
+ let result = SquashResult::NoCommitsAhead("main".to_string());
+ let debug = format!("{:?}", result);
+ assert!(debug.contains("NoCommitsAhead"));
+ assert!(debug.contains("main"));
+
+ let result = SquashResult::AlreadySingleCommit;
+ let debug = format!("{:?}", result);
+ assert!(debug.contains("AlreadySingleCommit"));
+
+ let result = SquashResult::NoNetChanges;
+ let debug = format!("{:?}", result);
+ assert!(debug.contains("NoNetChanges"));
+ }
+
+ #[test]
+ fn test_squash_result_clone() {
+ let original = SquashResult::NoCommitsAhead("develop".to_string());
+ let cloned = original.clone();
+ assert!(matches!(cloned, SquashResult::NoCommitsAhead(ref s) if s == "develop"));
+ }
+
+ #[test]
+ fn test_rebase_result_variants() {
+ // RebaseResult doesn't derive Debug/Clone by default, just test matching
+ let result = RebaseResult::Rebased;
+ assert!(matches!(result, RebaseResult::Rebased));
+
+ let result = RebaseResult::UpToDate("main".to_string());
+ assert!(matches!(result, RebaseResult::UpToDate(ref s) if s == "main"));
+ }
+
+ #[test]
+ fn test_rebase_result_up_to_date_branch_extraction() {
+ let result = RebaseResult::UpToDate("feature-branch".to_string());
+ if let RebaseResult::UpToDate(branch) = result {
+ assert_eq!(branch, "feature-branch");
+ } else {
+ panic!("Expected UpToDate variant");
+ }
+ }
+}
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 13333b655..91b94515b 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -971,3 +971,242 @@ pub fn handle_push(
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_switch_result_path_already_at() {
+ let path = PathBuf::from("/test/path");
+ let result = SwitchResult::AlreadyAt(path.clone());
+ assert_eq!(result.path(), &path);
+ }
+
+ #[test]
+ fn test_switch_result_path_existing() {
+ let path = PathBuf::from("/test/existing");
+ let result = SwitchResult::Existing(path.clone());
+ assert_eq!(result.path(), &path);
+ }
+
+ #[test]
+ fn test_switch_result_path_created() {
+ let path = PathBuf::from("/test/created");
+ let result = SwitchResult::Created {
+ path: path.clone(),
+ created_branch: true,
+ base_branch: Some("main".to_string()),
+ from_remote: None,
+ };
+ assert_eq!(result.path(), &path);
+ }
+
+ #[test]
+ fn test_switch_result_created_with_remote() {
+ let path = PathBuf::from("/test/remote");
+ let result = SwitchResult::Created {
+ path: path.clone(),
+ created_branch: false,
+ base_branch: None,
+ from_remote: Some("origin/feature".to_string()),
+ };
+ assert_eq!(result.path(), &path);
+ }
+
+ #[test]
+ fn test_switch_branch_info_is_branch_mismatch_true() {
+ let info = SwitchBranchInfo {
+ expected: "feature".to_string(),
+ current: Some("main".to_string()),
+ expected_path: None,
+ };
+ assert!(info.is_branch_mismatch());
+ }
+
+ #[test]
+ fn test_switch_branch_info_is_branch_mismatch_false() {
+ let info = SwitchBranchInfo {
+ expected: "feature".to_string(),
+ current: Some("feature".to_string()),
+ expected_path: None,
+ };
+ assert!(!info.is_branch_mismatch());
+ }
+
+ #[test]
+ fn test_switch_branch_info_is_branch_mismatch_detached() {
+ let info = SwitchBranchInfo {
+ expected: "feature".to_string(),
+ current: None, // Detached HEAD
+ expected_path: None,
+ };
+ assert!(info.is_branch_mismatch());
+ }
+
+ #[test]
+ fn test_switch_branch_info_branch_with_current() {
+ let info = SwitchBranchInfo {
+ expected: "expected".to_string(),
+ current: Some("current".to_string()),
+ expected_path: None,
+ };
+ assert_eq!(info.branch(), "current");
+ }
+
+ #[test]
+ fn test_switch_branch_info_branch_without_current() {
+ let info = SwitchBranchInfo {
+ expected: "expected".to_string(),
+ current: None,
+ expected_path: None,
+ };
+ assert_eq!(info.branch(), "expected");
+ }
+
+ #[test]
+ fn test_switch_branch_info_with_expected_path() {
+ let info = SwitchBranchInfo {
+ expected: "feature".to_string(),
+ current: Some("feature".to_string()),
+ expected_path: Some(PathBuf::from("/expected/path")),
+ };
+ assert_eq!(
+ info.expected_path.as_ref().unwrap().to_str().unwrap(),
+ "/expected/path"
+ );
+ }
+
+ #[test]
+ fn test_merge_operations_struct() {
+ let ops = MergeOperations {
+ committed: true,
+ squashed: false,
+ rebased: true,
+ };
+ assert!(ops.committed);
+ assert!(!ops.squashed);
+ assert!(ops.rebased);
+ }
+
+ #[test]
+ fn test_merge_operations_clone() {
+ let ops = MergeOperations {
+ committed: true,
+ squashed: true,
+ rebased: false,
+ };
+ // MergeOperations implements both Clone and Copy
+ // Use Clone explicitly to test the Clone impl
+ let cloned = Clone::clone(&ops);
+ assert_eq!(ops.committed, cloned.committed);
+ assert_eq!(ops.squashed, cloned.squashed);
+ assert_eq!(ops.rebased, cloned.rebased);
+ }
+
+ #[test]
+ fn test_merge_operations_copy() {
+ let ops = MergeOperations {
+ committed: false,
+ squashed: false,
+ rebased: true,
+ };
+ let copied = ops; // Copy trait
+ assert_eq!(ops.committed, copied.committed);
+ assert_eq!(ops.squashed, copied.squashed);
+ assert_eq!(ops.rebased, copied.rebased);
+ }
+
+ #[test]
+ fn test_merge_operations_debug() {
+ let ops = MergeOperations {
+ committed: true,
+ squashed: false,
+ rebased: true,
+ };
+ let debug = format!("{:?}", ops);
+ assert!(debug.contains("committed: true"));
+ assert!(debug.contains("squashed: false"));
+ assert!(debug.contains("rebased: true"));
+ }
+
+ #[test]
+ fn test_remove_result_removed_worktree() {
+ let result = RemoveResult::RemovedWorktree {
+ main_path: PathBuf::from("/main"),
+ worktree_path: PathBuf::from("/worktree"),
+ changed_directory: true,
+ branch_name: Some("feature".to_string()),
+ no_delete_branch: false,
+ force_delete: false,
+ target_branch: Some("main".to_string()),
+ };
+ match result {
+ RemoveResult::RemovedWorktree {
+ main_path,
+ worktree_path,
+ changed_directory,
+ branch_name,
+ no_delete_branch,
+ force_delete,
+ target_branch,
+ } => {
+ assert_eq!(main_path.to_str().unwrap(), "/main");
+ assert_eq!(worktree_path.to_str().unwrap(), "/worktree");
+ assert!(changed_directory);
+ assert_eq!(branch_name.as_deref(), Some("feature"));
+ assert!(!no_delete_branch);
+ assert!(!force_delete);
+ assert_eq!(target_branch.as_deref(), Some("main"));
+ }
+ _ => panic!("Expected RemovedWorktree variant"),
+ }
+ }
+
+ #[test]
+ fn test_remove_result_branch_only() {
+ let result = RemoveResult::BranchOnly {
+ branch_name: "stale-branch".to_string(),
+ no_delete_branch: true,
+ force_delete: false,
+ };
+ match result {
+ RemoveResult::BranchOnly {
+ branch_name,
+ no_delete_branch,
+ force_delete,
+ } => {
+ assert_eq!(branch_name, "stale-branch");
+ assert!(no_delete_branch);
+ assert!(!force_delete);
+ }
+ _ => panic!("Expected BranchOnly variant"),
+ }
+ }
+
+ #[test]
+ fn test_remove_result_with_force_delete() {
+ let result = RemoveResult::RemovedWorktree {
+ main_path: PathBuf::from("/main"),
+ worktree_path: PathBuf::from("/worktree"),
+ changed_directory: false,
+ branch_name: None, // Detached HEAD
+ no_delete_branch: true,
+ force_delete: true,
+ target_branch: None,
+ };
+ match result {
+ RemoveResult::RemovedWorktree {
+ branch_name,
+ no_delete_branch,
+ force_delete,
+ ..
+ } => {
+ assert!(branch_name.is_none());
+ assert!(no_delete_branch);
+ assert!(force_delete);
+ }
+ _ => panic!("Expected RemovedWorktree variant"),
+ }
+ }
+}
diff --git a/src/display.rs b/src/display.rs
index 1dc9cf0df..f6bd43e06 100644
--- a/src/display.rs
+++ b/src/display.rs
@@ -332,4 +332,49 @@ mod tests {
let result = shorten_path(&other, &prefix);
assert!(!result.starts_with("./"));
}
+
+ #[test]
+ fn test_format_relative_time_short_public() {
+ // Test the public function (uses get_now internally)
+ let result = format_relative_time_short(0);
+ // A timestamp of 0 (Unix epoch) should show years ago
+ assert!(
+ result.contains('y') || result == "future",
+ "Expected years format, got: {}",
+ result
+ );
+ }
+
+ #[test]
+ fn test_get_now() {
+ // get_now should return a reasonable timestamp
+ let now = get_now();
+ // Should be after 2020 (1577836800)
+ assert!(now > 1577836800, "get_now() should return current time");
+ }
+
+ #[test]
+ fn test_truncate_edge_cases() {
+ // Empty string
+ let result = truncate_at_word_boundary("", 10);
+ assert_eq!(result, "");
+
+ // Single character
+ let result = truncate_at_word_boundary("X", 10);
+ assert_eq!(result, "X");
+
+ // Exact width
+ let result = truncate_at_word_boundary("12345", 5);
+ assert_eq!(result, "12345");
+
+ // Just over width
+ let result = truncate_at_word_boundary("123456", 5);
+ assert!(result.ends_with('…'));
+ }
+
+ #[test]
+ fn test_find_common_prefix_relative_paths() {
+ let paths = vec![PathBuf::from("src/main.rs"), PathBuf::from("src/lib.rs")];
+ assert_eq!(find_common_prefix(&paths), PathBuf::from("src"));
+ }
}
diff --git a/src/git/error.rs b/src/git/error.rs
index aef96c417..22d1251e7 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -856,4 +856,427 @@ mod tests {
""
);
}
+
+ #[test]
+ fn test_git_error_invalid_reference() {
+ let err = GitError::InvalidReference {
+ reference: "nonexistent".into(),
+ };
+ let display = err.to_string();
+ assert!(display.contains("nonexistent"));
+ assert!(display.contains("not found"));
+ assert!(display.contains("--create"));
+ }
+
+ #[test]
+ fn test_git_error_worktree_missing() {
+ let err = GitError::WorktreeMissing {
+ branch: "feature".into(),
+ };
+ let display = err.to_string();
+ assert!(display.contains("feature"));
+ assert!(display.contains("missing"));
+ }
+
+ #[test]
+ fn test_git_error_no_worktree_found() {
+ let err = GitError::NoWorktreeFound {
+ branch: "feature".into(),
+ };
+ let display = err.to_string();
+ assert!(display.contains("No worktree found"));
+ assert!(display.contains("feature"));
+ }
+
+ #[test]
+ fn test_git_error_remote_only_branch() {
+ let err = GitError::RemoteOnlyBranch {
+ branch: "feature".into(),
+ remote: "origin".into(),
+ };
+ let display = err.to_string();
+ assert!(display.contains("feature"));
+ assert!(display.contains("remote"));
+ assert!(display.contains("origin"));
+ }
+
+ #[test]
+ fn test_git_error_worktree_path_occupied() {
+ // With occupant branch
+ let err = GitError::WorktreePathOccupied {
+ branch: "feature".into(),
+ path: PathBuf::from("/tmp/repo"),
+ occupant: Some("main".into()),
+ };
+ let display = err.to_string();
+ assert!(display.contains("feature"));
+ assert!(display.contains("main"));
+ assert!(display.contains("existing worktree"));
+
+ // Without occupant (detached)
+ let err = GitError::WorktreePathOccupied {
+ branch: "feature".into(),
+ path: PathBuf::from("/tmp/repo"),
+ occupant: None,
+ };
+ let display = err.to_string();
+ assert!(display.contains("detached"));
+ }
+
+ #[test]
+ fn test_git_error_worktree_creation_failed() {
+ // With base branch
+ let err = GitError::WorktreeCreationFailed {
+ branch: "feature".into(),
+ base_branch: Some("main".into()),
+ error: "git error".into(),
+ };
+ let display = err.to_string();
+ assert!(display.contains("feature"));
+ assert!(display.contains("main"));
+ assert!(display.contains("git error"));
+
+ // Without base branch
+ let err = GitError::WorktreeCreationFailed {
+ branch: "feature".into(),
+ base_branch: None,
+ error: "git error".into(),
+ };
+ let display = err.to_string();
+ assert!(display.contains("feature"));
+ }
+
+ #[test]
+ fn test_git_error_worktree_removal_failed() {
+ let err = GitError::WorktreeRemovalFailed {
+ branch: "feature".into(),
+ path: PathBuf::from("/tmp/repo"),
+ error: "still has changes".into(),
+ };
+ let display = err.to_string();
+ assert!(display.contains("feature"));
+ assert!(display.contains("still has changes"));
+ }
+
+ #[test]
+ fn test_git_error_cannot_remove_main() {
+ let err = GitError::CannotRemoveMainWorktree;
+ let display = err.to_string();
+ assert!(display.contains("main worktree"));
+ }
+
+ #[test]
+ fn test_git_error_conflicting_changes() {
+ let err = GitError::ConflictingChanges {
+ files: vec!["file1.rs".into(), "file2.rs".into()],
+ worktree_path: PathBuf::from("/tmp/repo"),
+ };
+ let display = err.to_string();
+ assert!(display.contains("conflicting"));
+ assert!(display.contains("file1.rs"));
+ }
+
+ #[test]
+ fn test_git_error_not_fast_forward() {
+ // In merge context
+ let err = GitError::NotFastForward {
+ target_branch: "main".into(),
+ commits_formatted: "abc1234 Some commit".into(),
+ in_merge_context: true,
+ };
+ let display = err.to_string();
+ assert!(display.contains("main"));
+ assert!(display.contains("wt merge"));
+
+ // Not in merge context
+ let err = GitError::NotFastForward {
+ target_branch: "main".into(),
+ commits_formatted: String::new(),
+ in_merge_context: false,
+ };
+ let display = err.to_string();
+ assert!(display.contains("wt step rebase"));
+ }
+
+ #[test]
+ fn test_git_error_merge_commits_found() {
+ let err = GitError::MergeCommitsFound;
+ let display = err.to_string();
+ assert!(display.contains("merge commits"));
+ assert!(display.contains("--allow-merge-commits"));
+ }
+
+ #[test]
+ fn test_git_error_rebase_conflict() {
+ // With git output
+ let err = GitError::RebaseConflict {
+ target_branch: "main".into(),
+ git_output: "CONFLICT in file.rs".into(),
+ };
+ let display = err.to_string();
+ assert!(display.contains("main"));
+ assert!(display.contains("CONFLICT"));
+
+ // Without git output
+ let err = GitError::RebaseConflict {
+ target_branch: "main".into(),
+ git_output: String::new(),
+ };
+ let display = err.to_string();
+ assert!(display.contains("rebase --continue"));
+ }
+
+ #[test]
+ fn test_git_error_not_rebased() {
+ let err = GitError::NotRebased {
+ target_branch: "main".into(),
+ };
+ let display = err.to_string();
+ assert!(display.contains("main"));
+ assert!(display.contains("not rebased"));
+ }
+
+ #[test]
+ fn test_git_error_push_failed() {
+ let err = GitError::PushFailed {
+ error: "rejected".into(),
+ };
+ let display = err.to_string();
+ assert!(display.contains("Push failed"));
+ assert!(display.contains("rejected"));
+ }
+
+ #[test]
+ fn test_git_error_not_interactive() {
+ let err = GitError::NotInteractive;
+ let display = err.to_string();
+ assert!(display.contains("non-interactive"));
+ assert!(display.contains("--force"));
+ }
+
+ #[test]
+ fn test_git_error_hook_command_not_found() {
+ // With available commands
+ let err = GitError::HookCommandNotFound {
+ name: "unknown".into(),
+ available: vec!["lint".into(), "test".into()],
+ };
+ let display = err.to_string();
+ assert!(display.contains("unknown"));
+ assert!(display.contains("lint"));
+
+ // No available commands
+ let err = GitError::HookCommandNotFound {
+ name: "unknown".into(),
+ available: vec![],
+ };
+ let display = err.to_string();
+ assert!(display.contains("no named commands"));
+ }
+
+ #[test]
+ fn test_git_error_llm_command_failed() {
+ // With reproduction command
+ let err = GitError::LlmCommandFailed {
+ command: "llm".into(),
+ error: "connection failed".into(),
+ reproduction_command: Some("wt step commit --show-prompt | llm".into()),
+ };
+ let display = err.to_string();
+ assert!(display.contains("connection failed"));
+ assert!(display.contains("wt step commit"));
+
+ // Without reproduction command
+ let err = GitError::LlmCommandFailed {
+ command: "llm --model gpt-4".into(),
+ error: "timeout".into(),
+ reproduction_command: None,
+ };
+ let display = err.to_string();
+ assert!(display.contains("llm --model gpt-4"));
+ }
+
+ #[test]
+ fn test_git_error_project_config_not_found() {
+ let err = GitError::ProjectConfigNotFound {
+ config_path: PathBuf::from("/.worktrunk.toml"),
+ };
+ let display = err.to_string();
+ assert!(display.contains("No project configuration"));
+ assert!(display.contains(".worktrunk.toml"));
+ }
+
+ #[test]
+ fn test_git_error_parse_error() {
+ let err = GitError::ParseError {
+ message: "invalid syntax".into(),
+ };
+ let display = err.to_string();
+ assert!(display.contains("invalid syntax"));
+ }
+
+ #[test]
+ fn test_git_error_other() {
+ let err = GitError::Other {
+ message: "something went wrong".into(),
+ };
+ let display = err.to_string();
+ assert!(display.contains("something went wrong"));
+ }
+
+ #[test]
+ fn test_git_error_detached_head_with_action() {
+ let err = GitError::DetachedHead {
+ action: Some("merge".into()),
+ };
+ let display = err.to_string();
+ assert!(display.contains("Cannot merge"));
+ assert!(display.contains("detached HEAD"));
+ }
+
+ #[test]
+ fn test_git_error_uncommitted_changes_variants() {
+ // Action only
+ let err = GitError::UncommittedChanges {
+ action: Some("push".into()),
+ worktree: None,
+ };
+ let display = err.to_string();
+ assert!(display.contains("Cannot push"));
+ assert!(display.contains("working tree"));
+
+ // Worktree only
+ let err = GitError::UncommittedChanges {
+ action: None,
+ worktree: Some("feature".into()),
+ };
+ let display = err.to_string();
+ assert!(display.contains("feature"));
+ assert!(display.contains("uncommitted"));
+
+ // Neither
+ let err = GitError::UncommittedChanges {
+ action: None,
+ worktree: None,
+ };
+ let display = err.to_string();
+ assert!(display.contains("Working tree"));
+ }
+
+ #[test]
+ fn test_git_error_not_fast_forward_empty_commits() {
+ // Test with empty commits_formatted to cover that branch
+ let err = GitError::NotFastForward {
+ target_branch: "main".into(),
+ commits_formatted: "".into(),
+ in_merge_context: false,
+ };
+ let display = err.to_string();
+ assert!(display.contains("main"));
+ assert!(display.contains("newer commits"));
+ // Should still have hint
+ assert!(display.contains("rebase"));
+ }
+
+ #[test]
+ fn test_git_error_not_fast_forward_outside_merge() {
+ // Test outside merge context (in_merge_context = false)
+ let err = GitError::NotFastForward {
+ target_branch: "develop".into(),
+ commits_formatted: "abc123 Some commit".into(),
+ in_merge_context: false,
+ };
+ let display = err.to_string();
+ assert!(display.contains("develop"));
+ // Should have generic rebase hint, not "wt merge"
+ assert!(display.contains("rebase"));
+ // commits_formatted should be in gutter
+ assert!(display.contains("abc123"));
+ }
+
+ #[test]
+ fn test_git_error_conflicting_changes_empty_files() {
+ // Test with empty files list
+ let err = GitError::ConflictingChanges {
+ files: vec![],
+ worktree_path: PathBuf::from("/tmp/repo"),
+ };
+ let display = err.to_string();
+ assert!(display.contains("conflicting"));
+ // Should still have hint about commit/stash
+ assert!(display.contains("Commit or stash"));
+ }
+
+ #[test]
+ fn test_hook_error_with_hint_source() {
+ use crate::HookType;
+
+ // Create a WorktrunkError with hook_type
+ let inner_error: anyhow::Error = WorktrunkError::HookCommandFailed {
+ hook_type: HookType::PreMerge,
+ command_name: Some("test".into()),
+ error: "Test failed".into(),
+ exit_code: Some(1),
+ }
+ .into();
+
+ // Wrap it using add_hook_skip_hint
+ let wrapped = add_hook_skip_hint(inner_error);
+
+ // The source() method should return the underlying error
+ let source = wrapped.source();
+ // source can be Some or None depending on implementation
+ let _ = source;
+ }
+
+ #[test]
+ fn test_add_hook_skip_hint_with_hook_type() {
+ use crate::HookType;
+
+ let inner: anyhow::Error = WorktrunkError::HookCommandFailed {
+ hook_type: HookType::PreCommit,
+ command_name: Some("build".into()),
+ error: "Build failed".into(),
+ exit_code: Some(1),
+ }
+ .into();
+
+ let wrapped = add_hook_skip_hint(inner);
+ let display = wrapped.to_string();
+
+ // Should include the original error
+ assert!(display.contains("build"));
+ // Should include the hint
+ assert!(display.contains("--no-verify"));
+ assert!(display.contains("pre-commit"));
+ }
+
+ #[test]
+ fn test_add_hook_skip_hint_non_hook_error() {
+ // Test with a non-hook error (should pass through unchanged)
+ let inner: anyhow::Error = GitError::Other {
+ message: "some error".into(),
+ }
+ .into();
+
+ let wrapped = add_hook_skip_hint(inner);
+ let display = wrapped.to_string();
+
+ // Should include the original error
+ assert!(display.contains("some error"));
+ // Should NOT include hint (not a hook error)
+ assert!(!display.contains("--no-verify"));
+ }
+
+ #[test]
+ fn test_rebase_conflict_empty_output() {
+ let err = GitError::RebaseConflict {
+ target_branch: "main".into(),
+ git_output: "".into(),
+ };
+ let display = err.to_string();
+ assert!(display.contains("incomplete"));
+ assert!(display.contains("main"));
+ // Empty output shouldn't cause issues
+ }
}
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index 964303144..aa7575f96 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -267,3 +267,140 @@ fn test_parse_remote_default_branch_branch_with_slash() {
.unwrap();
assert_eq!(branch, "feature/new-ui");
}
+
+use super::ResolvedWorktree;
+
+#[test]
+fn test_resolved_worktree_debug() {
+ let wt = ResolvedWorktree::Worktree {
+ path: PathBuf::from("/path/to/worktree"),
+ branch: Some("feature".to_string()),
+ };
+ let debug = format!("{:?}", wt);
+ assert!(debug.contains("Worktree"));
+ assert!(debug.contains("/path/to/worktree"));
+ assert!(debug.contains("feature"));
+}
+
+#[test]
+fn test_resolved_worktree_branch_only_debug() {
+ let wt = ResolvedWorktree::BranchOnly {
+ branch: "feature".to_string(),
+ };
+ let debug = format!("{:?}", wt);
+ assert!(debug.contains("BranchOnly"));
+ assert!(debug.contains("feature"));
+}
+
+#[test]
+fn test_resolved_worktree_clone() {
+ let wt = ResolvedWorktree::Worktree {
+ path: PathBuf::from("/path/to/worktree"),
+ branch: Some("feature".to_string()),
+ };
+ let cloned = wt.clone();
+ if let ResolvedWorktree::Worktree { path, branch } = cloned {
+ assert_eq!(path, PathBuf::from("/path/to/worktree"));
+ assert_eq!(branch, Some("feature".to_string()));
+ } else {
+ panic!("Expected Worktree variant");
+ }
+}
+
+#[test]
+fn test_resolved_worktree_none_branch() {
+ // Worktree with detached HEAD (no branch)
+ let wt = ResolvedWorktree::Worktree {
+ path: PathBuf::from("/path/to/worktree"),
+ branch: None,
+ };
+ if let ResolvedWorktree::Worktree { path, branch } = wt {
+ assert_eq!(path, PathBuf::from("/path/to/worktree"));
+ assert!(branch.is_none());
+ } else {
+ panic!("Expected Worktree variant");
+ }
+}
+
+#[test]
+fn test_worktree_locked_empty_reason() {
+ let output = "worktree /path/to/locked
+HEAD abcd1234
+branch refs/heads/main
+locked
+
+";
+
+ let worktrees = Worktree::parse_porcelain_list(output).unwrap();
+ assert_eq!(worktrees.len(), 1);
+ // Empty lock reason should still be recorded
+ assert_eq!(worktrees[0].locked, Some(String::new()));
+}
+
+#[test]
+fn test_worktree_prunable() {
+ let output = "worktree /path/to/prunable
+HEAD abcd1234
+detached
+prunable gitdir file points to non-existent location
+
+";
+
+ let worktrees = Worktree::parse_porcelain_list(output).unwrap();
+ assert_eq!(worktrees.len(), 1);
+ assert!(worktrees[0].prunable.is_some());
+ assert!(
+ worktrees[0]
+ .prunable
+ .as_ref()
+ .unwrap()
+ .contains("non-existent")
+ );
+}
+
+#[test]
+fn test_parse_multiple_worktrees() {
+ let output = "worktree /main
+HEAD 1111111111111111111111111111111111111111
+branch refs/heads/main
+
+worktree /feature-a
+HEAD 2222222222222222222222222222222222222222
+branch refs/heads/feature-a
+
+worktree /feature-b
+HEAD 3333333333333333333333333333333333333333
+branch refs/heads/feature-b
+
+worktree /detached
+HEAD 4444444444444444444444444444444444444444
+detached
+
+";
+
+ let worktrees = Worktree::parse_porcelain_list(output).unwrap();
+ assert_eq!(worktrees.len(), 4);
+ assert_eq!(worktrees[0].branch, Some("main".to_string()));
+ assert_eq!(worktrees[1].branch, Some("feature-a".to_string()));
+ assert_eq!(worktrees[2].branch, Some("feature-b".to_string()));
+ assert!(worktrees[3].detached);
+ assert_eq!(worktrees[3].branch, None);
+}
+
+#[test]
+fn test_default_branch_name_display() {
+ // Test that DefaultBranchName properly extracts branch names
+ let cases = [
+ ("origin/main\n", "main"),
+ ("upstream/develop\n", "develop"),
+ ("origin/master\n", "master"),
+ ];
+
+ for (input, expected) in cases {
+ let remote = input.split('/').next().unwrap();
+ let branch = DefaultBranchName::from_local(remote, input)
+ .map(DefaultBranchName::into_string)
+ .unwrap();
+ assert_eq!(branch, expected);
+ }
+}
diff --git a/src/llm.rs b/src/llm.rs
index 51964ec67..2fa709406 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -1330,4 +1330,55 @@ diff --git a/Cargo.lock b/Cargo.lock
// Should be truncated (max 50 files)
assert!(prepared.diff.contains("files omitted"));
}
+
+ #[test]
+ fn test_format_command_display_no_args() {
+ let result = format_command_display("echo", &[]);
+ assert_eq!(result, "echo");
+ }
+
+ #[test]
+ fn test_format_command_display_with_args() {
+ let args = vec!["--model".to_string(), "gpt-4".to_string()];
+ let result = format_command_display("llm", &args);
+ assert_eq!(result, "llm --model gpt-4");
+ }
+
+ #[test]
+ fn test_format_command_display_single_arg() {
+ let args = vec!["--help".to_string()];
+ let result = format_command_display("wt", &args);
+ assert_eq!(result, "wt --help");
+ }
+
+ #[test]
+ fn test_parse_diff_sections_empty() {
+ let sections = parse_diff_sections("");
+ assert!(sections.is_empty());
+ }
+
+ #[test]
+ fn test_parse_diff_sections_single_file() {
+ let diff = "diff --git a/foo.rs b/foo.rs\nsome content\n";
+ let sections = parse_diff_sections(diff);
+ assert_eq!(sections.len(), 1);
+ assert_eq!(sections[0].0, "foo.rs");
+ }
+
+ #[test]
+ fn test_truncate_diff_section_short() {
+ // Section shorter than max lines should pass through unchanged
+ let section = "line1\nline2\nline3\n";
+ let truncated = truncate_diff_section(section, 10);
+ assert_eq!(truncated, section);
+ }
+
+ #[test]
+ fn test_truncate_diff_section_no_header() {
+ // Section without @@ marker
+ let section = "line1\nline2\nline3\nline4\nline5\nline6\nline7\nline8\n";
+ let truncated = truncate_diff_section(section, 3);
+ assert!(truncated.contains("line1"));
+ assert!(truncated.contains("lines omitted"));
+ }
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 76a4d1dd7..59aea7ee2 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -916,3 +916,189 @@ pub fn execute_command_in_worktree(
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::path::PathBuf;
+ use worktrunk::git::IntegrationReason;
+
+ #[test]
+ fn test_format_switch_success_message() {
+ let path = PathBuf::from("/tmp/test");
+
+ // Switched to existing worktree (no creation, no remote)
+ let msg = format_switch_success_message("feature", &path, false, None, None);
+ assert!(msg.contains("Switched to worktree for"));
+ assert!(msg.contains("feature"));
+
+ // Created new worktree from base branch
+ let msg = format_switch_success_message("feature", &path, true, Some("main"), None);
+ assert!(msg.contains("Created new worktree for"));
+ assert!(msg.contains("from"));
+ assert!(msg.contains("main"));
+
+ // Created worktree from remote (DWIM)
+ let msg =
+ format_switch_success_message("feature", &path, false, None, Some("origin/feature"));
+ assert!(msg.contains("Created worktree for"));
+ assert!(msg.contains("origin/feature"));
+ }
+
+ #[test]
+ fn test_get_flag_note() {
+ // --no-delete-branch flag
+ assert_eq!(
+ get_flag_note(true, &BranchDeletionOutcome::NotDeleted, None),
+ " (--no-delete-branch)"
+ );
+
+ // NotDeleted without flag
+ assert_eq!(
+ get_flag_note(false, &BranchDeletionOutcome::NotDeleted, None),
+ ""
+ );
+
+ // Force deleted
+ assert_eq!(
+ get_flag_note(false, &BranchDeletionOutcome::ForceDeleted, None),
+ " (--force-delete)"
+ );
+
+ // Integration reasons
+ let cases = [
+ (IntegrationReason::SameCommit, "same commit as main"),
+ (IntegrationReason::Ancestor, "ancestor of main"),
+ (IntegrationReason::TreesMatch, "tree matches main"),
+ (IntegrationReason::MergeAddsNothing, "all changes in main"),
+ ];
+ for (reason, expected_contains) in cases {
+ let note = get_flag_note(
+ false,
+ &BranchDeletionOutcome::Integrated(reason),
+ Some("main"),
+ );
+ assert!(
+ note.contains(expected_contains),
+ "reason {:?} should contain '{}'",
+ reason,
+ expected_contains
+ );
+ }
+
+ // NoAddedChanges is special - no target shown
+ let note = get_flag_note(
+ false,
+ &BranchDeletionOutcome::Integrated(IntegrationReason::NoAddedChanges),
+ Some("main"),
+ );
+ assert!(note.contains("no added changes"));
+ assert!(!note.contains("main"));
+ }
+
+ #[test]
+ fn test_format_remove_worktree_message() {
+ let main_path = PathBuf::from("/home/user/project");
+
+ // Removed worktree and branch (integrated)
+ let msg = format_remove_worktree_message(
+ &main_path,
+ false,
+ "feature",
+ Some("feature"),
+ false,
+ &BranchDeletionOutcome::Integrated(IntegrationReason::SameCommit),
+ Some("main"),
+ );
+ assert!(msg.contains("feature"));
+ assert!(msg.contains("worktree & branch"));
+ assert!(msg.contains("same commit as main"));
+
+ // Removed worktree only (--no-delete-branch)
+ let msg = format_remove_worktree_message(
+ &main_path,
+ false,
+ "feature",
+ Some("feature"),
+ true,
+ &BranchDeletionOutcome::NotDeleted,
+ None,
+ );
+ assert!(msg.contains("worktree"));
+ assert!(!msg.contains("& branch"));
+ assert!(msg.contains("--no-delete-branch"));
+
+ // Removed with directory change
+ let msg = format_remove_worktree_message(
+ &main_path,
+ true,
+ "feature",
+ Some("feature"),
+ false,
+ &BranchDeletionOutcome::ForceDeleted,
+ None,
+ );
+ assert!(msg.contains("changed directory"));
+ assert!(msg.contains("--force-delete"));
+
+ // Unmerged branch retained
+ let msg = format_remove_worktree_message(
+ &main_path,
+ false,
+ "feature",
+ Some("feature"),
+ false,
+ &BranchDeletionOutcome::NotDeleted,
+ None,
+ );
+ assert!(msg.contains("retaining unmerged branch"));
+ }
+
+ #[test]
+ fn test_shell_integration_hint() {
+ let hint = shell_integration_hint();
+ assert!(hint.contains("wt config shell install"));
+ }
+
+ #[test]
+ fn test_build_remove_command() {
+ let path = PathBuf::from("/tmp/test-worktree");
+
+ // Without branch deletion
+ let cmd = build_remove_command(&path, None);
+ assert!(cmd.contains("git worktree remove"));
+ assert!(cmd.contains("/tmp/test-worktree"));
+ assert!(!cmd.contains("branch -D"));
+
+ // With branch deletion
+ let cmd = build_remove_command(&path, Some("feature-branch"));
+ assert!(cmd.contains("git worktree remove"));
+ assert!(cmd.contains("git branch -D"));
+ assert!(cmd.contains("feature-branch"));
+
+ // Shell escaping for special characters
+ let special_path = PathBuf::from("/tmp/test worktree");
+ let cmd = build_remove_command(&special_path, Some("feature/branch"));
+ assert!(cmd.contains("worktree remove"));
+ }
+
+ #[test]
+ fn test_branch_deletion_outcome_matching() {
+ // Ensure the match patterns work correctly
+ let outcomes = [
+ (BranchDeletionOutcome::NotDeleted, false),
+ (BranchDeletionOutcome::ForceDeleted, true),
+ (
+ BranchDeletionOutcome::Integrated(IntegrationReason::SameCommit),
+ true,
+ ),
+ ];
+ for (outcome, expected_deleted) in outcomes {
+ let deleted = matches!(
+ outcome,
+ BranchDeletionOutcome::ForceDeleted | BranchDeletionOutcome::Integrated(_)
+ );
+ assert_eq!(deleted, expected_deleted);
+ }
+ }
+}
diff --git a/src/path.rs b/src/path.rs
index a2e4b7ef6..9702ef354 100644
--- a/src/path.rs
+++ b/src/path.rs
@@ -185,4 +185,33 @@ mod tests {
"Expected converted path, got: {result}"
);
}
+
+ #[test]
+ fn test_home_dir_returns_valid_path() {
+ // home_dir should return a valid path on most systems
+ if let Some(home) = home_dir() {
+ assert!(home.is_absolute(), "Home directory should be absolute");
+ // The home directory itself might not exist in some CI environments,
+ // but the path should at least have components
+ assert!(home.components().count() > 0, "Home should have components");
+ }
+ }
+
+ #[test]
+ fn test_format_path_outside_home() {
+ // A path that definitely won't be under home
+ let path = PathBuf::from("/definitely/not/under/home/dir");
+ let result = format_path_for_display(&path);
+ // Should return unchanged
+ assert_eq!(result, "/definitely/not/under/home/dir");
+ }
+
+ #[test]
+ #[cfg(not(windows))]
+ fn test_to_posix_path_on_unix() {
+ // On Unix, to_posix_path is a no-op
+ assert_eq!(to_posix_path("/some/path"), "/some/path");
+ assert_eq!(to_posix_path("relative"), "relative");
+ assert_eq!(to_posix_path(""), "");
+ }
}
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index e83d01637..5c4b8da69 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -326,4 +326,35 @@ mod tests {
);
}
}
+
+ #[test]
+ fn test_shell_config_debug() {
+ let config = ShellConfig::get();
+ let debug = format!("{:?}", config);
+ assert!(debug.contains("ShellConfig"));
+ assert!(debug.contains(&config.name));
+ }
+
+ #[test]
+ fn test_shell_config_clone() {
+ let config = ShellConfig::get();
+ let cloned = config.clone();
+ assert_eq!(config.name, cloned.name);
+ assert_eq!(config.is_posix, cloned.is_posix);
+ assert_eq!(config.args, cloned.args);
+ }
+
+ #[test]
+ fn test_shell_is_posix_method() {
+ let config = ShellConfig::get();
+ // is_posix method should match the field
+ assert_eq!(config.is_posix(), config.is_posix);
+ }
+
+ #[test]
+ #[cfg(not(windows))]
+ fn test_unix_is_not_windows_without_git_bash() {
+ let config = ShellConfig::get();
+ assert!(!config.is_windows_without_git_bash());
+ }
}