Skip to content

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

Add unit tests to improve code coverage (#211)

Maximilian Roos724a14f94c66
diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rs
index 72b2266a3..abddd2d2d 100644
--- a/src/commands/list/json_output.rs
+++ b/src/commands/list/json_output.rs
@@ -471,3 +471,438 @@ fn format_raw_symbols(symbols: &super::model::StatusSymbols) -> String {
pub fn to_json_items(items: &[ListItem]) -> Vec<JsonItem> {
items.iter().map(JsonItem::from_list_item).collect()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::commands::list::ci_status::{CiSource, CiStatus};
+ use crate::commands::list::model::{
+ Divergence, GitOperationState, MainState, OperationState, StatusSymbols, WorkingTreeStatus,
+ WorktreeData, WorktreeState,
+ };
+ use std::path::PathBuf;
+
+ // ============================================================================
+ // JsonDiff Tests
+ // ============================================================================
+
+ #[test]
+ fn test_json_diff_from_line_diff() {
+ let line_diff = LineDiff {
+ added: 10,
+ deleted: 5,
+ };
+ let json_diff = JsonDiff::from(line_diff);
+ assert_eq!(json_diff.added, 10);
+ assert_eq!(json_diff.deleted, 5);
+ }
+
+ #[test]
+ fn test_json_diff_from_line_diff_zeros() {
+ let line_diff = LineDiff {
+ added: 0,
+ deleted: 0,
+ };
+ let json_diff = JsonDiff::from(line_diff);
+ assert_eq!(json_diff.added, 0);
+ assert_eq!(json_diff.deleted, 0);
+ }
+
+ // ============================================================================
+ // pr_status_to_json Tests
+ // ============================================================================
+
+ #[test]
+ fn test_pr_status_to_json_passed() {
+ let pr = PrStatus {
+ ci_status: CiStatus::Passed,
+ source: CiSource::PullRequest,
+ is_stale: false,
+ url: Some("https://github.com/org/repo/pull/123".to_string()),
+ };
+ let json = pr_status_to_json(&pr);
+ assert_eq!(json.ci, "passed");
+ assert_eq!(json.source, "pull_request");
+ assert!(!json.stale);
+ assert_eq!(
+ json.url,
+ Some("https://github.com/org/repo/pull/123".to_string())
+ );
+ }
+
+ #[test]
+ fn test_pr_status_to_json_failed_branch() {
+ let pr = PrStatus {
+ ci_status: CiStatus::Failed,
+ source: CiSource::Branch,
+ is_stale: true,
+ url: None,
+ };
+ let json = pr_status_to_json(&pr);
+ assert_eq!(json.ci, "failed");
+ assert_eq!(json.source, "branch");
+ assert!(json.stale);
+ assert!(json.url.is_none());
+ }
+
+ #[test]
+ fn test_pr_status_to_json_running() {
+ let pr = PrStatus {
+ ci_status: CiStatus::Running,
+ source: CiSource::PullRequest,
+ is_stale: false,
+ url: None,
+ };
+ let json = pr_status_to_json(&pr);
+ assert_eq!(json.ci, "running");
+ }
+
+ #[test]
+ fn test_pr_status_to_json_conflicts() {
+ let pr = PrStatus {
+ ci_status: CiStatus::Conflicts,
+ source: CiSource::PullRequest,
+ is_stale: false,
+ url: None,
+ };
+ let json = pr_status_to_json(&pr);
+ assert_eq!(json.ci, "conflicts");
+ }
+
+ #[test]
+ fn test_pr_status_to_json_no_ci() {
+ let pr = PrStatus {
+ ci_status: CiStatus::NoCI,
+ source: CiSource::Branch,
+ is_stale: false,
+ url: None,
+ };
+ let json = pr_status_to_json(&pr);
+ assert_eq!(json.ci, "no_ci");
+ }
+
+ #[test]
+ fn test_pr_status_to_json_error() {
+ let pr = PrStatus {
+ ci_status: CiStatus::Error,
+ source: CiSource::Branch,
+ is_stale: false,
+ url: None,
+ };
+ let json = pr_status_to_json(&pr);
+ assert_eq!(json.ci, "error");
+ }
+
+ // ============================================================================
+ // upstream_to_json Tests
+ // ============================================================================
+
+ #[test]
+ fn test_upstream_to_json_with_remote() {
+ let upstream = UpstreamStatus::from_parts(Some("origin".to_string()), 3, 2);
+ let branch = Some("feature".to_string());
+ let json = upstream_to_json(&upstream, &branch);
+ assert!(json.is_some());
+ let json = json.unwrap();
+ assert_eq!(json.name, "origin");
+ assert_eq!(json.branch, "feature");
+ assert_eq!(json.ahead, 3);
+ assert_eq!(json.behind, 2);
+ }
+
+ #[test]
+ fn test_upstream_to_json_no_remote() {
+ let upstream = UpstreamStatus::from_parts(None, 0, 0);
+ let branch = Some("feature".to_string());
+ let json = upstream_to_json(&upstream, &branch);
+ assert!(json.is_none());
+ }
+
+ #[test]
+ fn test_upstream_to_json_no_branch() {
+ let upstream = UpstreamStatus::from_parts(Some("origin".to_string()), 1, 0);
+ let branch = None;
+ let json = upstream_to_json(&upstream, &branch);
+ assert!(json.is_some());
+ let json = json.unwrap();
+ assert_eq!(json.branch, ""); // Empty string when branch is None
+ }
+
+ // ============================================================================
+ // worktree_state_to_json Tests
+ // ============================================================================
+
+ fn make_worktree_data() -> WorktreeData {
+ WorktreeData {
+ path: PathBuf::from("/test/path"),
+ is_main: false,
+ is_current: false,
+ is_previous: false,
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ working_tree_diff: None,
+ working_tree_diff_with_main: None,
+ git_operation: GitOperationState::None,
+ path_mismatch: false,
+ working_diff_display: None,
+ }
+ }
+
+ fn make_status_symbols_with_worktree_state(state: WorktreeState) -> StatusSymbols {
+ StatusSymbols {
+ working_tree: WorkingTreeStatus::default(),
+ worktree_state: state,
+ main_state: MainState::None,
+ operation_state: OperationState::None,
+ upstream_divergence: Divergence::None,
+ user_marker: None,
+ }
+ }
+
+ #[test]
+ fn test_worktree_state_to_json_none() {
+ let data = make_worktree_data();
+ let symbols = make_status_symbols_with_worktree_state(WorktreeState::None);
+ let (state, reason) = worktree_state_to_json(&data, Some(&symbols));
+ assert!(state.is_none());
+ assert!(reason.is_none());
+ }
+
+ #[test]
+ fn test_worktree_state_to_json_no_worktree() {
+ let data = make_worktree_data();
+ let symbols = make_status_symbols_with_worktree_state(WorktreeState::Branch);
+ let (state, reason) = worktree_state_to_json(&data, Some(&symbols));
+ assert_eq!(state, Some("no_worktree"));
+ assert!(reason.is_none());
+ }
+
+ #[test]
+ fn test_worktree_state_to_json_path_mismatch() {
+ let data = make_worktree_data();
+ let symbols = make_status_symbols_with_worktree_state(WorktreeState::PathMismatch);
+ let (state, reason) = worktree_state_to_json(&data, Some(&symbols));
+ assert_eq!(state, Some("path_mismatch"));
+ assert!(reason.is_none());
+ }
+
+ #[test]
+ fn test_worktree_state_to_json_locked() {
+ let mut data = make_worktree_data();
+ data.locked = Some("manual lock".to_string());
+ let symbols = make_status_symbols_with_worktree_state(WorktreeState::Locked);
+ let (state, reason) = worktree_state_to_json(&data, Some(&symbols));
+ assert_eq!(state, Some("locked"));
+ assert_eq!(reason, Some("manual lock".to_string()));
+ }
+
+ #[test]
+ fn test_worktree_state_to_json_prunable() {
+ let mut data = make_worktree_data();
+ data.prunable = Some("gitdir file missing".to_string());
+ let symbols = make_status_symbols_with_worktree_state(WorktreeState::Prunable);
+ let (state, reason) = worktree_state_to_json(&data, Some(&symbols));
+ assert_eq!(state, Some("prunable"));
+ assert_eq!(reason, Some("gitdir file missing".to_string()));
+ }
+
+ #[test]
+ fn test_worktree_state_to_json_fallback_prunable() {
+ let mut data = make_worktree_data();
+ data.prunable = Some("missing gitdir".to_string());
+ // No status symbols provided - fallback to data fields
+ let (state, reason) = worktree_state_to_json(&data, None);
+ assert_eq!(state, Some("prunable"));
+ assert_eq!(reason, Some("missing gitdir".to_string()));
+ }
+
+ #[test]
+ fn test_worktree_state_to_json_fallback_locked() {
+ let mut data = make_worktree_data();
+ data.locked = Some("in use".to_string());
+ let (state, reason) = worktree_state_to_json(&data, None);
+ assert_eq!(state, Some("locked"));
+ assert_eq!(reason, Some("in use".to_string()));
+ }
+
+ // ============================================================================
+ // format_raw_symbols Tests
+ // ============================================================================
+
+ #[test]
+ fn test_format_raw_symbols_empty() {
+ let symbols = StatusSymbols::default();
+ let result = format_raw_symbols(&symbols);
+ assert!(result.is_empty());
+ }
+
+ #[test]
+ fn test_format_raw_symbols_working_tree() {
+ let symbols = StatusSymbols {
+ working_tree: WorkingTreeStatus::new(true, true, true, false, false),
+ ..Default::default()
+ };
+ let result = format_raw_symbols(&symbols);
+ assert!(result.contains('+'));
+ assert!(result.contains('!'));
+ assert!(result.contains('?'));
+ }
+
+ #[test]
+ fn test_format_raw_symbols_main_state() {
+ let symbols = StatusSymbols {
+ main_state: MainState::Ahead,
+ ..Default::default()
+ };
+ let result = format_raw_symbols(&symbols);
+ assert!(result.contains('↑'));
+ }
+
+ #[test]
+ fn test_format_raw_symbols_upstream_divergence() {
+ let symbols = StatusSymbols {
+ upstream_divergence: Divergence::Behind,
+ ..Default::default()
+ };
+ let result = format_raw_symbols(&symbols);
+ assert!(result.contains('⇣'));
+ }
+
+ #[test]
+ fn test_format_raw_symbols_operation_state() {
+ let symbols = StatusSymbols {
+ operation_state: OperationState::Rebase,
+ ..Default::default()
+ };
+ let result = format_raw_symbols(&symbols);
+ assert!(result.contains('⤴'));
+ }
+
+ #[test]
+ fn test_format_raw_symbols_worktree_state() {
+ let symbols = StatusSymbols {
+ worktree_state: WorktreeState::Locked,
+ ..Default::default()
+ };
+ let result = format_raw_symbols(&symbols);
+ assert!(result.contains('⊞'));
+ }
+
+ #[test]
+ fn test_format_raw_symbols_user_marker() {
+ let symbols = StatusSymbols {
+ user_marker: Some("🔥".to_string()),
+ ..Default::default()
+ };
+ let result = format_raw_symbols(&symbols);
+ assert!(result.contains("🔥"));
+ }
+
+ #[test]
+ fn test_format_raw_symbols_combined() {
+ let symbols = StatusSymbols {
+ working_tree: WorkingTreeStatus::new(true, false, false, false, false),
+ main_state: MainState::Behind,
+ upstream_divergence: Divergence::Ahead,
+ ..Default::default()
+ };
+ let result = format_raw_symbols(&symbols);
+ assert!(result.contains('+'));
+ assert!(result.contains('↓'));
+ assert!(result.contains('⇡'));
+ }
+
+ // ============================================================================
+ // JSON Serialization Tests
+ // ============================================================================
+
+ #[test]
+ fn test_json_commit_serialization() {
+ let commit = JsonCommit {
+ sha: "abc123def456".to_string(),
+ short_sha: "abc123d".to_string(),
+ message: "Fix bug".to_string(),
+ timestamp: 1700000000,
+ };
+ let json = serde_json::to_string(&commit).unwrap();
+ assert!(json.contains("abc123def456"));
+ assert!(json.contains("Fix bug"));
+ assert!(json.contains("1700000000"));
+ }
+
+ #[test]
+ fn test_json_working_tree_serialization() {
+ let wt = JsonWorkingTree {
+ staged: true,
+ modified: false,
+ untracked: true,
+ renamed: false,
+ deleted: false,
+ diff: Some(JsonDiff {
+ added: 10,
+ deleted: 5,
+ }),
+ diff_vs_main: None,
+ };
+ let json = serde_json::to_string(&wt).unwrap();
+ assert!(json.contains("\"staged\":true"));
+ assert!(json.contains("\"modified\":false"));
+ assert!(json.contains("\"added\":10"));
+ }
+
+ #[test]
+ fn test_json_main_serialization() {
+ let main = JsonMain {
+ ahead: 3,
+ behind: 1,
+ diff: Some(JsonDiff {
+ added: 50,
+ deleted: 20,
+ }),
+ };
+ let json = serde_json::to_string(&main).unwrap();
+ assert!(json.contains("\"ahead\":3"));
+ assert!(json.contains("\"behind\":1"));
+ }
+
+ #[test]
+ fn test_json_remote_serialization() {
+ let remote = JsonRemote {
+ name: "origin".to_string(),
+ branch: "feature".to_string(),
+ ahead: 2,
+ behind: 0,
+ };
+ let json = serde_json::to_string(&remote).unwrap();
+ assert!(json.contains("\"name\":\"origin\""));
+ assert!(json.contains("\"branch\":\"feature\""));
+ }
+
+ #[test]
+ fn test_json_worktree_serialization() {
+ let wt = JsonWorktree {
+ state: Some("locked"),
+ reason: Some("manual".to_string()),
+ detached: false,
+ bare: false,
+ };
+ let json = serde_json::to_string(&wt).unwrap();
+ assert!(json.contains("\"state\":\"locked\""));
+ assert!(json.contains("\"reason\":\"manual\""));
+ }
+
+ #[test]
+ fn test_json_pr_serialization() {
+ let pr = JsonPr {
+ ci: "passed",
+ source: "pull_request",
+ stale: false,
+ url: Some("https://example.com".to_string()),
+ };
+ let json = serde_json::to_string(&pr).unwrap();
+ assert!(json.contains("\"ci\":\"passed\""));
+ assert!(json.contains("\"source\":\"pull_request\""));
+ }
+}
diff --git a/src/commands/list/model.rs b/src/commands/list/model.rs
index 3b86554eb..1f9b17477 100644
--- a/src/commands/list/model.rs
+++ b/src/commands/list/model.rs
@@ -1548,4 +1548,429 @@ mod tests {
"Clean working tree should show as integrated"
);
}
+
+ // ============================================================================
+ // Divergence Tests
+ // ============================================================================
+
+ #[test]
+ fn test_divergence_from_counts_with_remote() {
+ assert_eq!(
+ Divergence::from_counts_with_remote(0, 0),
+ Divergence::InSync
+ );
+ assert_eq!(Divergence::from_counts_with_remote(5, 0), Divergence::Ahead);
+ assert_eq!(
+ Divergence::from_counts_with_remote(0, 3),
+ Divergence::Behind
+ );
+ assert_eq!(
+ Divergence::from_counts_with_remote(5, 3),
+ Divergence::Diverged
+ );
+ }
+
+ #[test]
+ fn test_divergence_symbol() {
+ assert_eq!(Divergence::None.symbol(DivergenceContext::Upstream), "");
+ assert_eq!(Divergence::InSync.symbol(DivergenceContext::Upstream), "|");
+ assert_eq!(Divergence::Ahead.symbol(DivergenceContext::Upstream), "⇡");
+ assert_eq!(Divergence::Behind.symbol(DivergenceContext::Upstream), "⇣");
+ assert_eq!(
+ Divergence::Diverged.symbol(DivergenceContext::Upstream),
+ "⇅"
+ );
+ }
+
+ #[test]
+ fn test_divergence_styled() {
+ // None returns None
+ assert!(
+ Divergence::None
+ .styled(DivergenceContext::Upstream)
+ .is_none()
+ );
+
+ // Other variants return styled strings
+ let styled = Divergence::InSync
+ .styled(DivergenceContext::Upstream)
+ .unwrap();
+ assert!(styled.contains("|"));
+
+ let styled = Divergence::Ahead
+ .styled(DivergenceContext::Upstream)
+ .unwrap();
+ assert!(styled.contains("⇡"));
+
+ let styled = Divergence::Behind
+ .styled(DivergenceContext::Upstream)
+ .unwrap();
+ assert!(styled.contains("⇣"));
+
+ let styled = Divergence::Diverged
+ .styled(DivergenceContext::Upstream)
+ .unwrap();
+ assert!(styled.contains("⇅"));
+ }
+
+ // ============================================================================
+ // WorktreeState Tests
+ // ============================================================================
+
+ #[test]
+ fn test_worktree_state_display() {
+ assert_eq!(format!("{}", WorktreeState::None), "");
+ assert_eq!(format!("{}", WorktreeState::PathMismatch), "⚑");
+ assert_eq!(format!("{}", WorktreeState::Prunable), "⊟");
+ assert_eq!(format!("{}", WorktreeState::Locked), "⊞");
+ assert_eq!(format!("{}", WorktreeState::Branch), "/");
+ }
+
+ #[test]
+ fn test_worktree_state_serialize() {
+ // Serialize to JSON and check the string representation
+ let json = serde_json::to_string(&WorktreeState::None).unwrap();
+ assert_eq!(json, "\"\"");
+
+ let json = serde_json::to_string(&WorktreeState::PathMismatch).unwrap();
+ assert_eq!(json, "\"⚑\"");
+
+ let json = serde_json::to_string(&WorktreeState::Branch).unwrap();
+ assert_eq!(json, "\"/\"");
+ }
+
+ // ============================================================================
+ // MainState Tests
+ // ============================================================================
+
+ #[test]
+ fn test_main_state_display() {
+ assert_eq!(format!("{}", MainState::None), "");
+ assert_eq!(format!("{}", MainState::IsMain), "^");
+ assert_eq!(format!("{}", MainState::WouldConflict), "✗");
+ assert_eq!(format!("{}", MainState::Empty), "_");
+ assert_eq!(format!("{}", MainState::SameCommit), "–"); // en-dash
+ assert_eq!(
+ format!("{}", MainState::Integrated(IntegrationReason::Ancestor)),
+ "⊂"
+ );
+ assert_eq!(format!("{}", MainState::Diverged), "↕");
+ assert_eq!(format!("{}", MainState::Ahead), "↑");
+ assert_eq!(format!("{}", MainState::Behind), "↓");
+ }
+
+ #[test]
+ fn test_main_state_styled() {
+ // None returns None
+ assert!(MainState::None.styled().is_none());
+
+ // WouldConflict is yellow
+ let styled = MainState::WouldConflict.styled().unwrap();
+ assert!(styled.contains("✗"));
+
+ // Other states are dimmed
+ let styled = MainState::IsMain.styled().unwrap();
+ assert!(styled.contains("^"));
+
+ let styled = MainState::Ahead.styled().unwrap();
+ assert!(styled.contains("↑"));
+ }
+
+ #[test]
+ fn test_main_state_serialize() {
+ let json = serde_json::to_string(&MainState::None).unwrap();
+ assert_eq!(json, "\"\"");
+
+ let json = serde_json::to_string(&MainState::IsMain).unwrap();
+ assert_eq!(json, "\"^\"");
+
+ let json = serde_json::to_string(&MainState::Diverged).unwrap();
+ assert_eq!(json, "\"↕\"");
+ }
+
+ // ============================================================================
+ // OperationState Tests
+ // ============================================================================
+
+ #[test]
+ fn test_operation_state_display() {
+ assert_eq!(format!("{}", OperationState::None), "");
+ assert_eq!(format!("{}", OperationState::Conflicts), "✘");
+ assert_eq!(format!("{}", OperationState::Rebase), "⤴");
+ assert_eq!(format!("{}", OperationState::Merge), "⤵");
+ }
+
+ #[test]
+ fn test_operation_state_styled() {
+ // None returns None
+ assert!(OperationState::None.styled().is_none());
+
+ // Conflicts is red
+ let styled = OperationState::Conflicts.styled().unwrap();
+ assert!(styled.contains("✘"));
+
+ // Rebase and Merge are yellow
+ let styled = OperationState::Rebase.styled().unwrap();
+ assert!(styled.contains("⤴"));
+
+ let styled = OperationState::Merge.styled().unwrap();
+ assert!(styled.contains("⤵"));
+ }
+
+ #[test]
+ fn test_operation_state_serialize() {
+ let json = serde_json::to_string(&OperationState::None).unwrap();
+ assert_eq!(json, "\"\"");
+
+ let json = serde_json::to_string(&OperationState::Conflicts).unwrap();
+ assert_eq!(json, "\"✘\"");
+ }
+
+ // ============================================================================
+ // StatusSymbols Tests
+ // ============================================================================
+
+ #[test]
+ fn test_status_symbols_is_empty() {
+ let symbols = StatusSymbols::default();
+ assert!(symbols.is_empty());
+
+ let symbols = StatusSymbols {
+ main_state: MainState::Ahead,
+ ..Default::default()
+ };
+ assert!(!symbols.is_empty());
+
+ let symbols = StatusSymbols {
+ operation_state: OperationState::Rebase,
+ ..Default::default()
+ };
+ assert!(!symbols.is_empty());
+
+ let symbols = StatusSymbols {
+ worktree_state: WorktreeState::Locked,
+ ..Default::default()
+ };
+ assert!(!symbols.is_empty());
+
+ let symbols = StatusSymbols {
+ upstream_divergence: Divergence::Ahead,
+ ..Default::default()
+ };
+ assert!(!symbols.is_empty());
+
+ let symbols = StatusSymbols {
+ working_tree: WorkingTreeStatus::new(true, false, false, false, false),
+ ..Default::default()
+ };
+ assert!(!symbols.is_empty());
+
+ let symbols = StatusSymbols {
+ user_marker: Some("🔥".to_string()),
+ ..Default::default()
+ };
+ assert!(!symbols.is_empty());
+ }
+
+ #[test]
+ fn test_status_symbols_format_compact() {
+ // Empty symbols
+ let symbols = StatusSymbols::default();
+ assert_eq!(symbols.format_compact(), "");
+
+ // Single symbol
+ let symbols = StatusSymbols {
+ main_state: MainState::Ahead,
+ ..Default::default()
+ };
+ let compact = symbols.format_compact();
+ assert!(compact.contains("↑"));
+
+ // Multiple symbols
+ let symbols = StatusSymbols {
+ working_tree: WorkingTreeStatus::new(true, true, false, false, false),
+ main_state: MainState::Ahead,
+ ..Default::default()
+ };
+ let compact = symbols.format_compact();
+ assert!(compact.contains("+"));
+ assert!(compact.contains("!"));
+ assert!(compact.contains("↑"));
+ }
+
+ #[test]
+ fn test_status_symbols_render_with_mask() {
+ let symbols = StatusSymbols {
+ main_state: MainState::Ahead,
+ ..Default::default()
+ };
+ let rendered = symbols.render_with_mask(&PositionMask::FULL);
+ // Should have fixed-width output with spacing
+ assert!(!rendered.is_empty());
+ assert!(rendered.contains("↑"));
+ }
+
+ // ============================================================================
+ // UpstreamStatus Tests
+ // ============================================================================
+
+ #[test]
+ fn test_upstream_status_active_with_remote() {
+ let status = UpstreamStatus::from_parts(Some("origin".to_string()), 3, 2);
+ let active = status.active().unwrap();
+ assert_eq!(active.remote, "origin");
+ assert_eq!(active.ahead, 3);
+ assert_eq!(active.behind, 2);
+ }
+
+ #[test]
+ fn test_upstream_status_active_no_remote() {
+ let status = UpstreamStatus::from_parts(None, 0, 0);
+ assert!(status.active().is_none());
+ }
+
+ // ============================================================================
+ // ListItem Tests
+ // ============================================================================
+
+ #[test]
+ fn test_list_item_branch_name() {
+ let item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
+ assert_eq!(item.branch_name(), "feature");
+
+ let mut item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
+ item.branch = None; // Simulate detached
+ assert_eq!(item.branch_name(), "(detached)");
+ }
+
+ #[test]
+ fn test_list_item_head() {
+ let item = ListItem::new_branch("abc123def".to_string(), "feature".to_string());
+ assert_eq!(item.head(), "abc123def");
+ }
+
+ #[test]
+ fn test_list_item_commit_details() {
+ let item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
+ let details = item.commit_details();
+ assert_eq!(details.timestamp, 0);
+ assert_eq!(details.commit_message, "");
+ }
+
+ #[test]
+ fn test_list_item_counts() {
+ let item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
+ let counts = item.counts();
+ assert_eq!(counts.ahead, 0);
+ assert_eq!(counts.behind, 0);
+
+ let mut item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
+ item.counts = Some(AheadBehind {
+ ahead: 5,
+ behind: 3,
+ });
+ let counts = item.counts();
+ assert_eq!(counts.ahead, 5);
+ assert_eq!(counts.behind, 3);
+ }
+
+ #[test]
+ fn test_list_item_branch_diff() {
+ let item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
+ let diff = item.branch_diff();
+ assert!(diff.diff.is_empty());
+ }
+
+ #[test]
+ fn test_list_item_upstream() {
+ let item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
+ let upstream = item.upstream();
+ assert!(upstream.remote.is_none());
+ }
+
+ #[test]
+ fn test_list_item_worktree_data() {
+ // Branch item has no worktree data
+ let item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
+ assert!(item.worktree_data().is_none());
+ assert!(item.worktree_path().is_none());
+ }
+
+ #[test]
+ fn test_list_item_should_dim() {
+ // No status_symbols = should NOT dim (data still loading)
+ let item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
+ assert!(!item.should_dim());
+ }
+
+ // ============================================================================
+ // PositionMask Tests
+ // ============================================================================
+
+ #[test]
+ fn test_position_mask_width() {
+ let mask = PositionMask::FULL;
+ // Check expected widths for each position
+ assert_eq!(mask.width(PositionMask::STAGED), 1);
+ assert_eq!(mask.width(PositionMask::MODIFIED), 1);
+ assert_eq!(mask.width(PositionMask::UNTRACKED), 1);
+ assert_eq!(mask.width(PositionMask::WORKTREE_STATE), 1);
+ assert_eq!(mask.width(PositionMask::MAIN_STATE), 1);
+ assert_eq!(mask.width(PositionMask::UPSTREAM_DIVERGENCE), 1);
+ assert_eq!(mask.width(PositionMask::USER_MARKER), 2);
+ }
+
+ #[test]
+ fn test_position_mask_default() {
+ let mask = PositionMask::default();
+ // Default has all widths at 0
+ for i in 0..7 {
+ assert_eq!(mask.width(i), 0);
+ }
+ }
+
+ // ============================================================================
+ // GitOperationState Tests
+ // ============================================================================
+
+ #[test]
+ fn test_git_operation_state_default() {
+ let state = GitOperationState::default();
+ assert_eq!(state, GitOperationState::None);
+ }
+
+ #[test]
+ fn test_git_operation_is_none() {
+ assert!(git_operation_is_none(&GitOperationState::None));
+ assert!(!git_operation_is_none(&GitOperationState::Rebase));
+ assert!(!git_operation_is_none(&GitOperationState::Merge));
+ }
+
+ // ============================================================================
+ // AheadBehind and BranchDiffTotals Tests
+ // ============================================================================
+
+ #[test]
+ fn test_ahead_behind_default() {
+ let ab = AheadBehind::default();
+ assert_eq!(ab.ahead, 0);
+ assert_eq!(ab.behind, 0);
+ }
+
+ #[test]
+ fn test_branch_diff_totals_default() {
+ let diff = BranchDiffTotals::default();
+ assert!(diff.diff.is_empty());
+ }
+
+ // ============================================================================
+ // CommitDetails Tests
+ // ============================================================================
+
+ #[test]
+ fn test_commit_details_default() {
+ let details = CommitDetails::default();
+ assert_eq!(details.timestamp, 0);
+ assert_eq!(details.commit_message, "");
+ }
}
diff --git a/src/config/commands.rs b/src/config/commands.rs
index 94feb79e7..260cea694 100644
--- a/src/config/commands.rs
+++ b/src/config/commands.rs
@@ -139,3 +139,290 @@ impl Serialize for CommandConfig {
map.end()
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // ============================================================================
+ // Command Tests
+ // ============================================================================
+
+ #[test]
+ fn test_command_new() {
+ let cmd = Command::new(
+ Some("build".to_string()),
+ "cargo build".to_string(),
+ HookType::PreMerge,
+ );
+ assert_eq!(cmd.name, Some("build".to_string()));
+ assert_eq!(cmd.template, "cargo build");
+ assert_eq!(cmd.expanded, "cargo build"); // Same as template when not expanded
+ assert_eq!(cmd.phase, HookType::PreMerge);
+ }
+
+ #[test]
+ fn test_command_new_unnamed() {
+ let cmd = Command::new(None, "npm install".to_string(), HookType::PostCreate);
+ assert_eq!(cmd.name, None);
+ assert_eq!(cmd.template, "npm install");
+ assert_eq!(cmd.expanded, "npm install");
+ assert_eq!(cmd.phase, HookType::PostCreate);
+ }
+
+ #[test]
+ fn test_command_with_expansion() {
+ let cmd = Command::with_expansion(
+ Some("test".to_string()),
+ "cargo test --package {{ repo }}".to_string(),
+ "cargo test --package myrepo".to_string(),
+ HookType::PreMerge,
+ );
+ assert_eq!(cmd.name, Some("test".to_string()));
+ assert_eq!(cmd.template, "cargo test --package {{ repo }}");
+ assert_eq!(cmd.expanded, "cargo test --package myrepo");
+ assert_eq!(cmd.phase, HookType::PreMerge);
+ }
+
+ #[test]
+ fn test_command_clone() {
+ let cmd = Command::new(
+ Some("build".to_string()),
+ "make".to_string(),
+ HookType::PreMerge,
+ );
+ let cloned = cmd.clone();
+ assert_eq!(cmd, cloned);
+ }
+
+ // ============================================================================
+ // CommandConfig Deserialization Tests
+ // ============================================================================
+
+ #[test]
+ fn test_deserialize_single_string() {
+ let toml_str = r#"command = "npm install""#;
+
+ #[derive(Deserialize)]
+ struct Wrapper {
+ command: CommandConfig,
+ }
+
+ let wrapper: Wrapper = toml::from_str(toml_str).unwrap();
+ let commands = wrapper.command.commands();
+ assert_eq!(commands.len(), 1);
+ assert_eq!(commands[0].name, None);
+ assert_eq!(commands[0].template, "npm install");
+ }
+
+ #[test]
+ fn test_deserialize_named_table() {
+ let toml_str = r#"
+[command]
+build = "cargo build"
+test = "cargo test"
+"#;
+
+ #[derive(Deserialize)]
+ struct Wrapper {
+ command: CommandConfig,
+ }
+
+ let wrapper: Wrapper = toml::from_str(toml_str).unwrap();
+ let commands = wrapper.command.commands();
+ assert_eq!(commands.len(), 2);
+ assert!(commands.iter().any(|c| c.name == Some("build".to_string())));
+ assert!(commands.iter().any(|c| c.name == Some("test".to_string())));
+ }
+
+ #[test]
+ fn test_deserialize_preserves_order() {
+ // Order should match TOML insertion order
+ let toml_str = r#"
+[command]
+first = "echo 1"
+second = "echo 2"
+third = "echo 3"
+"#;
+
+ #[derive(Deserialize)]
+ struct Wrapper {
+ command: CommandConfig,
+ }
+
+ let wrapper: Wrapper = toml::from_str(toml_str).unwrap();
+ let commands = wrapper.command.commands();
+ assert_eq!(commands.len(), 3);
+ // IndexMap preserves insertion order
+ assert_eq!(commands[0].name, Some("first".to_string()));
+ assert_eq!(commands[1].name, Some("second".to_string()));
+ assert_eq!(commands[2].name, Some("third".to_string()));
+ }
+
+ // ============================================================================
+ // CommandConfig Serialization Tests
+ // ============================================================================
+
+ #[test]
+ fn test_serialize_single_unnamed() {
+ // A single unnamed command should serialize as a string (when wrapped in a struct)
+ #[derive(Serialize)]
+ struct Wrapper {
+ cmd: CommandConfig,
+ }
+
+ let wrapper = Wrapper {
+ cmd: CommandConfig {
+ commands: vec![Command::new(
+ None,
+ "npm install".to_string(),
+ HookType::PostCreate,
+ )],
+ },
+ };
+
+ let serialized = toml::to_string(&wrapper).unwrap();
+ assert!(serialized.contains("cmd = \"npm install\""));
+ }
+
+ #[test]
+ fn test_serialize_named_commands() {
+ // Multiple named commands should serialize as a table
+ #[derive(Serialize)]
+ struct Wrapper {
+ cmd: CommandConfig,
+ }
+
+ let wrapper = Wrapper {
+ cmd: CommandConfig {
+ commands: vec![
+ Command::new(
+ Some("build".to_string()),
+ "cargo build".to_string(),
+ HookType::PostCreate,
+ ),
+ Command::new(
+ Some("test".to_string()),
+ "cargo test".to_string(),
+ HookType::PostCreate,
+ ),
+ ],
+ },
+ };
+
+ let serialized = toml::to_string(&wrapper).unwrap();
+ assert!(serialized.contains("build"));
+ assert!(serialized.contains("cargo build"));
+ assert!(serialized.contains("test"));
+ assert!(serialized.contains("cargo test"));
+ }
+
+ #[test]
+ fn test_serialize_deserialize_roundtrip_single() {
+ let config = CommandConfig {
+ commands: vec![Command::new(
+ None,
+ "echo hello".to_string(),
+ HookType::PostCreate,
+ )],
+ };
+
+ #[derive(Serialize, Deserialize)]
+ struct Wrapper {
+ cmd: CommandConfig,
+ }
+
+ let wrapper = Wrapper { cmd: config };
+ let serialized = toml::to_string(&wrapper).unwrap();
+ let deserialized: Wrapper = toml::from_str(&serialized).unwrap();
+
+ assert_eq!(deserialized.cmd.commands().len(), 1);
+ assert_eq!(deserialized.cmd.commands()[0].template, "echo hello");
+ }
+
+ #[test]
+ fn test_serialize_deserialize_roundtrip_named() {
+ let config = CommandConfig {
+ commands: vec![
+ Command::new(
+ Some("a".to_string()),
+ "echo a".to_string(),
+ HookType::PostCreate,
+ ),
+ Command::new(
+ Some("b".to_string()),
+ "echo b".to_string(),
+ HookType::PostCreate,
+ ),
+ ],
+ };
+
+ #[derive(Serialize, Deserialize)]
+ struct Wrapper {
+ cmd: CommandConfig,
+ }
+
+ let wrapper = Wrapper { cmd: config };
+ let serialized = toml::to_string(&wrapper).unwrap();
+ let deserialized: Wrapper = toml::from_str(&serialized).unwrap();
+
+ assert_eq!(deserialized.cmd.commands().len(), 2);
+ }
+
+ // ============================================================================
+ // CommandConfig Methods Tests
+ // ============================================================================
+
+ #[test]
+ fn test_commands_returns_slice() {
+ let config = CommandConfig {
+ commands: vec![
+ Command::new(None, "cmd1".to_string(), HookType::PostCreate),
+ Command::new(None, "cmd2".to_string(), HookType::PostCreate),
+ ],
+ };
+
+ let cmds = config.commands();
+ assert_eq!(cmds.len(), 2);
+ assert_eq!(cmds[0].template, "cmd1");
+ assert_eq!(cmds[1].template, "cmd2");
+ }
+
+ #[test]
+ fn test_commands_with_phase() {
+ let config = CommandConfig {
+ commands: vec![
+ Command::new(
+ Some("build".to_string()),
+ "cargo build".to_string(),
+ HookType::PostCreate,
+ ),
+ Command::new(
+ Some("test".to_string()),
+ "cargo test".to_string(),
+ HookType::PostCreate,
+ ),
+ ],
+ };
+
+ let cmds = config.commands_with_phase(HookType::PreMerge);
+
+ // All returned commands should have the new phase
+ assert_eq!(cmds.len(), 2);
+ assert!(cmds.iter().all(|c| c.phase == HookType::PreMerge));
+ // But templates and names should be preserved
+ assert_eq!(cmds[0].name, Some("build".to_string()));
+ assert_eq!(cmds[0].template, "cargo build");
+ }
+
+ #[test]
+ fn test_command_config_equality() {
+ let config1 = CommandConfig {
+ commands: vec![Command::new(None, "test".to_string(), HookType::PostCreate)],
+ };
+ let config2 = CommandConfig {
+ commands: vec![Command::new(None, "test".to_string(), HookType::PostCreate)],
+ };
+ assert_eq!(config1, config2);
+ }
+}
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 088a87806..524192c76 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -88,3 +88,126 @@ pub fn expand_template(
tmpl.render(minijinja::Value::from_object(context))
.map_err(|e| format!("Template render error: {}", e))
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_sanitize_branch_name() {
+ let cases = [
+ ("feature/foo", "feature-foo"),
+ ("user\\task", "user-task"),
+ ("feature/user/task", "feature-user-task"),
+ ("feature/user\\task", "feature-user-task"),
+ ("simple-branch", "simple-branch"),
+ ("", ""),
+ ("///", "---"),
+ ("/feature", "-feature"),
+ ("feature/", "feature-"),
+ ];
+ for (input, expected) in cases {
+ assert_eq!(sanitize_branch_name(input), expected, "input: {input}");
+ }
+ }
+
+ #[test]
+ fn test_expand_template_basic() {
+ // Single variable
+ let mut vars = HashMap::new();
+ vars.insert("name", "world");
+ assert_eq!(
+ expand_template("Hello {{ name }}", &vars, false).unwrap(),
+ "Hello world"
+ );
+
+ // Multiple variables
+ vars.insert("repo", "myrepo");
+ assert_eq!(
+ expand_template("{{ repo }}/{{ name }}", &vars, false).unwrap(),
+ "myrepo/world"
+ );
+
+ // Empty/static cases
+ let empty: HashMap<&str, &str> = HashMap::new();
+ assert_eq!(expand_template("", &empty, false).unwrap(), "");
+ assert_eq!(
+ expand_template("static text", &empty, false).unwrap(),
+ "static text"
+ );
+ assert_eq!(
+ expand_template("no {{ variables }} here", &empty, false).unwrap(),
+ "no here"
+ );
+ }
+
+ #[test]
+ fn test_expand_template_shell_escape() {
+ let mut vars = HashMap::new();
+ vars.insert("path", "my path");
+ let expanded = expand_template("cd {{ path }}", &vars, true).unwrap();
+ assert!(expanded.contains("'my path'") || expanded.contains("my\\ path"));
+
+ // Command injection prevention
+ vars.insert("arg", "test;rm -rf");
+ let expanded = expand_template("echo {{ arg }}", &vars, true).unwrap();
+ assert!(!expanded.contains(";rm") || expanded.contains("'"));
+
+ // No escape for literal mode
+ vars.insert("branch", "feature/foo");
+ assert_eq!(
+ expand_template("{{ branch }}", &vars, false).unwrap(),
+ "feature/foo"
+ );
+ }
+
+ #[test]
+ fn test_expand_template_errors() {
+ let vars = HashMap::new();
+ assert!(
+ expand_template("{{ unclosed", &vars, false)
+ .unwrap_err()
+ .contains("syntax error")
+ );
+ assert!(expand_template("{{ 1 + }}", &vars, false).is_err());
+ }
+
+ #[test]
+ fn test_expand_template_jinja_features() {
+ let mut vars = HashMap::new();
+ vars.insert("debug", "true");
+ assert_eq!(
+ expand_template("{% if debug %}DEBUG{% endif %}", &vars, false).unwrap(),
+ "DEBUG"
+ );
+
+ vars.insert("debug", "");
+ assert_eq!(
+ expand_template("{% if debug %}DEBUG{% endif %}", &vars, false).unwrap(),
+ ""
+ );
+
+ let empty: HashMap<&str, &str> = HashMap::new();
+ assert_eq!(
+ expand_template("{{ missing | default('fallback') }}", &empty, false).unwrap(),
+ "fallback"
+ );
+
+ vars.insert("name", "hello");
+ assert_eq!(
+ expand_template("{{ name | upper }}", &vars, false).unwrap(),
+ "HELLO"
+ );
+ }
+
+ #[test]
+ fn test_expand_template_trailing_newline() {
+ let mut vars = HashMap::new();
+ vars.insert("cmd", "echo hello");
+ assert!(
+ expand_template("{{ cmd }}\n", &vars, true)
+ .unwrap()
+ .ends_with('\n')
+ );
+ }
+}
diff --git a/src/config/project.rs b/src/config/project.rs
index 6e8100f5c..fa8f03e9b 100644
--- a/src/config/project.rs
+++ b/src/config/project.rs
@@ -115,3 +115,180 @@ pub fn find_unknown_keys(contents: &str) -> Vec<String> {
config.unknown.into_keys().collect()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // ============================================================================
+ // ProjectConfig Default Tests
+ // ============================================================================
+
+ #[test]
+ fn test_project_config_default() {
+ let config = ProjectConfig::default();
+ assert!(config.post_create.is_none());
+ assert!(config.post_start.is_none());
+ assert!(config.pre_commit.is_none());
+ assert!(config.pre_merge.is_none());
+ assert!(config.post_merge.is_none());
+ assert!(config.pre_remove.is_none());
+ }
+
+ // ============================================================================
+ // Deserialization Tests
+ // ============================================================================
+
+ #[test]
+ fn test_deserialize_empty_config() {
+ let contents = "";
+ let config: ProjectConfig = toml::from_str(contents).unwrap();
+ assert!(config.post_create.is_none());
+ assert!(config.pre_merge.is_none());
+ }
+
+ #[test]
+ fn test_deserialize_post_create_string() {
+ let contents = r#"post-create = "npm install""#;
+ let config: ProjectConfig = toml::from_str(contents).unwrap();
+ assert!(config.post_create.is_some());
+ }
+
+ #[test]
+ fn test_deserialize_post_start_table() {
+ let contents = r#"
+[post-start]
+build = "cargo build"
+test = "cargo test"
+"#;
+ let config: ProjectConfig = toml::from_str(contents).unwrap();
+ assert!(config.post_start.is_some());
+ }
+
+ #[test]
+ fn test_deserialize_pre_merge() {
+ let contents = r#"pre-merge = "cargo test""#;
+ let config: ProjectConfig = toml::from_str(contents).unwrap();
+ assert!(config.pre_merge.is_some());
+ }
+
+ #[test]
+ fn test_deserialize_post_merge() {
+ let contents = r#"post-merge = "git push origin main""#;
+ let config: ProjectConfig = toml::from_str(contents).unwrap();
+ assert!(config.post_merge.is_some());
+ }
+
+ #[test]
+ fn test_deserialize_pre_remove() {
+ let contents = r#"pre-remove = "echo cleaning up""#;
+ let config: ProjectConfig = toml::from_str(contents).unwrap();
+ assert!(config.pre_remove.is_some());
+ }
+
+ #[test]
+ fn test_deserialize_pre_commit() {
+ let contents = r#"pre-commit = "cargo fmt --check""#;
+ let config: ProjectConfig = toml::from_str(contents).unwrap();
+ assert!(config.pre_commit.is_some());
+ }
+
+ #[test]
+ fn test_deserialize_all_hooks() {
+ let contents = r#"
+post-create = "npm install"
+post-start = "npm run watch"
+pre-commit = "cargo fmt --check"
+pre-merge = "cargo test"
+post-merge = "git push"
+pre-remove = "echo bye"
+"#;
+ let config: ProjectConfig = toml::from_str(contents).unwrap();
+ assert!(config.post_create.is_some());
+ assert!(config.post_start.is_some());
+ assert!(config.pre_commit.is_some());
+ assert!(config.pre_merge.is_some());
+ assert!(config.post_merge.is_some());
+ assert!(config.pre_remove.is_some());
+ }
+
+ // ============================================================================
+ // find_unknown_keys Tests
+ // ============================================================================
+
+ #[test]
+ fn test_find_unknown_keys_empty() {
+ let contents = "";
+ let keys = find_unknown_keys(contents);
+ assert!(keys.is_empty());
+ }
+
+ #[test]
+ fn test_find_unknown_keys_all_known() {
+ let contents = r#"
+post-create = "npm install"
+pre-merge = "cargo test"
+"#;
+ let keys = find_unknown_keys(contents);
+ assert!(keys.is_empty());
+ }
+
+ #[test]
+ fn test_find_unknown_keys_unknown_key() {
+ let contents = r#"
+post-create = "npm install"
+unknown-key = "value"
+"#;
+ let keys = find_unknown_keys(contents);
+ assert_eq!(keys.len(), 1);
+ assert!(keys.contains(&"unknown-key".to_string()));
+ }
+
+ #[test]
+ fn test_find_unknown_keys_multiple_unknown() {
+ let contents = r#"
+foo = "bar"
+baz = "qux"
+post-create = "npm install"
+"#;
+ let keys = find_unknown_keys(contents);
+ assert_eq!(keys.len(), 2);
+ assert!(keys.contains(&"foo".to_string()));
+ assert!(keys.contains(&"baz".to_string()));
+ }
+
+ #[test]
+ fn test_find_unknown_keys_invalid_toml() {
+ let contents = "invalid { toml }}}";
+ let keys = find_unknown_keys(contents);
+ // Returns empty vec for invalid TOML (graceful fallback)
+ assert!(keys.is_empty());
+ }
+
+ // ============================================================================
+ // Serialization Tests
+ // ============================================================================
+
+ #[test]
+ fn test_serialize_empty_config() {
+ let config = ProjectConfig::default();
+ let serialized = toml::to_string(&config).unwrap();
+ // Default config should serialize to empty or minimal string
+ assert!(serialized.is_empty() || serialized.trim().is_empty());
+ }
+
+ #[test]
+ fn test_config_equality() {
+ let config1 = ProjectConfig::default();
+ let config2 = ProjectConfig::default();
+ assert_eq!(config1, config2);
+ }
+
+ #[test]
+ fn test_config_clone() {
+ let contents = r#"pre-merge = "cargo test""#;
+ let config: ProjectConfig = toml::from_str(contents).unwrap();
+ let cloned = config.clone();
+ assert_eq!(config, cloned);
+ }
+}
diff --git a/src/config/user.rs b/src/config/user.rs
index 1987e57a1..8f668b12e 100644
--- a/src/config/user.rs
+++ b/src/config/user.rs
@@ -745,3 +745,247 @@ pub fn find_unknown_keys(contents: &str) -> Vec<String> {
config.unknown.into_keys().collect()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_find_unknown_keys_empty() {
+ // Valid config with no unknown keys
+ let content = r#"
+worktree-path = "../{{ main_worktree }}.{{ branch }}"
+"#;
+ let keys = find_unknown_keys(content);
+ assert!(keys.is_empty());
+ }
+
+ #[test]
+ fn test_find_unknown_keys_with_unknown() {
+ // Config with unknown top-level keys
+ let content = r#"
+worktree-path = "../{{ main_worktree }}.{{ branch }}"
+unknown-key = "value"
+another-unknown = 42
+"#;
+ let keys = find_unknown_keys(content);
+ assert!(keys.contains(&"unknown-key".to_string()));
+ assert!(keys.contains(&"another-unknown".to_string()));
+ }
+
+ #[test]
+ fn test_find_unknown_keys_invalid_toml() {
+ // Invalid TOML should return empty
+ let content = "this is not valid toml {{{";
+ let keys = find_unknown_keys(content);
+ assert!(keys.is_empty());
+ }
+
+ #[test]
+ fn test_find_unknown_keys_known_sections() {
+ // All known sections should not be reported
+ let content = r#"
+worktree-path = "../{{ main_worktree }}.{{ branch }}"
+
+[commit-generation]
+command = "llm"
+
+[list]
+full = true
+
+[commit]
+stage = "all"
+
+[merge]
+squash = true
+
+[post-create]
+run = "npm install"
+
+[post-start]
+run = "npm run build"
+"#;
+ let keys = find_unknown_keys(content);
+ assert!(keys.is_empty());
+ }
+
+ #[test]
+ fn test_commit_generation_config_is_configured_empty() {
+ let config = CommitGenerationConfig::default();
+ assert!(!config.is_configured());
+ }
+
+ #[test]
+ fn test_commit_generation_config_is_configured_with_command() {
+ let config = CommitGenerationConfig {
+ command: Some("llm".to_string()),
+ ..Default::default()
+ };
+ assert!(config.is_configured());
+ }
+
+ #[test]
+ fn test_commit_generation_config_is_configured_with_whitespace_only() {
+ let config = CommitGenerationConfig {
+ command: Some(" ".to_string()),
+ ..Default::default()
+ };
+ assert!(!config.is_configured());
+ }
+
+ #[test]
+ fn test_commit_generation_config_is_configured_with_empty_string() {
+ let config = CommitGenerationConfig {
+ command: Some("".to_string()),
+ ..Default::default()
+ };
+ assert!(!config.is_configured());
+ }
+
+ #[test]
+ fn test_stage_mode_default() {
+ assert_eq!(StageMode::default(), StageMode::All);
+ }
+
+ #[test]
+ fn test_stage_mode_serde() {
+ // Test serialization
+ let all_json = serde_json::to_string(&StageMode::All).unwrap();
+ assert_eq!(all_json, "\"all\"");
+
+ let tracked_json = serde_json::to_string(&StageMode::Tracked).unwrap();
+ assert_eq!(tracked_json, "\"tracked\"");
+
+ let none_json = serde_json::to_string(&StageMode::None).unwrap();
+ assert_eq!(none_json, "\"none\"");
+
+ // Test deserialization
+ let all: StageMode = serde_json::from_str("\"all\"").unwrap();
+ assert_eq!(all, StageMode::All);
+
+ let tracked: StageMode = serde_json::from_str("\"tracked\"").unwrap();
+ assert_eq!(tracked, StageMode::Tracked);
+
+ let none: StageMode = serde_json::from_str("\"none\"").unwrap();
+ assert_eq!(none, StageMode::None);
+ }
+
+ #[test]
+ fn test_user_project_config_default() {
+ let config = UserProjectConfig::default();
+ assert!(config.approved_commands.is_empty());
+ }
+
+ #[test]
+ fn test_list_config_serde() {
+ let config = ListConfig {
+ full: Some(true),
+ branches: Some(false),
+ remotes: None,
+ };
+ let json = serde_json::to_string(&config).unwrap();
+ let parsed: ListConfig = serde_json::from_str(&json).unwrap();
+ assert_eq!(parsed.full, Some(true));
+ assert_eq!(parsed.branches, Some(false));
+ assert_eq!(parsed.remotes, None);
+ }
+
+ #[test]
+ fn test_commit_config_default() {
+ let config = CommitConfig::default();
+ assert!(config.stage.is_none());
+ }
+
+ #[test]
+ fn test_worktrunk_config_default() {
+ let config = WorktrunkConfig::default();
+ assert_eq!(config.worktree_path, "../{{ main_worktree }}.{{ branch }}");
+ assert!(config.projects.is_empty());
+ assert!(config.list.is_none());
+ assert!(config.commit.is_none());
+ assert!(config.merge.is_none());
+ assert!(!config.commit_generation.is_configured());
+ }
+
+ #[test]
+ fn test_worktrunk_config_is_command_approved_empty() {
+ let config = WorktrunkConfig::default();
+ assert!(!config.is_command_approved("some/project", "npm install"));
+ }
+
+ #[test]
+ fn test_worktrunk_config_is_command_approved_with_commands() {
+ let mut config = WorktrunkConfig::default();
+ config.projects.insert(
+ "github.com/user/repo".to_string(),
+ UserProjectConfig {
+ approved_commands: vec!["npm install".to_string(), "npm test".to_string()],
+ },
+ );
+ assert!(config.is_command_approved("github.com/user/repo", "npm install"));
+ assert!(config.is_command_approved("github.com/user/repo", "npm test"));
+ assert!(!config.is_command_approved("github.com/user/repo", "rm -rf /"));
+ assert!(!config.is_command_approved("other/project", "npm install"));
+ }
+
+ #[test]
+ fn test_worktrunk_config_format_path() {
+ let config = WorktrunkConfig::default();
+ let path = config.format_path("myrepo", "feature/branch").unwrap();
+ assert_eq!(path, "../myrepo.feature-branch");
+ }
+
+ #[test]
+ fn test_worktrunk_config_format_path_custom_template() {
+ let config = WorktrunkConfig {
+ worktree_path: ".worktrees/{{ branch }}".to_string(),
+ ..Default::default()
+ };
+ let path = config.format_path("myrepo", "feature").unwrap();
+ assert_eq!(path, ".worktrees/feature");
+ }
+
+ #[test]
+ fn test_deserialize_string_or_vec_from_string() {
+ #[derive(serde::Deserialize)]
+ struct Test {
+ #[serde(deserialize_with = "deserialize_string_or_vec")]
+ args: Vec<String>,
+ }
+
+ let json = r#"{"args": "single"}"#;
+ let parsed: Test = serde_json::from_str(json).unwrap();
+ assert_eq!(parsed.args, vec!["single".to_string()]);
+ }
+
+ #[test]
+ fn test_deserialize_string_or_vec_from_array() {
+ #[derive(serde::Deserialize)]
+ struct Test {
+ #[serde(deserialize_with = "deserialize_string_or_vec")]
+ args: Vec<String>,
+ }
+
+ let json = r#"{"args": ["one", "two", "three"]}"#;
+ let parsed: Test = serde_json::from_str(json).unwrap();
+ assert_eq!(
+ parsed.args,
+ vec!["one".to_string(), "two".to_string(), "three".to_string()]
+ );
+ }
+
+ #[test]
+ fn test_merge_config_serde() {
+ let config = MergeConfig {
+ squash: Some(true),
+ commit: Some(true),
+ rebase: Some(false),
+ remove: Some(true),
+ verify: Some(true),
+ };
+ let json = serde_json::to_string(&config).unwrap();
+ let parsed: MergeConfig = serde_json::from_str(&json).unwrap();
+ assert_eq!(parsed.squash, Some(true));
+ assert_eq!(parsed.rebase, Some(false));
+ }
+}
diff --git a/src/git/diff.rs b/src/git/diff.rs
index 3872454d1..b124e3a96 100644
--- a/src/git/diff.rs
+++ b/src/git/diff.rs
@@ -132,3 +132,261 @@ impl DiffStats {
parts
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // ============================================================================
+ // LineDiff Tests
+ // ============================================================================
+
+ #[test]
+ fn test_line_diff_default() {
+ let diff = LineDiff::default();
+ assert_eq!(diff.added, 0);
+ assert_eq!(diff.deleted, 0);
+ }
+
+ #[test]
+ fn test_line_diff_is_empty_true() {
+ let diff = LineDiff {
+ added: 0,
+ deleted: 0,
+ };
+ assert!(diff.is_empty());
+ }
+
+ #[test]
+ fn test_line_diff_is_empty_false_added() {
+ let diff = LineDiff {
+ added: 5,
+ deleted: 0,
+ };
+ assert!(!diff.is_empty());
+ }
+
+ #[test]
+ fn test_line_diff_is_empty_false_deleted() {
+ let diff = LineDiff {
+ added: 0,
+ deleted: 5,
+ };
+ assert!(!diff.is_empty());
+ }
+
+ #[test]
+ fn test_line_diff_into_tuple() {
+ let diff = LineDiff {
+ added: 10,
+ deleted: 5,
+ };
+ assert_eq!(diff.into_tuple(), (10, 5));
+ }
+
+ #[test]
+ fn test_line_diff_from_tuple() {
+ let diff: LineDiff = (10, 5).into();
+ assert_eq!(diff.added, 10);
+ assert_eq!(diff.deleted, 5);
+ }
+
+ #[test]
+ fn test_tuple_from_line_diff() {
+ let diff = LineDiff {
+ added: 10,
+ deleted: 5,
+ };
+ let tuple: (usize, usize) = diff.into();
+ assert_eq!(tuple, (10, 5));
+ }
+
+ #[test]
+ fn test_line_diff_from_numstat_empty() {
+ let result = LineDiff::from_numstat("").unwrap();
+ assert!(result.is_empty());
+ }
+
+ #[test]
+ fn test_line_diff_from_numstat_single_file() {
+ let output = "10\t5\tsrc/main.rs";
+ let result = LineDiff::from_numstat(output).unwrap();
+ assert_eq!(result.added, 10);
+ assert_eq!(result.deleted, 5);
+ }
+
+ #[test]
+ fn test_line_diff_from_numstat_multiple_files() {
+ let output = "10\t5\tsrc/main.rs\n20\t3\tsrc/lib.rs\n1\t0\tCargo.toml";
+ let result = LineDiff::from_numstat(output).unwrap();
+ assert_eq!(result.added, 31); // 10 + 20 + 1
+ assert_eq!(result.deleted, 8); // 5 + 3 + 0
+ }
+
+ #[test]
+ fn test_line_diff_from_numstat_binary_file() {
+ // Binary files show "-" for added/deleted
+ let output = "-\t-\timage.png";
+ let result = LineDiff::from_numstat(output).unwrap();
+ assert!(result.is_empty());
+ }
+
+ #[test]
+ fn test_line_diff_from_numstat_mixed_binary_and_text() {
+ let output = "10\t5\tsrc/main.rs\n-\t-\timage.png\n3\t2\tREADME.md";
+ let result = LineDiff::from_numstat(output).unwrap();
+ assert_eq!(result.added, 13); // 10 + 3, skips binary
+ assert_eq!(result.deleted, 7); // 5 + 2, skips binary
+ }
+
+ #[test]
+ fn test_line_diff_from_numstat_empty_lines() {
+ let output = "\n10\t5\tsrc/main.rs\n\n";
+ let result = LineDiff::from_numstat(output).unwrap();
+ assert_eq!(result.added, 10);
+ assert_eq!(result.deleted, 5);
+ }
+
+ #[test]
+ fn test_line_diff_from_numstat_malformed_line_missing_deleted() {
+ // Line with only added count (missing tab and deleted)
+ let output = "10";
+ let result = LineDiff::from_numstat(output).unwrap();
+ assert!(result.is_empty()); // Should skip malformed line
+ }
+
+ #[test]
+ fn test_line_diff_from_numstat_non_numeric_added() {
+ let output = "abc\t5\tsrc/main.rs";
+ let result = LineDiff::from_numstat(output).unwrap();
+ assert!(result.is_empty()); // Should skip non-numeric
+ }
+
+ #[test]
+ fn test_line_diff_from_numstat_non_numeric_deleted() {
+ let output = "10\tabc\tsrc/main.rs";
+ let result = LineDiff::from_numstat(output).unwrap();
+ assert!(result.is_empty()); // Should skip non-numeric
+ }
+
+ // ============================================================================
+ // DiffStats Tests
+ // ============================================================================
+
+ #[test]
+ fn test_diff_stats_from_shortstat_empty() {
+ let stats = DiffStats::from_shortstat("");
+ assert!(stats.files.is_none());
+ assert!(stats.insertions.is_none());
+ assert!(stats.deletions.is_none());
+ }
+
+ #[test]
+ fn test_diff_stats_from_shortstat_full() {
+ let output = " 3 files changed, 45 insertions(+), 12 deletions(-)";
+ let stats = DiffStats::from_shortstat(output);
+ assert_eq!(stats.files, Some(3));
+ assert_eq!(stats.insertions, Some(45));
+ assert_eq!(stats.deletions, Some(12));
+ }
+
+ #[test]
+ fn test_diff_stats_from_shortstat_single_file() {
+ let output = " 1 file changed, 10 insertions(+)";
+ let stats = DiffStats::from_shortstat(output);
+ assert_eq!(stats.files, Some(1));
+ assert_eq!(stats.insertions, Some(10));
+ assert!(stats.deletions.is_none());
+ }
+
+ #[test]
+ fn test_diff_stats_from_shortstat_only_deletions() {
+ let output = " 2 files changed, 5 deletions(-)";
+ let stats = DiffStats::from_shortstat(output);
+ assert_eq!(stats.files, Some(2));
+ assert!(stats.insertions.is_none());
+ assert_eq!(stats.deletions, Some(5));
+ }
+
+ #[test]
+ fn test_diff_stats_from_shortstat_no_changes() {
+ // Output when comparing identical trees
+ let output = "";
+ let stats = DiffStats::from_shortstat(output);
+ assert!(stats.files.is_none());
+ }
+
+ #[test]
+ fn test_diff_stats_format_summary_empty() {
+ let stats = DiffStats {
+ files: None,
+ insertions: None,
+ deletions: None,
+ };
+ let summary = stats.format_summary();
+ assert!(summary.is_empty());
+ }
+
+ #[test]
+ fn test_diff_stats_format_summary_all_parts() {
+ let stats = DiffStats {
+ files: Some(3),
+ insertions: Some(45),
+ deletions: Some(12),
+ };
+ let summary = stats.format_summary();
+ assert_eq!(summary.len(), 3);
+ assert_eq!(summary[0], "3 files");
+ assert!(summary[1].contains("45")); // Has color codes
+ assert!(summary[2].contains("12")); // Has color codes
+ }
+
+ #[test]
+ fn test_diff_stats_format_summary_single_file() {
+ let stats = DiffStats {
+ files: Some(1),
+ insertions: Some(10),
+ deletions: None,
+ };
+ let summary = stats.format_summary();
+ assert_eq!(summary.len(), 2);
+ assert_eq!(summary[0], "1 file"); // Singular
+ assert!(summary[1].contains("10"));
+ }
+
+ #[test]
+ fn test_diff_stats_format_summary_only_files() {
+ let stats = DiffStats {
+ files: Some(5),
+ insertions: None,
+ deletions: None,
+ };
+ let summary = stats.format_summary();
+ assert_eq!(summary.len(), 1);
+ assert_eq!(summary[0], "5 files");
+ }
+
+ #[test]
+ fn test_diff_stats_format_summary_only_insertions() {
+ let stats = DiffStats {
+ files: None,
+ insertions: Some(100),
+ deletions: None,
+ };
+ let summary = stats.format_summary();
+ assert_eq!(summary.len(), 1);
+ assert!(summary[0].contains("100"));
+ }
+
+ #[test]
+ fn test_diff_stats_format_summary_only_deletions() {
+ let stats = DiffStats {
+ files: None,
+ insertions: None,
+ deletions: Some(50),
+ };
+ let summary = stats.format_summary();
+ assert_eq!(summary.len(), 1);
+ assert!(summary[0].contains("50"));
+ }
+}
diff --git a/src/git/error.rs b/src/git/error.rs
index e5ce5df0c..aef96c417 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -706,4 +706,154 @@ mod tests {
💡 Remove with rm -rf /some/path or use a different branch name
");
}
+
+ #[test]
+ fn test_exit_code() {
+ // ChildProcessExited
+ let err: anyhow::Error = WorktrunkError::ChildProcessExited {
+ code: 42,
+ message: "test".into(),
+ }
+ .into();
+ assert_eq!(exit_code(&err), Some(42));
+
+ // HookCommandFailed with code
+ let err: anyhow::Error = WorktrunkError::HookCommandFailed {
+ hook_type: HookType::PreMerge,
+ command_name: Some("test".into()),
+ error: "failed".into(),
+ exit_code: Some(1),
+ }
+ .into();
+ assert_eq!(exit_code(&err), Some(1));
+
+ // HookCommandFailed without code
+ let err: anyhow::Error = WorktrunkError::HookCommandFailed {
+ hook_type: HookType::PreMerge,
+ command_name: None,
+ error: "failed".into(),
+ exit_code: None,
+ }
+ .into();
+ assert_eq!(exit_code(&err), None);
+
+ // CommandNotApproved, AlreadyDisplayed, GitError
+ assert_eq!(exit_code(&WorktrunkError::CommandNotApproved.into()), None);
+ assert_eq!(
+ exit_code(&WorktrunkError::AlreadyDisplayed { exit_code: 5 }.into()),
+ Some(5)
+ );
+ assert_eq!(
+ exit_code(&GitError::DetachedHead { action: None }.into()),
+ None
+ );
+
+ // Wrapped hook error
+ let inner: anyhow::Error = WorktrunkError::HookCommandFailed {
+ hook_type: HookType::PreCommit,
+ command_name: Some("lint".into()),
+ error: "failed".into(),
+ exit_code: Some(7),
+ }
+ .into();
+ assert_eq!(exit_code(&add_hook_skip_hint(inner)), Some(7));
+ }
+
+ #[test]
+ fn test_is_command_not_approved() {
+ assert!(is_command_not_approved(
+ &WorktrunkError::CommandNotApproved.into()
+ ));
+ assert!(!is_command_not_approved(
+ &WorktrunkError::ChildProcessExited {
+ code: 1,
+ message: "test".into()
+ }
+ .into()
+ ));
+ assert!(!is_command_not_approved(
+ &WorktrunkError::HookCommandFailed {
+ hook_type: HookType::PostCreate,
+ command_name: None,
+ error: "failed".into(),
+ exit_code: None,
+ }
+ .into()
+ ));
+ assert!(!is_command_not_approved(
+ &GitError::DetachedHead { action: None }.into()
+ ));
+ }
+
+ #[test]
+ fn test_add_hook_skip_hint() {
+ // Wraps HookCommandFailed with --no-verify hint
+ let inner: anyhow::Error = WorktrunkError::HookCommandFailed {
+ hook_type: HookType::PreMerge,
+ command_name: Some("test".into()),
+ error: "failed".into(),
+ exit_code: Some(1),
+ }
+ .into();
+ let display = format!("{}", add_hook_skip_hint(inner));
+ assert!(display.contains("--no-verify") && display.contains("pre-merge"));
+
+ // Passes through non-hook errors
+ let err: anyhow::Error = WorktrunkError::ChildProcessExited {
+ code: 1,
+ message: "test".into(),
+ }
+ .into();
+ assert!(!format!("{}", add_hook_skip_hint(err)).contains("--no-verify"));
+
+ let err: anyhow::Error = GitError::DetachedHead { action: None }.into();
+ assert!(!format!("{}", add_hook_skip_hint(err)).contains("--no-verify"));
+ }
+
+ #[test]
+ fn test_format_error_block() {
+ let header = "Error occurred".to_string();
+ let result = format_error_block(header.clone(), " some error text ");
+ assert!(result.contains("Error occurred") && result.contains("some error text"));
+
+ // Empty/whitespace returns header only
+ assert_eq!(format_error_block(header.clone(), ""), header);
+ assert_eq!(format_error_block(header.clone(), " \n\t "), header);
+ }
+
+ #[test]
+ fn test_worktrunk_error_display() {
+ // ChildProcessExited
+ let err = WorktrunkError::ChildProcessExited {
+ code: 1,
+ message: "Command failed".into(),
+ };
+ assert!(format!("{err}").contains("Command failed"));
+
+ // HookCommandFailed with/without name
+ let err = WorktrunkError::HookCommandFailed {
+ hook_type: HookType::PreMerge,
+ command_name: Some("lint".into()),
+ error: "lint failed".into(),
+ exit_code: Some(1),
+ };
+ let display = format!("{err}");
+ assert!(display.contains("pre-merge") && display.contains("lint"));
+
+ let err = WorktrunkError::HookCommandFailed {
+ hook_type: HookType::PostCreate,
+ command_name: None,
+ error: "setup failed".into(),
+ exit_code: None,
+ };
+ let display = format!("{err}");
+ assert!(display.contains("post-create") && display.contains("setup failed"));
+
+ // Silent errors
+ assert_eq!(format!("{}", WorktrunkError::CommandNotApproved), "");
+ assert_eq!(
+ format!("{}", WorktrunkError::AlreadyDisplayed { exit_code: 1 }),
+ ""
+ );
+ }
}
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 507cc1d5e..322986dc4 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -596,4 +596,133 @@ mod tests {
vec!["main".to_string(), "feature".to_string()]
);
}
+
+ #[test]
+ fn test_escape_unescape_roundtrip() {
+ // Test escape
+ let cases = [
+ ("main", "main"),
+ ("feature/foo", "feature-2Ffoo"),
+ ("feature_foo", "feature-5Ffoo"),
+ ("feature-foo", "feature-2Dfoo"),
+ ("v1.0.0", "v1.0.0"), // Dots allowed
+ ("user/feature_name-v2", "user-2Ffeature-5Fname-2Dv2"),
+ ];
+ for (input, expected_escaped) in cases {
+ assert_eq!(
+ escape_branch_for_config(input),
+ expected_escaped,
+ "escape {input}"
+ );
+ assert_eq!(
+ unescape_branch_from_config(expected_escaped),
+ input,
+ "unescape {expected_escaped}"
+ );
+ }
+ // Invalid/truncated escape sequences kept as-is
+ assert_eq!(unescape_branch_from_config("foo-GGbar"), "foo-GGbar");
+ assert_eq!(unescape_branch_from_config("foo-2"), "foo-2");
+ }
+
+ #[test]
+ fn test_check_integration() {
+ // Each integration reason + not integrated
+ let cases = [
+ (
+ (true, false, true, false, true),
+ Some(IntegrationReason::SameCommit),
+ ),
+ (
+ (false, true, true, false, true),
+ Some(IntegrationReason::Ancestor),
+ ),
+ (
+ (false, false, false, false, true),
+ Some(IntegrationReason::NoAddedChanges),
+ ),
+ (
+ (false, false, true, true, true),
+ Some(IntegrationReason::TreesMatch),
+ ),
+ (
+ (false, false, true, false, false),
+ Some(IntegrationReason::MergeAddsNothing),
+ ),
+ ((false, false, true, false, true), None), // Not integrated
+ (
+ (true, true, false, true, false),
+ Some(IntegrationReason::SameCommit),
+ ), // Priority test
+ ];
+ for ((same, ancestor, added, trees, merge), expected) in cases {
+ let mut provider = PrecomputedIntegration {
+ is_same_commit: same,
+ is_ancestor: ancestor,
+ has_added_changes: added,
+ trees_match: trees,
+ would_merge_add: merge,
+ };
+ assert_eq!(
+ check_integration(&mut provider),
+ expected,
+ "case: {same},{ancestor},{added},{trees},{merge}"
+ );
+ }
+ }
+
+ #[test]
+ fn test_integration_reason_description() {
+ assert_eq!(
+ IntegrationReason::SameCommit.description(),
+ "same commit as"
+ );
+ assert_eq!(IntegrationReason::Ancestor.description(), "ancestor of");
+ assert_eq!(
+ IntegrationReason::NoAddedChanges.description(),
+ "no added changes"
+ );
+ assert_eq!(IntegrationReason::TreesMatch.description(), "tree matches");
+ assert_eq!(
+ IntegrationReason::MergeAddsNothing.description(),
+ "all changes in"
+ );
+ }
+
+ #[test]
+ fn test_path_dir_name() {
+ assert_eq!(
+ path_dir_name(&PathBuf::from("/home/user/repo.feature")),
+ "repo.feature"
+ );
+ assert_eq!(path_dir_name(&PathBuf::from("/")), "(unknown)");
+ assert!(!path_dir_name(&PathBuf::from("/home/user/repo/")).is_empty());
+
+ // Worktree::dir_name
+ let wt = Worktree {
+ path: PathBuf::from("/repos/myrepo.feature"),
+ head: "abc123".into(),
+ branch: Some("feature".into()),
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ };
+ assert_eq!(wt.dir_name(), "myrepo.feature");
+ }
+
+ #[test]
+ fn test_hook_type_display() {
+ let cases = [
+ (HookType::PostCreate, "post-create"),
+ (HookType::PostStart, "post-start"),
+ (HookType::PreCommit, "pre-commit"),
+ (HookType::PreMerge, "pre-merge"),
+ (HookType::PostMerge, "post-merge"),
+ (HookType::PreRemove, "pre-remove"),
+ ];
+ for (hook, expected) in cases {
+ assert_eq!(format!("{hook}"), expected);
+ }
+ }
}
diff --git a/src/git/parse.rs b/src/git/parse.rs
index 7301a1450..f625a89d1 100644
--- a/src/git/parse.rs
+++ b/src/git/parse.rs
@@ -136,3 +136,207 @@ impl DefaultBranchName {
self.0
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // ============================================================================
+ // DefaultBranchName::from_local Tests
+ // ============================================================================
+
+ #[test]
+ fn test_from_local_simple() {
+ let result = DefaultBranchName::from_local("origin", "main");
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap().into_string(), "main");
+ }
+
+ #[test]
+ fn test_from_local_with_remote_prefix() {
+ let result = DefaultBranchName::from_local("origin", "origin/main");
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap().into_string(), "main");
+ }
+
+ #[test]
+ fn test_from_local_with_whitespace() {
+ let result = DefaultBranchName::from_local("origin", " main \n");
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap().into_string(), "main");
+ }
+
+ #[test]
+ fn test_from_local_empty() {
+ let result = DefaultBranchName::from_local("origin", "");
+ assert!(result.is_err());
+ }
+
+ #[test]
+ fn test_from_local_only_whitespace() {
+ let result = DefaultBranchName::from_local("origin", " \n ");
+ assert!(result.is_err());
+ }
+
+ #[test]
+ fn test_from_local_different_remote() {
+ let result = DefaultBranchName::from_local("upstream", "upstream/develop");
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap().into_string(), "develop");
+ }
+
+ // ============================================================================
+ // DefaultBranchName::from_remote Tests
+ // ============================================================================
+
+ #[test]
+ fn test_from_remote_standard() {
+ let output = "ref: refs/heads/main\tHEAD\n";
+ let result = DefaultBranchName::from_remote(output);
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap().into_string(), "main");
+ }
+
+ #[test]
+ fn test_from_remote_master() {
+ let output = "ref: refs/heads/master\tHEAD\n";
+ let result = DefaultBranchName::from_remote(output);
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap().into_string(), "master");
+ }
+
+ #[test]
+ fn test_from_remote_with_other_lines() {
+ let output = "abc123\tHEAD\nref: refs/heads/develop\tHEAD\ndef456\trefs/heads/main\n";
+ let result = DefaultBranchName::from_remote(output);
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap().into_string(), "develop");
+ }
+
+ #[test]
+ fn test_from_remote_no_ref() {
+ let output = "abc123\tHEAD\n";
+ let result = DefaultBranchName::from_remote(output);
+ assert!(result.is_err());
+ }
+
+ #[test]
+ fn test_from_remote_empty() {
+ let result = DefaultBranchName::from_remote("");
+ assert!(result.is_err());
+ }
+
+ // ============================================================================
+ // Worktree::parse_porcelain_list Tests
+ // ============================================================================
+
+ #[test]
+ fn test_parse_porcelain_list_single_worktree() {
+ let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\n\n";
+ let result = Worktree::parse_porcelain_list(output);
+ assert!(result.is_ok());
+ let worktrees = result.unwrap();
+ assert_eq!(worktrees.len(), 1);
+ assert_eq!(worktrees[0].path.to_str().unwrap(), "/path/to/repo");
+ assert_eq!(worktrees[0].head, "abc123");
+ assert_eq!(worktrees[0].branch, Some("main".to_string()));
+ }
+
+ #[test]
+ fn test_parse_porcelain_list_multiple_worktrees() {
+ let output = "worktree /path/main\nHEAD aaa\nbranch refs/heads/main\n\nworktree /path/feature\nHEAD bbb\nbranch refs/heads/feature\n\n";
+ let result = Worktree::parse_porcelain_list(output);
+ assert!(result.is_ok());
+ let worktrees = result.unwrap();
+ assert_eq!(worktrees.len(), 2);
+ assert_eq!(worktrees[0].branch, Some("main".to_string()));
+ assert_eq!(worktrees[1].branch, Some("feature".to_string()));
+ }
+
+ #[test]
+ fn test_parse_porcelain_list_bare_repo() {
+ let output = "worktree /path/to/repo.git\nHEAD abc123\nbare\n\n";
+ let result = Worktree::parse_porcelain_list(output);
+ assert!(result.is_ok());
+ let worktrees = result.unwrap();
+ assert_eq!(worktrees.len(), 1);
+ assert!(worktrees[0].bare);
+ }
+
+ #[test]
+ fn test_parse_porcelain_list_detached() {
+ let output = "worktree /path/to/repo\nHEAD abc123\ndetached\n\n";
+ let result = Worktree::parse_porcelain_list(output);
+ assert!(result.is_ok());
+ let worktrees = result.unwrap();
+ assert_eq!(worktrees.len(), 1);
+ assert!(worktrees[0].detached);
+ assert!(worktrees[0].branch.is_none());
+ }
+
+ #[test]
+ fn test_parse_porcelain_list_locked() {
+ let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nlocked reason for lock\n\n";
+ let result = Worktree::parse_porcelain_list(output);
+ assert!(result.is_ok());
+ let worktrees = result.unwrap();
+ assert_eq!(worktrees.len(), 1);
+ assert_eq!(worktrees[0].locked, Some("reason for lock".to_string()));
+ }
+
+ #[test]
+ fn test_parse_porcelain_list_prunable() {
+ let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nprunable gitdir file missing\n\n";
+ let result = Worktree::parse_porcelain_list(output);
+ assert!(result.is_ok());
+ let worktrees = result.unwrap();
+ assert_eq!(worktrees.len(), 1);
+ assert_eq!(
+ worktrees[0].prunable,
+ Some("gitdir file missing".to_string())
+ );
+ }
+
+ #[test]
+ fn test_parse_porcelain_list_empty() {
+ let result = Worktree::parse_porcelain_list("");
+ assert!(result.is_ok());
+ let worktrees = result.unwrap();
+ assert!(worktrees.is_empty());
+ }
+
+ #[test]
+ fn test_parse_porcelain_list_no_trailing_blank() {
+ // Git output may not always end with a blank line
+ let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main";
+ let result = Worktree::parse_porcelain_list(output);
+ assert!(result.is_ok());
+ let worktrees = result.unwrap();
+ assert_eq!(worktrees.len(), 1);
+ }
+
+ #[test]
+ fn test_parse_porcelain_list_missing_worktree_path() {
+ let output = "worktree\nHEAD abc123\n\n";
+ let result = Worktree::parse_porcelain_list(output);
+ assert!(result.is_err());
+ }
+
+ #[test]
+ fn test_parse_porcelain_list_missing_head_sha() {
+ let output = "worktree /path\nHEAD\n\n";
+ let result = Worktree::parse_porcelain_list(output);
+ assert!(result.is_err());
+ }
+
+ #[test]
+ fn test_parse_porcelain_list_branch_without_refs_prefix() {
+ // This can happen in some edge cases
+ let output = "worktree /path/to/repo\nHEAD abc123\nbranch main\n\n";
+ let result = Worktree::parse_porcelain_list(output);
+ assert!(result.is_ok());
+ let worktrees = result.unwrap();
+ // Should use the branch name as-is when no refs/heads/ prefix
+ assert_eq!(worktrees[0].branch, Some("main".to_string()));
+ }
+}
diff --git a/src/git/test.rs b/src/git/test.rs
index 2dc14a444..de73fc83d 100644
--- a/src/git/test.rs
+++ b/src/git/test.rs
@@ -394,3 +394,120 @@ fn snapshot_parse_worktree_list_unknown_attributes() {
}
"#);
}
+
+// Tests for escape_branch_for_config and unescape_branch_from_config
+
+use super::{escape_branch_for_config, unescape_branch_from_config};
+
+#[test]
+fn test_escape_branch_simple() {
+ // Alphanumeric and dots should pass through unchanged
+ assert_eq!(escape_branch_for_config("main"), "main");
+ assert_eq!(escape_branch_for_config("feature.123"), "feature.123");
+ assert_eq!(escape_branch_for_config("AaBbZz0189"), "AaBbZz0189");
+}
+
+#[test]
+fn test_escape_branch_with_slash() {
+ // Slashes should be encoded as -2F
+ assert_eq!(
+ escape_branch_for_config("feature/branch"),
+ "feature-2Fbranch"
+ );
+ assert_eq!(escape_branch_for_config("a/b/c"), "a-2Fb-2Fc");
+}
+
+#[test]
+fn test_escape_branch_with_underscore() {
+ // Underscores should be encoded as -5F
+ assert_eq!(escape_branch_for_config("my_branch"), "my-5Fbranch");
+ assert_eq!(escape_branch_for_config("a_b_c"), "a-5Fb-5Fc");
+}
+
+#[test]
+fn test_escape_branch_with_hyphen() {
+ // Hyphens should be encoded as -2D
+ assert_eq!(escape_branch_for_config("my-branch"), "my-2Dbranch");
+ assert_eq!(escape_branch_for_config("a-b-c"), "a-2Db-2Dc");
+}
+
+#[test]
+fn test_escape_branch_mixed_special_chars() {
+ // Mix of special characters
+ assert_eq!(
+ escape_branch_for_config("feature/my-branch_test"),
+ "feature-2Fmy-2Dbranch-5Ftest"
+ );
+}
+
+#[test]
+fn test_unescape_branch_simple() {
+ // Simple strings should pass through unchanged
+ assert_eq!(unescape_branch_from_config("main"), "main");
+ assert_eq!(unescape_branch_from_config("feature.123"), "feature.123");
+}
+
+#[test]
+fn test_unescape_branch_with_encoded_slash() {
+ // -2F should become /
+ assert_eq!(
+ unescape_branch_from_config("feature-2Fbranch"),
+ "feature/branch"
+ );
+}
+
+#[test]
+fn test_unescape_branch_with_encoded_underscore() {
+ // -5F should become _
+ assert_eq!(unescape_branch_from_config("my-5Fbranch"), "my_branch");
+}
+
+#[test]
+fn test_unescape_branch_with_encoded_hyphen() {
+ // -2D should become -
+ assert_eq!(unescape_branch_from_config("my-2Dbranch"), "my-branch");
+}
+
+#[test]
+fn test_escape_unescape_roundtrip() {
+ // Test that escape followed by unescape returns original
+ let test_cases = vec![
+ "main",
+ "feature/branch",
+ "my-branch",
+ "my_branch",
+ "feature/my-branch_test",
+ "a/b/c-d_e.f",
+ "",
+ ];
+ for branch in test_cases {
+ let escaped = escape_branch_for_config(branch);
+ let unescaped = unescape_branch_from_config(&escaped);
+ assert_eq!(
+ unescaped, branch,
+ "Roundtrip failed for '{branch}': escaped='{}', unescaped='{}'",
+ escaped, unescaped
+ );
+ }
+}
+
+#[test]
+fn test_unescape_branch_invalid_escape() {
+ // Invalid escape sequences should be kept as-is
+ // -XX where XX is not valid hex
+ assert_eq!(unescape_branch_from_config("test-ZZ"), "test-ZZ");
+ // - at end without following chars
+ assert_eq!(unescape_branch_from_config("test-"), "test-");
+ // - followed by only one char
+ assert_eq!(unescape_branch_from_config("test-A"), "test-A");
+}
+
+#[test]
+fn test_escape_branch_empty() {
+ assert_eq!(escape_branch_for_config(""), "");
+}
+
+#[test]
+fn test_unescape_branch_empty() {
+ assert_eq!(unescape_branch_from_config(""), "");
+}
diff --git a/src/md_help.rs b/src/md_help.rs
index 1b8960559..4ca091652 100644
--- a/src/md_help.rs
+++ b/src/md_help.rs
@@ -426,4 +426,273 @@ mod tests {
"Escaped sequence should not appear literally"
);
}
+
+ // ============================================================================
+ // strip_ansi Tests
+ // ============================================================================
+
+ #[test]
+ fn test_strip_ansi_no_escapes() {
+ assert_eq!(strip_ansi("plain text"), "plain text");
+ }
+
+ #[test]
+ fn test_strip_ansi_with_color() {
+ assert_eq!(strip_ansi("\u{1b}[32mgreen\u{1b}[0m"), "green");
+ }
+
+ #[test]
+ fn test_strip_ansi_multiple_codes() {
+ assert_eq!(
+ strip_ansi("\u{1b}[1mbold\u{1b}[0m and \u{1b}[2mdim\u{1b}[0m"),
+ "bold and dim"
+ );
+ }
+
+ #[test]
+ fn test_strip_ansi_nested() {
+ assert_eq!(
+ strip_ansi("\u{1b}[1m\u{1b}[32mtext\u{1b}[0m\u{1b}[0m"),
+ "text"
+ );
+ }
+
+ // ============================================================================
+ // render_markdown_in_help Tests
+ // ============================================================================
+
+ #[test]
+ fn test_render_markdown_in_help_h1() {
+ let result = render_markdown_in_help("# Header");
+ // H1 should be green
+ assert!(result.contains("Header"));
+ assert!(result.contains("\u{1b}[")); // Has color codes
+ }
+
+ #[test]
+ fn test_render_markdown_in_help_h2() {
+ let result = render_markdown_in_help("## Section");
+ assert!(result.contains("Section"));
+ assert!(result.contains("\u{1b}[")); // Has color codes
+ }
+
+ #[test]
+ fn test_render_markdown_in_help_h3() {
+ let result = render_markdown_in_help("### Subsection");
+ assert!(result.contains("Subsection"));
+ // H3 is bold
+ assert!(result.contains("\u{1b}[1m")); // Bold
+ }
+
+ #[test]
+ fn test_render_markdown_in_help_code_block() {
+ let md = "```\ncode here\n```\nafter";
+ let result = render_markdown_in_help(md);
+ // Code is dimmed with indent
+ assert!(result.contains("code here"));
+ assert!(result.contains("after"));
+ }
+
+ #[test]
+ fn test_render_markdown_in_help_html_comment() {
+ let md = "<!-- comment -->\nvisible";
+ let result = render_markdown_in_help(md);
+ // Comments should be stripped
+ assert!(!result.contains("comment"));
+ assert!(result.contains("visible"));
+ }
+
+ #[test]
+ fn test_render_markdown_in_help_plain_text() {
+ let result = render_markdown_in_help("Just plain text");
+ assert!(result.contains("Just plain text"));
+ }
+
+ #[test]
+ fn test_render_markdown_in_help_table() {
+ let md = "| A | B |\n| - | - |\n| 1 | 2 |";
+ let result = render_markdown_in_help(md);
+ // Table should be rendered
+ assert!(result.contains("A"));
+ assert!(result.contains("B"));
+ assert!(result.contains("1"));
+ assert!(result.contains("2"));
+ }
+
+ // ============================================================================
+ // render_markdown_table Tests
+ // ============================================================================
+
+ #[test]
+ fn test_render_markdown_table_basic() {
+ let md = "| Col1 | Col2 |\n| ---- | ---- |\n| A | B |";
+ let result = render_markdown_table(md);
+ assert!(result.contains("Col1"));
+ assert!(result.contains("Col2"));
+ assert!(result.contains("A"));
+ assert!(result.contains("B"));
+ }
+
+ #[test]
+ fn test_render_markdown_table_empty() {
+ let result = render_markdown_table("");
+ assert!(result.is_empty());
+ }
+
+ #[test]
+ fn test_render_markdown_table_with_non_table_lines() {
+ let md = "Not a table\n| A | B |\nAlso not\n| - | - |\n| 1 | 2 |";
+ let result = render_markdown_table(md);
+ // Should only include table rows
+ assert!(result.contains("A"));
+ assert!(result.contains("B"));
+ assert!(!result.contains("Not a table"));
+ assert!(!result.contains("Also not"));
+ }
+
+ // ============================================================================
+ // colorize_status_symbols Tests
+ // ============================================================================
+
+ #[test]
+ fn test_colorize_status_symbols_working_tree() {
+ // These symbols should become cyan
+ let dim = Style::new().dimmed();
+ let input = format!("{}+{dim:#} staged", dim);
+ let result = colorize_status_symbols(&input);
+ // Should have cyan color code (36)
+ assert!(result.contains("\u{1b}[36m+"));
+ }
+
+ #[test]
+ fn test_colorize_status_symbols_conflicts() {
+ // ✘ should become red
+ let dim = Style::new().dimmed();
+ let input = format!("{}✘{dim:#} conflicts", dim);
+ let result = colorize_status_symbols(&input);
+ // Should have red color code (31)
+ assert!(result.contains("\u{1b}[31m✘"));
+ }
+
+ #[test]
+ fn test_colorize_status_symbols_git_ops() {
+ // ⤴ and ⤵ should become yellow
+ let dim = Style::new().dimmed();
+ let input = format!("{}⤴{dim:#} rebase", dim);
+ let result = colorize_status_symbols(&input);
+ // Should have yellow color code (33)
+ assert!(result.contains("\u{1b}[33m⤴"));
+ }
+
+ #[test]
+ fn test_colorize_status_symbols_ci_green() {
+ let result = colorize_status_symbols("● passed");
+ // Should have green color (32)
+ assert!(result.contains("\u{1b}[32m●"));
+ }
+
+ #[test]
+ fn test_colorize_status_symbols_ci_red() {
+ let result = colorize_status_symbols("● failed");
+ // Should have red color (31)
+ assert!(result.contains("\u{1b}[31m●"));
+ }
+
+ #[test]
+ fn test_colorize_status_symbols_ci_running() {
+ let result = colorize_status_symbols("● running");
+ // Should have blue color (34)
+ assert!(result.contains("\u{1b}[34m●"));
+ }
+
+ #[test]
+ fn test_colorize_status_symbols_no_change() {
+ // Text without symbols should pass through unchanged
+ let input = "plain text here";
+ let result = colorize_status_symbols(input);
+ assert_eq!(result, input);
+ }
+
+ // ============================================================================
+ // render_inline_formatting Tests
+ // ============================================================================
+
+ #[test]
+ fn test_render_inline_formatting_inline_code() {
+ let result = render_inline_formatting("`code`");
+ // Should have dim escape codes
+ assert!(result.contains("code"));
+ assert!(result.contains("\u{1b}[2m")); // Dimmed
+ }
+
+ #[test]
+ fn test_render_inline_formatting_bold() {
+ let result = render_inline_formatting("**bold**");
+ assert!(result.contains("bold"));
+ assert!(result.contains("\u{1b}[1m")); // Bold
+ }
+
+ #[test]
+ fn test_render_inline_formatting_mixed() {
+ let result = render_inline_formatting("text `code` more **bold** end");
+ assert!(result.contains("text"));
+ assert!(result.contains("code"));
+ assert!(result.contains("more"));
+ assert!(result.contains("bold"));
+ assert!(result.contains("end"));
+ }
+
+ #[test]
+ fn test_render_inline_formatting_unclosed_code() {
+ // Unclosed backtick - should consume until end
+ let result = render_inline_formatting("`unclosed");
+ assert!(result.contains("unclosed"));
+ }
+
+ #[test]
+ fn test_render_inline_formatting_unclosed_bold() {
+ // Unclosed bold - should consume until end
+ let result = render_inline_formatting("**unclosed");
+ assert!(result.contains("unclosed"));
+ }
+
+ // ============================================================================
+ // render_markdown_table_impl Tests (via render_table)
+ // ============================================================================
+
+ #[test]
+ fn test_render_table_column_alignment() {
+ let lines = vec![
+ "| Short | LongerHeader |",
+ "| ----- | ------------ |",
+ "| A | B |",
+ ];
+ let result = render_table(&lines);
+ // Should have proper column alignment
+ assert!(result.contains("Short"));
+ assert!(result.contains("LongerHeader"));
+ // Should have separator line with ─
+ assert!(result.contains('─'));
+ }
+
+ #[test]
+ fn test_render_table_uneven_columns() {
+ let lines = vec!["| A | B | C |", "| --- | --- | --- |", "| 1 | 2 |"];
+ let result = render_table(&lines);
+ // Should handle rows with different column counts
+ assert!(result.contains("A"));
+ assert!(result.contains("1"));
+ }
+
+ #[test]
+ fn test_render_table_no_separator() {
+ // Table without separator row
+ let lines = vec!["| A | B |", "| 1 | 2 |"];
+ let result = render_table(&lines);
+ // Should still render, just without separator line
+ assert!(result.contains("A"));
+ assert!(result.contains("1"));
+ // Should NOT have separator line
+ assert!(!result.contains('─'));
+ }
}
diff --git a/src/shell.rs b/src/shell.rs
index 24aafbf66..f738c2f54 100644
--- a/src/shell.rs
+++ b/src/shell.rs
@@ -563,4 +563,121 @@ mod tests {
assert!(!output.is_empty(), "Empty output for {:?}", shell);
}
}
+
+ #[test]
+ fn test_shell_config_paths_returns_paths() {
+ // All shells should return at least one config path
+ let shells = [Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell];
+ for shell in shells {
+ let result = shell.config_paths();
+ assert!(result.is_ok(), "Failed to get config paths for {:?}", shell);
+ let paths = result.unwrap();
+ assert!(
+ !paths.is_empty(),
+ "No config paths returned for {:?}",
+ shell
+ );
+ }
+ }
+
+ #[test]
+ fn test_shell_completion_path_returns_path() {
+ // All shells should return a completion path
+ let shells = [Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell];
+ for shell in shells {
+ let result = shell.completion_path();
+ assert!(
+ result.is_ok(),
+ "Failed to get completion path for {:?}",
+ shell
+ );
+ let path = result.unwrap();
+ assert!(
+ !path.as_os_str().is_empty(),
+ "Empty completion path for {:?}",
+ shell
+ );
+ }
+ }
+
+ #[test]
+ fn test_shell_config_paths_with_custom_prefix() {
+ // Test that custom prefix affects the paths where appropriate
+ let prefix = "custom-wt";
+
+ // Fish config path should include prefix in filename
+ let fish_paths = Shell::Fish.config_paths_with_prefix(prefix).unwrap();
+ assert!(
+ fish_paths[0].to_string_lossy().contains("custom-wt.fish"),
+ "Fish config should include prefix in filename"
+ );
+
+ // Bash and Zsh config paths are fixed (not affected by prefix)
+ let bash_paths = Shell::Bash.config_paths_with_prefix(prefix).unwrap();
+ assert!(
+ bash_paths[0].to_string_lossy().contains(".bashrc"),
+ "Bash config should be .bashrc"
+ );
+
+ let zsh_paths = Shell::Zsh.config_paths_with_prefix(prefix).unwrap();
+ assert!(
+ zsh_paths[0].to_string_lossy().contains(".zshrc"),
+ "Zsh config should be .zshrc"
+ );
+ }
+
+ #[test]
+ fn test_shell_completion_path_with_custom_prefix() {
+ let prefix = "my-prefix";
+
+ // Bash completion should include prefix in path
+ let bash_path = Shell::Bash.completion_path_with_prefix(prefix).unwrap();
+ assert!(
+ bash_path.to_string_lossy().contains("my-prefix"),
+ "Bash completion should include prefix"
+ );
+
+ // Fish completion should include prefix in filename
+ let fish_path = Shell::Fish.completion_path_with_prefix(prefix).unwrap();
+ assert!(
+ fish_path.to_string_lossy().contains("my-prefix.fish"),
+ "Fish completion should include prefix in filename"
+ );
+
+ // Zsh completion should include prefix
+ let zsh_path = Shell::Zsh.completion_path_with_prefix(prefix).unwrap();
+ assert!(
+ zsh_path.to_string_lossy().contains("_my-prefix"),
+ "Zsh completion should include underscore prefix"
+ );
+ }
+
+ #[test]
+ fn test_config_line_prefix_arg_handling() {
+ // Default prefix should not include --cmd
+ let bash_default = Shell::Bash.config_line_with_prefix("wt");
+ assert!(
+ !bash_default.contains("--cmd"),
+ "Default prefix should not include --cmd"
+ );
+
+ // Custom prefix should include --cmd
+ let bash_custom = Shell::Bash.config_line_with_prefix("custom");
+ assert!(
+ bash_custom.contains("--cmd=custom"),
+ "Custom prefix should include --cmd=custom"
+ );
+ }
+
+ #[test]
+ fn test_shell_init_with_custom_prefix() {
+ let init = ShellInit::with_prefix(Shell::Bash, "custom".to_string());
+ let result = init.generate();
+ assert!(result.is_ok(), "Should generate with custom prefix");
+ let output = result.unwrap();
+ assert!(
+ output.contains("custom"),
+ "Output should contain custom prefix"
+ );
+ }
}
diff --git a/src/styling/constants.rs b/src/styling/constants.rs
index 61fd436f4..7623a23b2 100644
--- a/src/styling/constants.rs
+++ b/src/styling/constants.rs
@@ -150,3 +150,134 @@ pub fn format_heading(title: &str, suffix: Option<&str>) -> String {
None => cformat!("<cyan>{}</>", title),
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // ============================================================================
+ // Style Constants Tests
+ // ============================================================================
+
+ #[test]
+ fn test_addition_style() {
+ // ADDITION should be green foreground
+ let rendered = ADDITION.render().to_string();
+ // Green is ANSI 32
+ assert!(rendered.contains("32"));
+ }
+
+ #[test]
+ fn test_deletion_style() {
+ // DELETION should be red foreground
+ let rendered = DELETION.render().to_string();
+ // Red is ANSI 31
+ assert!(rendered.contains("31"));
+ }
+
+ #[test]
+ fn test_gutter_style() {
+ // GUTTER should have bright white background
+ let rendered = GUTTER.render().to_string();
+ // BrightWhite background is ANSI 107
+ assert!(rendered.contains("107"));
+ }
+
+ // ============================================================================
+ // Emoji Constants Tests
+ // ============================================================================
+
+ #[test]
+ fn test_emoji_constants() {
+ assert_eq!(PROGRESS_EMOJI, "🔄");
+ assert_eq!(SUCCESS_EMOJI, "✅");
+ assert_eq!(ERROR_EMOJI, "❌");
+ assert_eq!(WARNING_EMOJI, "🟡");
+ assert_eq!(HINT_EMOJI, "💡");
+ assert_eq!(INFO_EMOJI, "⚪");
+ assert_eq!(PROMPT_EMOJI, "❓");
+ }
+
+ // ============================================================================
+ // Message Formatting Functions Tests
+ // ============================================================================
+
+ #[test]
+ fn test_error_message() {
+ let msg = error_message("Something went wrong");
+ assert!(msg.contains("❌"));
+ assert!(msg.contains("Something went wrong"));
+ }
+
+ #[test]
+ fn test_error_message_with_inner_styling() {
+ let name = "feature";
+ let msg = error_message(cformat!("Branch <bold>{name}</> not found"));
+ assert!(msg.contains("❌"));
+ assert!(msg.contains("Branch"));
+ assert!(msg.contains("feature"));
+ }
+
+ #[test]
+ fn test_hint_message() {
+ let msg = hint_message("Try running --help");
+ assert!(msg.contains("💡"));
+ assert!(msg.contains("Try running --help"));
+ }
+
+ #[test]
+ fn test_warning_message() {
+ let msg = warning_message("Deprecated option");
+ assert!(msg.contains("🟡"));
+ assert!(msg.contains("Deprecated option"));
+ }
+
+ #[test]
+ fn test_success_message() {
+ let msg = success_message("Operation completed");
+ assert!(msg.contains("✅"));
+ assert!(msg.contains("Operation completed"));
+ }
+
+ #[test]
+ fn test_progress_message() {
+ let msg = progress_message("Loading data...");
+ assert!(msg.contains("🔄"));
+ assert!(msg.contains("Loading data..."));
+ }
+
+ #[test]
+ fn test_info_message() {
+ let msg = info_message("5 items found");
+ assert!(msg.contains("⚪"));
+ assert!(msg.contains("5 items found"));
+ }
+
+ // ============================================================================
+ // format_heading Tests
+ // ============================================================================
+
+ #[test]
+ fn test_format_heading_without_suffix() {
+ let heading = format_heading("BINARIES", None);
+ assert!(heading.contains("BINARIES"));
+ // Should NOT contain extra spacing for suffix
+ assert!(!heading.ends_with(" "));
+ }
+
+ #[test]
+ fn test_format_heading_with_suffix() {
+ let heading = format_heading("USER CONFIG", Some("~/.config/wt.toml"));
+ assert!(heading.contains("USER CONFIG"));
+ assert!(heading.contains("~/.config/wt.toml"));
+ // Should have double-space separator
+ assert!(heading.contains(" "));
+ }
+
+ #[test]
+ fn test_format_heading_empty_title() {
+ let heading = format_heading("", None);
+ // Empty string, still formatted
+ assert!(heading.is_empty() || heading.contains('\u{1b}'));
+ }
+}
diff --git a/src/styling/format.rs b/src/styling/format.rs
index 3232761ec..42e93367c 100644
--- a/src/styling/format.rs
+++ b/src/styling/format.rs
@@ -410,4 +410,94 @@ mod tests {
// Verify the overhead matches documented value
assert_eq!(GUTTER_OVERHEAD, 3);
}
+
+ #[test]
+ fn test_format_with_gutter_empty() {
+ let result = format_with_gutter("", "", Some(80));
+ // Empty input should produce empty output
+ assert!(result.is_empty());
+ }
+
+ #[test]
+ fn test_format_with_gutter_with_margin() {
+ let result = format_with_gutter("content", " ", Some(80));
+ // Content with margin should still have the content
+ assert!(result.contains("content"));
+ // Should start with margin spaces
+ assert!(result.starts_with(" "));
+ }
+
+ #[test]
+ fn test_format_with_gutter_wrapping() {
+ // Use a very narrow width to force wrapping
+ let result = format_with_gutter("word1 word2 word3 word4", "", Some(15));
+ // Content should be wrapped to multiple lines
+ let line_count = result.matches('\n').count();
+ assert!(
+ line_count > 1,
+ "Expected multiple lines, got {}",
+ line_count
+ );
+ }
+
+ #[test]
+ fn test_wrap_text_at_width_with_multiple_spaces() {
+ // wrap_text_at_width uses split_whitespace which joins with single space
+ // Let's verify behavior by checking what actually happens
+ let result = wrap_text_at_width("hello world", 20);
+ // split_whitespace preserves word boundaries but normalizes whitespace
+ // Actually looking at the code - split_whitespace + rejoin with single space
+ // yields "hello world" when joining
+ assert!(result[0].contains("hello"));
+ assert!(result[0].contains("world"));
+ }
+
+ #[test]
+ fn test_wrap_styled_text_with_ansi() {
+ // Text with ANSI codes should wrap based on visible width
+ let styled = "\u{1b}[1mbold text\u{1b}[0m here";
+ let result = wrap_styled_text(styled, 100);
+ // Should preserve the content
+ assert!(result[0].contains("bold"));
+ assert!(result[0].contains("text"));
+ }
+
+ #[test]
+ fn test_wrap_styled_text_strips_injected_resets() {
+ // If wrap_ansi injects [39m or [49m, they should be stripped
+ let styled = "some colored text";
+ let result = wrap_styled_text(styled, 50);
+ // Result should not contain the specific reset codes we strip
+ assert!(!result[0].contains("\u{1b}[39m"));
+ assert!(!result[0].contains("\u{1b}[49m"));
+ }
+
+ #[test]
+ #[cfg(feature = "syntax-highlighting")]
+ fn test_format_bash_with_gutter_at_width_basic() {
+ let result = format_bash_with_gutter_at_width("echo hello", "", 80);
+ assert!(result.contains("echo"));
+ assert!(result.contains("hello"));
+ assert!(result.ends_with('\n'));
+ }
+
+ #[test]
+ #[cfg(feature = "syntax-highlighting")]
+ fn test_format_bash_with_gutter_at_width_multiline() {
+ let result = format_bash_with_gutter_at_width("echo line1\necho line2", "", 80);
+ assert!(result.contains("line1"));
+ assert!(result.contains("line2"));
+ // Two lines should have two newlines
+ assert_eq!(result.matches('\n').count(), 2);
+ }
+
+ #[test]
+ #[cfg(feature = "syntax-highlighting")]
+ fn test_format_bash_with_gutter_complex_command() {
+ let result =
+ format_bash_with_gutter_at_width("npm install && cargo build --release", "", 100);
+ assert!(result.contains("npm"));
+ assert!(result.contains("cargo"));
+ assert!(result.contains("--release"));
+ }
}
diff --git a/src/styling/highlighting.rs b/src/styling/highlighting.rs
index 1306c1873..5b0be95f5 100644
--- a/src/styling/highlighting.rs
+++ b/src/styling/highlighting.rs
@@ -170,3 +170,180 @@ fn toml_token_style(kind: &str) -> Option<Style> {
_ => None,
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ #[cfg(feature = "syntax-highlighting")]
+ fn test_bash_token_style_function() {
+ // Commands should be blue dimmed
+ let style = bash_token_style("function");
+ assert!(style.is_some());
+ let s = style.unwrap();
+ assert_eq!(s.get_fg_color(), Some(Color::Ansi(AnsiColor::Blue)));
+ }
+
+ #[test]
+ #[cfg(feature = "syntax-highlighting")]
+ fn test_bash_token_style_keyword() {
+ // Keywords should be magenta dimmed
+ let style = bash_token_style("keyword");
+ assert!(style.is_some());
+ let s = style.unwrap();
+ assert_eq!(s.get_fg_color(), Some(Color::Ansi(AnsiColor::Magenta)));
+ }
+
+ #[test]
+ #[cfg(feature = "syntax-highlighting")]
+ fn test_bash_token_style_string() {
+ // Strings should be green dimmed
+ let style = bash_token_style("string");
+ assert!(style.is_some());
+ let s = style.unwrap();
+ assert_eq!(s.get_fg_color(), Some(Color::Ansi(AnsiColor::Green)));
+ }
+
+ #[test]
+ #[cfg(feature = "syntax-highlighting")]
+ fn test_bash_token_style_operator() {
+ // Operators should be cyan dimmed
+ let style = bash_token_style("operator");
+ assert!(style.is_some());
+ let s = style.unwrap();
+ assert_eq!(s.get_fg_color(), Some(Color::Ansi(AnsiColor::Cyan)));
+ }
+
+ #[test]
+ #[cfg(feature = "syntax-highlighting")]
+ fn test_bash_token_style_property() {
+ // Variables (property) should be yellow dimmed
+ let style = bash_token_style("property");
+ assert!(style.is_some());
+ let s = style.unwrap();
+ assert_eq!(s.get_fg_color(), Some(Color::Ansi(AnsiColor::Yellow)));
+ }
+
+ #[test]
+ #[cfg(feature = "syntax-highlighting")]
+ fn test_bash_token_style_number() {
+ // Numbers should be yellow dimmed
+ let style = bash_token_style("number");
+ assert!(style.is_some());
+ let s = style.unwrap();
+ assert_eq!(s.get_fg_color(), Some(Color::Ansi(AnsiColor::Yellow)));
+ }
+
+ #[test]
+ #[cfg(feature = "syntax-highlighting")]
+ fn test_bash_token_style_constant() {
+ // Constants/flags should be cyan dimmed
+ let style = bash_token_style("constant");
+ assert!(style.is_some());
+ let s = style.unwrap();
+ assert_eq!(s.get_fg_color(), Some(Color::Ansi(AnsiColor::Cyan)));
+ }
+
+ #[test]
+ #[cfg(feature = "syntax-highlighting")]
+ fn test_bash_token_style_unknown() {
+ // Unknown tokens should return None
+ assert!(bash_token_style("unknown").is_none());
+ assert!(bash_token_style("comment").is_none());
+ assert!(bash_token_style("embedded").is_none());
+ }
+
+ #[test]
+ fn test_toml_token_style_string() {
+ // Strings should be green
+ let style = toml_token_style("string");
+ assert!(style.is_some());
+ let s = style.unwrap();
+ assert_eq!(s.get_fg_color(), Some(Color::Ansi(AnsiColor::Green)));
+ }
+
+ #[test]
+ fn test_toml_token_style_comment() {
+ // Comments should be dimmed
+ let style = toml_token_style("comment");
+ assert!(style.is_some());
+ }
+
+ #[test]
+ fn test_toml_token_style_table() {
+ // Table headers should be cyan bold
+ let style = toml_token_style("table");
+ assert!(style.is_some());
+ let s = style.unwrap();
+ assert_eq!(s.get_fg_color(), Some(Color::Ansi(AnsiColor::Cyan)));
+ }
+
+ #[test]
+ fn test_toml_token_style_boolean() {
+ // Booleans should be yellow
+ let style = toml_token_style("boolean");
+ assert!(style.is_some());
+ let s = style.unwrap();
+ assert_eq!(s.get_fg_color(), Some(Color::Ansi(AnsiColor::Yellow)));
+ }
+
+ #[test]
+ fn test_toml_token_style_digit() {
+ // Digits should be yellow
+ let style = toml_token_style("digit");
+ assert!(style.is_some());
+ let s = style.unwrap();
+ assert_eq!(s.get_fg_color(), Some(Color::Ansi(AnsiColor::Yellow)));
+ }
+
+ #[test]
+ fn test_toml_token_style_unknown() {
+ // Unknown tokens should return None
+ assert!(toml_token_style("unknown").is_none());
+ assert!(toml_token_style("key").is_none());
+ assert!(toml_token_style("operator").is_none());
+ }
+
+ #[test]
+ fn test_format_toml_basic() {
+ let content = "[section]\nkey = \"value\"";
+ let result = format_toml(content, "");
+ // Should contain the original content (highlighted or not)
+ assert!(result.contains("section"));
+ assert!(result.contains("key"));
+ assert!(result.contains("value"));
+ // Should have multiple lines (one per input line)
+ assert!(result.lines().count() >= 2);
+ }
+
+ #[test]
+ fn test_format_toml_with_margin() {
+ let content = "key = true";
+ let result = format_toml(content, " ");
+ // Should have margin prefix
+ assert!(result.starts_with(" "));
+ assert!(result.contains("key"));
+ assert!(result.contains("true"));
+ }
+
+ #[test]
+ fn test_format_toml_multiline() {
+ let content = "[table]\nkey1 = \"value1\"\nkey2 = 42\n# comment\nkey3 = false";
+ let result = format_toml(content, "");
+ // Each line should be present
+ assert!(result.contains("table"));
+ assert!(result.contains("key1"));
+ assert!(result.contains("key2"));
+ assert!(result.contains("key3"));
+ assert!(result.contains("comment"));
+ }
+
+ #[test]
+ fn test_format_toml_empty() {
+ let content = "";
+ let result = format_toml(content, "");
+ // Empty content should produce empty output (or just newlines)
+ assert!(result.is_empty() || result.trim().is_empty() || result == "\n");
+ }
+}
diff --git a/src/styling/line.rs b/src/styling/line.rs
index b9eadadc5..8650422ab 100644
--- a/src/styling/line.rs
+++ b/src/styling/line.rs
@@ -243,4 +243,150 @@ mod tests {
assert_eq!(visible_width(&out), 1);
assert!(out.ends_with("\u{1b}[0m"));
}
+
+ #[test]
+ fn test_truncate_visible_zero_width() {
+ let text = "hello world";
+ let out = truncate_visible(text, 0, "…");
+ assert!(out.is_empty(), "Zero width should return empty string");
+ }
+
+ #[test]
+ fn test_truncate_visible_no_truncation_needed() {
+ let text = "short";
+ let out = truncate_visible(text, 100, "…");
+ assert_eq!(out, text, "No truncation should return original string");
+ }
+
+ #[test]
+ fn test_truncate_visible_zero_budget() {
+ // When max_width equals ellipsis width, budget becomes 0
+ let text = "hello";
+ let out = truncate_visible(text, 1, "…");
+ assert!(
+ visible_width(&out) <= 1,
+ "Output should be within max_width"
+ );
+ }
+
+ #[test]
+ fn test_styled_string_raw() {
+ let s = StyledString::raw("test");
+ assert_eq!(s.text, "test");
+ assert!(s.style.is_none());
+ }
+
+ #[test]
+ fn test_styled_string_styled() {
+ let style = Style::new().bold();
+ let s = StyledString::styled("test", style);
+ assert_eq!(s.text, "test");
+ assert!(s.style.is_some());
+ }
+
+ #[test]
+ fn test_styled_string_render_raw() {
+ let s = StyledString::raw("test");
+ assert_eq!(s.render(), "test");
+ }
+
+ #[test]
+ fn test_styled_string_render_styled() {
+ let style = Style::new().bold();
+ let s = StyledString::styled("test", style);
+ let rendered = s.render();
+ assert!(rendered.contains("test"));
+ // Should have escape codes for bold
+ assert!(rendered.starts_with("\u{1b}["));
+ }
+
+ #[test]
+ fn test_styled_line_push_methods() {
+ let mut line = StyledLine::new();
+ line.push_raw("hello");
+ line.push_styled(" world", Style::new().bold());
+ line.push(StyledString::raw("!"));
+
+ assert_eq!(line.segments.len(), 3);
+ assert_eq!(line.width(), 12); // "hello world!" = 12
+ }
+
+ #[test]
+ fn test_styled_line_extend() {
+ let mut line1 = StyledLine::new();
+ line1.push_raw("hello");
+
+ let mut line2 = StyledLine::new();
+ line2.push_raw(" world");
+
+ line1.extend(line2);
+ assert_eq!(line1.segments.len(), 2);
+ assert_eq!(line1.plain_text(), "hello world");
+ }
+
+ #[test]
+ fn test_styled_line_pad_to() {
+ let mut line = StyledLine::new();
+ line.push_raw("hi");
+ assert_eq!(line.width(), 2);
+
+ line.pad_to(5);
+ assert_eq!(line.width(), 5);
+ assert!(line.plain_text().ends_with(" ")); // 3 spaces added
+ }
+
+ #[test]
+ fn test_styled_line_pad_to_no_padding_needed() {
+ let mut line = StyledLine::new();
+ line.push_raw("hello");
+ let original_width = line.width();
+
+ line.pad_to(3); // Target is less than current width
+ assert_eq!(line.width(), original_width); // Should not change
+ }
+
+ #[test]
+ fn test_styled_line_render() {
+ let mut line = StyledLine::new();
+ line.push_raw("a");
+ line.push_styled("b", Style::new().bold());
+ line.push_raw("c");
+
+ let rendered = line.render();
+ assert!(rendered.contains("a"));
+ assert!(rendered.contains("b"));
+ assert!(rendered.contains("c"));
+ }
+
+ #[test]
+ fn test_styled_line_plain_text() {
+ let mut line = StyledLine::new();
+ line.push_raw("hello");
+ line.push_styled(" world", Style::new().bold());
+
+ assert_eq!(line.plain_text(), "hello world");
+ }
+
+ #[test]
+ fn test_styled_line_truncate_to_width_no_truncation() {
+ let mut line = StyledLine::new();
+ line.push_raw("hello");
+ let truncated = line.clone().truncate_to_width(100);
+ assert_eq!(truncated.plain_text(), "hello");
+ }
+
+ #[test]
+ fn test_styled_line_truncate_to_width_truncates() {
+ let mut line = StyledLine::new();
+ line.push_raw("hello world this is a long message");
+ let truncated = line.truncate_to_width(10);
+ assert!(truncated.width() <= 10);
+ }
+
+ #[test]
+ fn test_styled_line_default() {
+ let line = StyledLine::default();
+ assert!(line.segments.is_empty());
+ assert_eq!(line.width(), 0);
+ }
}