Skip to content

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

refactor(tests): replace multi-assert with inline snapshots (#1382)

Maximilian Roos4ce07c1adca2
diff --git a/CLAUDE.md b/CLAUDE.md
index d2d8aedc3..7a5fba15c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -53,6 +53,8 @@ Key skills:
## Testing
+See `tests/CLAUDE.md` for test infrastructure, assertion style, and test granularity guidelines.
+
### Running Tests
```bash
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index ccd7e5dc9..205875eee 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -332,39 +332,14 @@ mod tests {
}
#[test]
- fn test_parse_missing_name() {
- let err = parse(&[]).unwrap_err();
- assert!(err.to_string().contains("Missing alias name"));
- }
-
- #[test]
- fn test_parse_var_missing_value() {
- let err = parse(&["deploy", "--var"]).unwrap_err();
- assert!(err.to_string().contains("--var requires a KEY=VALUE"));
- }
-
- #[test]
- fn test_parse_var_no_equals() {
- let err = parse(&["deploy", "--var", "noequals"]).unwrap_err();
- assert!(err.to_string().contains("KEY=VALUE"));
- }
-
- #[test]
- fn test_parse_unknown_flag() {
- let err = parse(&["deploy", "--verbose"]).unwrap_err();
- assert!(err.to_string().contains("Unexpected argument '--verbose'"));
- }
-
- #[test]
- fn test_parse_positional_arg_rejected() {
- let err = parse(&["deploy", "arg1"]).unwrap_err();
- assert!(err.to_string().contains("Unexpected argument 'arg1'"));
- }
-
- #[test]
- fn test_parse_var_empty_key_rejected() {
- let err = parse(&["deploy", "--var", "=value"]).unwrap_err();
- assert!(err.to_string().contains("--var key must not be empty"));
+ fn test_parse_errors() {
+ use insta::assert_snapshot;
+ assert_snapshot!(parse(&[]).unwrap_err(), @"Missing alias name");
+ assert_snapshot!(parse(&["deploy", "--var"]).unwrap_err(), @"--var requires a KEY=VALUE argument");
+ assert_snapshot!(parse(&["deploy", "--var", "noequals"]).unwrap_err(), @"--var value must be KEY=VALUE");
+ assert_snapshot!(parse(&["deploy", "--verbose"]).unwrap_err(), @"Unexpected argument '--verbose' for alias 'deploy'");
+ assert_snapshot!(parse(&["deploy", "arg1"]).unwrap_err(), @"Unexpected argument 'arg1' for alias 'deploy'");
+ assert_snapshot!(parse(&["deploy", "--var", "=value"]).unwrap_err(), @"--var key must not be empty (got '=value')");
}
#[test]
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index ae75c2f10..9acf743e2 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -238,24 +238,17 @@ mod tests {
use super::*;
#[test]
- fn test_format_message_for_display_single_line() {
+ fn test_format_message_for_display() {
+ use insta::assert_snapshot;
let config = CommitGenerationConfig::default();
let generator = CommitGenerator::new(&config);
- let result = generator.format_message_for_display("Simple commit message");
- // Should contain the message text with styling
- assert!(result.contains("Simple commit message"));
- // Should be styled (output differs from plain input)
- assert!(result.len() > "Simple commit message".len());
- }
- #[test]
- fn test_format_message_for_display_multiline() {
- let config = CommitGenerationConfig::default();
- let generator = CommitGenerator::new(&config);
- let result = generator.format_message_for_display("First line\nSecond line\nThird line");
- assert!(result.contains("First line"));
- assert!(result.contains("Second line"));
- assert!(result.contains("Third line"));
+ assert_snapshot!(generator.format_message_for_display("Simple commit message"), @"Simple commit message");
+ assert_snapshot!(generator.format_message_for_display("First line\nSecond line\nThird line"), @"
+ First line
+ Second line
+ Third line
+ ");
}
#[test]
diff --git a/src/commands/config/mod.rs b/src/commands/config/mod.rs
index fff04eba2..e613b47cc 100644
--- a/src/commands/config/mod.rs
+++ b/src/commands/config/mod.rs
@@ -22,6 +22,7 @@ pub use update::handle_config_update;
mod tests {
use std::collections::HashMap;
+ use insta::assert_snapshot;
use worktrunk::config::{ProjectConfig, UserConfig};
use super::create::comment_out_config;
@@ -31,91 +32,78 @@ mod tests {
// ==================== comment_out_config tests ====================
#[test]
- fn test_comment_out_config_basic() {
- let input = "key = \"value\"\n";
- let expected = "# key = \"value\"\n";
- assert_eq!(comment_out_config(input), expected);
- }
+ fn test_comment_out_config() {
+ // Basic key-value
+ assert_snapshot!(comment_out_config("key = \"value\"\n"), @r#"# key = "value""#);
- #[test]
- fn test_comment_out_config_preserves_existing_comments() {
- let input = "# This is a comment\nkey = \"value\"\n";
- let expected = "# This is a comment\n# key = \"value\"\n";
- assert_eq!(comment_out_config(input), expected);
- }
+ // Preserves existing comments
+ assert_snapshot!(comment_out_config("# This is a comment\nkey = \"value\"\n"), @r#"
+ # This is a comment
+ # key = "value"
+ "#);
- #[test]
- fn test_comment_out_config_preserves_empty_lines() {
- let input = "key1 = \"value\"\n\nkey2 = \"value\"\n";
- let expected = "# key1 = \"value\"\n\n# key2 = \"value\"\n";
- assert_eq!(comment_out_config(input), expected);
- }
+ // Preserves empty lines (not commented)
+ assert_snapshot!(comment_out_config("key1 = \"value\"\n\nkey2 = \"value\"\n"), @r#"
+ # key1 = "value"
- #[test]
- fn test_comment_out_config_preserves_trailing_newline() {
- let with_newline = "key = \"value\"\n";
- let without_newline = "key = \"value\"";
+ # key2 = "value"
+ "#);
- assert!(comment_out_config(with_newline).ends_with('\n'));
- assert!(!comment_out_config(without_newline).ends_with('\n'));
- }
+ // Section headers
+ assert_snapshot!(comment_out_config("[hooks]\ncommand = \"npm test\"\n"), @r#"
+ # [hooks]
+ # command = "npm test"
+ "#);
- #[test]
- fn test_comment_out_config_section_headers() {
- let input = "[hooks]\ncommand = \"npm test\"\n";
- let expected = "# [hooks]\n# command = \"npm test\"\n";
- assert_eq!(comment_out_config(input), expected);
- }
+ // Empty input
+ assert_snapshot!(comment_out_config(""), @"");
- #[test]
- fn test_comment_out_config_empty_input() {
- assert_eq!(comment_out_config(""), "");
- }
+ // Only empty lines
+ assert_snapshot!(comment_out_config("\n\n\n"), @"");
- #[test]
- fn test_comment_out_config_only_empty_lines() {
- let input = "\n\n\n";
- let expected = "\n\n\n";
- assert_eq!(comment_out_config(input), expected);
- }
+ // Only comments (unchanged)
+ assert_snapshot!(comment_out_config("# comment 1\n# comment 2\n"), @"
+ # comment 1
+ # comment 2
+ ");
- #[test]
- fn test_comment_out_config_only_comments() {
- let input = "# comment 1\n# comment 2\n";
- let expected = "# comment 1\n# comment 2\n";
- assert_eq!(comment_out_config(input), expected);
- }
+ // Mixed content
+ assert_snapshot!(
+ comment_out_config("# Header comment\n\n[section]\nkey = \"value\"\n\n# Another comment\nkey2 = true\n"),
+ @r#"
+ # Header comment
- #[test]
- fn test_comment_out_config_mixed_content() {
- let input =
- "# Header comment\n\n[section]\nkey = \"value\"\n\n# Another comment\nkey2 = true\n";
- let expected = "# Header comment\n\n# [section]\n# key = \"value\"\n\n# Another comment\n# key2 = true\n";
- assert_eq!(comment_out_config(input), expected);
- }
+ # [section]
+ # key = "value"
- #[test]
- fn test_comment_out_config_inline_table() {
- let input = "point = { x = 1, y = 2 }\n";
- let expected = "# point = { x = 1, y = 2 }\n";
- assert_eq!(comment_out_config(input), expected);
- }
+ # Another comment
+ # key2 = true
+ "#
+ );
- #[test]
- fn test_comment_out_config_multiline_array() {
- let input = "args = [\n \"--flag\",\n \"value\"\n]\n";
- let expected = "# args = [\n# \"--flag\",\n# \"value\"\n# ]\n";
- assert_eq!(comment_out_config(input), expected);
+ // Inline table
+ assert_snapshot!(comment_out_config("point = { x = 1, y = 2 }\n"), @"# point = { x = 1, y = 2 }");
+
+ // Multiline array
+ assert_snapshot!(comment_out_config("args = [\n \"--flag\",\n \"value\"\n]\n"), @r#"
+ # args = [
+ # "--flag",
+ # "value"
+ # ]
+ "#);
+
+ // Whitespace-only lines are not empty, so they get commented
+ assert_snapshot!(comment_out_config("key = 1\n \nkey2 = 2\n"), @"
+ # key = 1
+ #
+ # key2 = 2
+ ");
}
#[test]
- fn test_comment_out_config_whitespace_only_line() {
- // Lines with only whitespace are not empty - they should NOT be commented
- // Actually, let's check what the current behavior is:
- // The function checks `!line.is_empty()` - a line with spaces is not empty
- let input = "key = 1\n \nkey2 = 2\n";
- let expected = "# key = 1\n# \n# key2 = 2\n";
- assert_eq!(comment_out_config(input), expected);
+ fn test_comment_out_config_preserves_trailing_newline() {
+ assert!(comment_out_config("key = \"value\"\n").ends_with('\n'));
+ assert!(!comment_out_config("key = \"value\"").ends_with('\n'));
}
// ==================== warn_unknown_keys tests ====================
@@ -127,19 +115,16 @@ mod tests {
}
#[test]
- fn test_warn_unknown_keys_single() {
+ fn test_warn_unknown_keys() {
+ // Single unknown key
let mut unknown = HashMap::new();
unknown.insert(
"unknown-key".to_string(),
toml::Value::String("value".to_string()),
);
- let out = warn_unknown_keys::<UserConfig>(&unknown);
- assert!(out.contains("unknown-key"));
- assert!(out.contains("Unknown"));
- }
+ assert_snapshot!(warn_unknown_keys::<UserConfig>(&unknown), @"β–² Unknown key unknown-key will be ignored");
- #[test]
- fn test_warn_unknown_keys_multiple() {
+ // Multiple unknown keys (output is sorted deterministically)
let mut unknown = HashMap::new();
unknown.insert(
"key1".to_string(),
@@ -149,29 +134,25 @@ mod tests {
"key2".to_string(),
toml::Value::String("value2".to_string()),
);
- let out = warn_unknown_keys::<UserConfig>(&unknown);
- assert!(out.contains("key1"));
- assert!(out.contains("key2"));
+ assert_snapshot!(warn_unknown_keys::<UserConfig>(&unknown), @"
+ β–² Unknown key key1 will be ignored
+ β–² Unknown key key2 will be ignored
+ ");
}
#[test]
fn test_warn_unknown_keys_suggests_other_config() {
- // Test: commit-generation in project config should suggest user config
+ // commit-generation in project config should suggest user config
let mut unknown = HashMap::new();
- // Build a commit-generation table value
let mut inner = toml::map::Map::new();
inner.insert(
"command".to_string(),
toml::Value::String("claude".to_string()),
);
unknown.insert("commit-generation".to_string(), toml::Value::Table(inner));
- let out = warn_unknown_keys::<ProjectConfig>(&unknown);
- assert!(
- out.contains("user config"),
- "Should suggest user config for commit-generation in project config: {out}"
- );
+ assert_snapshot!(warn_unknown_keys::<ProjectConfig>(&unknown), @"β–² Key commit-generation belongs in user config (will be ignored)");
- // Test: ci in user config should suggest project config
+ // ci in user config should suggest project config
let mut unknown = HashMap::new();
let mut inner = toml::map::Map::new();
inner.insert(
@@ -179,51 +160,32 @@ mod tests {
toml::Value::String("github".to_string()),
);
unknown.insert("ci".to_string(), toml::Value::Table(inner));
- let out = warn_unknown_keys::<UserConfig>(&unknown);
- assert!(
- out.contains("project config"),
- "Should suggest project config for ci in user config: {out}"
- );
+ assert_snapshot!(warn_unknown_keys::<UserConfig>(&unknown), @"β–² Key ci belongs in project config (will be ignored)");
}
// ==================== render_ci_tool_status tests ====================
#[test]
- fn test_render_ci_tool_status_installed_authenticated() {
+ fn test_render_ci_tool_status() {
+ // Installed and authenticated
let mut out = String::new();
render_ci_tool_status(&mut out, "gh", "GitHub", true, true).unwrap();
- assert!(out.contains("gh"));
- assert!(out.contains("installed"));
- assert!(out.contains("authenticated"));
- }
+ assert_snapshot!(out, @"βœ“ gh installed & authenticated");
- #[test]
- fn test_render_ci_tool_status_installed_not_authenticated() {
+ // Installed but not authenticated
let mut out = String::new();
render_ci_tool_status(&mut out, "gh", "GitHub", true, false).unwrap();
- assert!(out.contains("gh"));
- assert!(out.contains("installed"));
- assert!(out.contains("not authenticated"));
- assert!(out.contains("gh auth login"));
- }
+ assert_snapshot!(out, @"β–² gh installed but not authenticated; run gh auth login");
- #[test]
- fn test_render_ci_tool_status_not_installed() {
+ // Not installed
let mut out = String::new();
render_ci_tool_status(&mut out, "glab", "GitLab", false, false).unwrap();
- assert!(out.contains("glab"));
- assert!(out.contains("not found"));
- assert!(out.contains("GitLab"));
- assert!(out.contains("CI status unavailable"));
- }
+ assert_snapshot!(out, @"↳ glab not found (GitLab CI status unavailable)");
- #[test]
- fn test_render_ci_tool_status_glab() {
+ // glab installed and authenticated
let mut out = String::new();
render_ci_tool_status(&mut out, "glab", "GitLab", true, true).unwrap();
- assert!(out.contains("glab"));
- assert!(out.contains("installed"));
- assert!(out.contains("authenticated"));
+ assert_snapshot!(out, @"βœ“ glab installed & authenticated");
}
// ==================== require_user_config_path tests ====================
diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rs
index 6b04f36e7..638141ef8 100644
--- a/src/commands/list/ci_status/mod.rs
+++ b/src/commands/list/ci_status/mod.rs
@@ -488,69 +488,28 @@ mod tests {
}
#[test]
- fn test_format_indicator_with_url() {
- let pr_with_url = PrStatus {
+ fn test_format_indicator() {
+ use insta::assert_snapshot;
+
+ let with_url = PrStatus {
ci_status: CiStatus::Passed,
source: CiSource::PullRequest,
is_stale: false,
url: Some("https://github.com/owner/repo/pull/123".to_string()),
};
-
- // Call format_indicator(true) directly
- let formatted = pr_with_url.format_indicator(true);
- // Should contain OSC 8 hyperlink escape sequences
- assert!(formatted.contains("\x1b]8;;"));
- assert!(formatted.contains("https://github.com/owner/repo/pull/123"));
- assert!(formatted.contains("●"));
- }
-
- #[test]
- fn test_format_indicator_without_url() {
- let pr_no_url = PrStatus {
+ let no_url = PrStatus {
ci_status: CiStatus::Passed,
source: CiSource::PullRequest,
is_stale: false,
url: None,
};
- // Call format_indicator(true) directly
- let formatted = pr_no_url.format_indicator(true);
- // Should NOT contain OSC 8 hyperlink
- assert!(
- !formatted.contains("\x1b]8;;"),
- "Should not contain OSC 8 sequences"
- );
- assert!(formatted.contains("●"));
- }
-
- #[test]
- fn test_format_indicator_skips_link() {
- // When include_link=false, should not include OSC 8 even when URL is present
- let pr_with_url = PrStatus {
- ci_status: CiStatus::Passed,
- source: CiSource::PullRequest,
- is_stale: false,
- url: Some("https://github.com/owner/repo/pull/123".to_string()),
- };
-
- let with_link = pr_with_url.format_indicator(true);
- let without_link = pr_with_url.format_indicator(false);
-
- // With link should contain OSC 8
- assert!(
- with_link.contains("\x1b]8;;"),
- "include_link=true should contain OSC 8"
- );
-
- // Without link should NOT contain OSC 8
- assert!(
- !without_link.contains("\x1b]8;;"),
- "include_link=false should not contain OSC 8"
- );
-
- // Both should contain the indicator
- assert!(with_link.contains("●"), "Should contain indicator");
- assert!(without_link.contains("●"), "Should contain indicator");
+ // With URL + include_link=true β†’ has OSC 8 hyperlink
+ assert_snapshot!(with_url.format_indicator(true), @r"]8;;https://github.com/owner/repo/pull/123\●]8;;\");
+ // With URL + include_link=false β†’ no OSC 8
+ assert_snapshot!(with_url.format_indicator(false), @"●");
+ // No URL + include_link=true β†’ no OSC 8
+ assert_snapshot!(no_url.format_indicator(true), @"●");
}
#[test]
@@ -563,17 +522,7 @@ mod tests {
}
#[test]
- fn test_pr_status_style_and_format() {
- let status = PrStatus {
- ci_status: CiStatus::Passed,
- source: CiSource::PullRequest,
- is_stale: false,
- url: None,
- };
- // Call format_indicator directly
- let formatted = status.format_indicator(false);
- assert!(formatted.contains("●"));
-
+ fn test_pr_status_style() {
// Stale status gets dimmed
let stale = PrStatus {
ci_status: CiStatus::Running,
diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rs
index f1b3848b1..aa6038fb5 100644
--- a/src/commands/list/json_output.rs
+++ b/src/commands/list/json_output.rs
@@ -462,6 +462,8 @@ pub fn to_json_items(items: &[ListItem]) -> Vec<JsonItem> {
#[cfg(test)]
mod tests {
+ use insta::assert_snapshot;
+
use super::*;
use crate::commands::list::ci_status::CiStatus;
use crate::commands::list::model::{
@@ -475,24 +477,19 @@ mod tests {
#[test]
fn test_json_diff_from_line_diff() {
- let line_diff = LineDiff {
+ let nonzero = JsonDiff::from(LineDiff {
added: 10,
deleted: 5,
- };
- let json_diff = JsonDiff::from(line_diff);
- assert_eq!(json_diff.added, 10);
- assert_eq!(json_diff.deleted, 5);
- }
+ });
+ assert_eq!(nonzero.added, 10);
+ assert_eq!(nonzero.deleted, 5);
- #[test]
- fn test_json_diff_from_line_diff_zeros() {
- let line_diff = LineDiff {
+ let zeros = JsonDiff::from(LineDiff {
added: 0,
deleted: 0,
- };
- let json_diff = JsonDiff::from(line_diff);
- assert_eq!(json_diff.added, 0);
- assert_eq!(json_diff.deleted, 0);
+ });
+ assert_eq!(zeros.added, 0);
+ assert_eq!(zeros.deleted, 0);
}
// ============================================================================
@@ -500,84 +497,50 @@ mod tests {
// ============================================================================
#[test]
- fn test_json_ci_from_passed() {
- let pr = PrStatus {
+ fn test_json_ci_from_pr_status() {
+ // Full field mapping with URL
+ let passed = JsonCi::from(&PrStatus {
ci_status: CiStatus::Passed,
source: CiSource::PullRequest,
is_stale: false,
url: Some("https://github.com/org/repo/pull/123".to_string()),
- };
- let json = JsonCi::from(&pr);
- assert_eq!(json.status, "passed");
- assert_eq!(json.source, CiSource::PullRequest);
- assert!(!json.stale);
+ });
+ assert_eq!(passed.status, "passed");
+ assert_eq!(passed.source, CiSource::PullRequest);
+ assert!(!passed.stale);
assert_eq!(
- json.url,
+ passed.url,
Some("https://github.com/org/repo/pull/123".to_string())
);
- }
- #[test]
- fn test_json_ci_from_failed_branch() {
- let pr = PrStatus {
+ // Stale branch with no URL
+ let failed = JsonCi::from(&PrStatus {
ci_status: CiStatus::Failed,
source: CiSource::Branch,
is_stale: true,
url: None,
- };
- let json = JsonCi::from(&pr);
- assert_eq!(json.status, "failed");
- assert_eq!(json.source, CiSource::Branch);
- assert!(json.stale);
- assert!(json.url.is_none());
- }
-
- #[test]
- fn test_json_ci_from_running() {
- let pr = PrStatus {
- ci_status: CiStatus::Running,
- source: CiSource::PullRequest,
- is_stale: false,
- url: None,
- };
- let json = JsonCi::from(&pr);
- assert_eq!(json.status, "running");
- }
-
- #[test]
- fn test_json_ci_from_conflicts() {
- let pr = PrStatus {
- ci_status: CiStatus::Conflicts,
- source: CiSource::PullRequest,
- is_stale: false,
- url: None,
- };
- let json = JsonCi::from(&pr);
- assert_eq!(json.status, "conflicts");
- }
-
- #[test]
- fn test_json_ci_from_no_ci() {
- let pr = PrStatus {
- ci_status: CiStatus::NoCI,
- source: CiSource::Branch,
- is_stale: false,
- url: None,
- };
- let json = JsonCi::from(&pr);
- assert_eq!(json.status, "no-ci");
- }
-
- #[test]
- fn test_json_ci_from_error() {
- let pr = PrStatus {
- ci_status: CiStatus::Error,
- source: CiSource::Branch,
- is_stale: false,
- url: None,
- };
- let json = JsonCi::from(&pr);
- assert_eq!(json.status, "error");
+ });
+ assert_eq!(failed.status, "failed");
+ assert_eq!(failed.source, CiSource::Branch);
+ assert!(failed.stale);
+ assert!(failed.url.is_none());
+
+ // All status string mappings
+ let status_mappings = [
+ (CiStatus::Running, "running"),
+ (CiStatus::Conflicts, "conflicts"),
+ (CiStatus::NoCI, "no-ci"),
+ (CiStatus::Error, "error"),
+ ];
+ for (ci_status, expected) in status_mappings {
+ let json = JsonCi::from(&PrStatus {
+ ci_status,
+ source: CiSource::Branch,
+ is_stale: false,
+ url: None,
+ });
+ assert_eq!(json.status, expected);
+ }
}
// ============================================================================
@@ -732,84 +695,58 @@ mod tests {
#[test]
fn test_format_raw_symbols_empty() {
let symbols = StatusSymbols::default();
- let result = format_raw_symbols(&symbols);
- assert!(result.is_empty());
+ assert!(format_raw_symbols(&symbols).is_empty());
}
#[test]
- fn test_format_raw_symbols_working_tree() {
- let symbols = StatusSymbols {
+ fn test_format_raw_symbols_each_category() {
+ let working_tree = format_raw_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('?'));
- }
+ });
+ assert_snapshot!(working_tree, @"+!?");
- #[test]
- fn test_format_raw_symbols_main_state() {
- let symbols = StatusSymbols {
+ let main_state = format_raw_symbols(&StatusSymbols {
main_state: MainState::Ahead,
..Default::default()
- };
- let result = format_raw_symbols(&symbols);
- assert!(result.contains('↑'));
- }
+ });
+ assert_snapshot!(main_state, @"↑");
- #[test]
- fn test_format_raw_symbols_upstream_divergence() {
- let symbols = StatusSymbols {
+ let upstream = format_raw_symbols(&StatusSymbols {
upstream_divergence: Divergence::Behind,
..Default::default()
- };
- let result = format_raw_symbols(&symbols);
- assert!(result.contains('⇣'));
- }
+ });
+ assert_snapshot!(upstream, @"⇣");
- #[test]
- fn test_format_raw_symbols_operation_state() {
- let symbols = StatusSymbols {
+ // Operation state takes priority over worktree state
+ let operation = format_raw_symbols(&StatusSymbols {
operation_state: OperationState::Rebase,
..Default::default()
- };
- let result = format_raw_symbols(&symbols);
- assert!(result.contains('‴'));
- }
+ });
+ assert_snapshot!(operation, @"‴");
- #[test]
- fn test_format_raw_symbols_worktree_state() {
- let symbols = StatusSymbols {
+ let worktree = format_raw_symbols(&StatusSymbols {
worktree_state: WorktreeState::Locked,
..Default::default()
- };
- let result = format_raw_symbols(&symbols);
- assert!(result.contains('⊞'));
- }
+ });
+ assert_snapshot!(worktree, @"⊞");
- #[test]
- fn test_format_raw_symbols_user_marker() {
- let symbols = StatusSymbols {
- user_marker: Some("πŸ”₯".to_string()),
+ let marker = format_raw_symbols(&StatusSymbols {
+ user_marker: Some("\u{1f525}".to_string()),
..Default::default()
- };
- let result = format_raw_symbols(&symbols);
- assert!(result.contains("πŸ”₯"));
+ });
+ assert_snapshot!(marker, @"πŸ”₯");
}
#[test]
fn test_format_raw_symbols_combined() {
- let symbols = StatusSymbols {
+ let result = format_raw_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('⇑'));
+ });
+ assert_snapshot!(result, @"+↓⇑");
}
// ============================================================================
@@ -817,22 +754,24 @@ mod tests {
// ============================================================================
#[test]
- fn test_json_commit_serialization() {
- let commit = JsonCommit {
+ fn test_json_serialization() {
+ let commit = serde_json::to_string_pretty(&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"));
- }
+ })
+ .unwrap();
+ assert_snapshot!(commit, @r#"
+ {
+ "sha": "abc123def456",
+ "short_sha": "abc123d",
+ "message": "Fix bug",
+ "timestamp": 1700000000
+ }
+ "#);
- #[test]
- fn test_json_working_tree_serialization() {
- let wt = JsonWorkingTree {
+ let working_tree = serde_json::to_string_pretty(&JsonWorkingTree {
staged: true,
modified: false,
untracked: true,
@@ -842,51 +781,71 @@ mod tests {
added: 10,
deleted: 5,
}),
- };
- let json = serde_json::to_string(&wt).unwrap();
- assert!(json.contains("\"staged\":true"));
- assert!(json.contains("\"modified\":false"));
- assert!(json.contains("\"added\":10"));
- }
+ })
+ .unwrap();
+ assert_snapshot!(working_tree, @r#"
+ {
+ "staged": true,
+ "modified": false,
+ "untracked": true,
+ "renamed": false,
+ "deleted": false,
+ "diff": {
+ "added": 10,
+ "deleted": 5
+ }
+ }
+ "#);
- #[test]
- fn test_json_main_serialization() {
- let main = JsonMain {
+ let main = serde_json::to_string_pretty(&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"));
- }
+ })
+ .unwrap();
+ assert_snapshot!(main, @r#"
+ {
+ "ahead": 3,
+ "behind": 1,
+ "diff": {
+ "added": 50,
+ "deleted": 20
+ }
+ }
+ "#);
- #[test]
- fn test_json_remote_serialization() {
- let remote = JsonRemote {
+ let remote = serde_json::to_string_pretty(&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\""));
- }
+ })
+ .unwrap();
+ assert_snapshot!(remote, @r#"
+ {
+ "name": "origin",
+ "branch": "feature",
+ "ahead": 2,
+ "behind": 0
+ }
+ "#);
- #[test]
- fn test_json_worktree_serialization() {
- let wt = JsonWorktree {
+ let worktree = serde_json::to_string_pretty(&JsonWorktree {
state: Some("locked"),
reason: Some("manual".to_string()),
detached: false,
- };
- let json = serde_json::to_string(&wt).unwrap();
- assert!(json.contains("\"state\":\"locked\""));
- assert!(json.contains("\"reason\":\"manual\""));
+ })
+ .unwrap();
+ assert_snapshot!(worktree, @r#"
+ {
+ "state": "locked",
+ "reason": "manual",
+ "detached": false
+ }
+ "#);
}
#[test]
@@ -909,14 +868,20 @@ mod tests {
#[test]
fn test_json_ci_serialization() {
- let ci = JsonCi {
+ let json = serde_json::to_string_pretty(&JsonCi {
status: "passed",
source: CiSource::PullRequest,
stale: false,
url: Some("https://example.com".to_string()),
- };
- let json = serde_json::to_string(&ci).unwrap();
- assert!(json.contains("\"status\":\"passed\""));
- assert!(json.contains("\"source\":\"pr\""));
+ })
+ .unwrap();
+ assert_snapshot!(json, @r#"
+ {
+ "status": "passed",
+ "source": "pr",
+ "stale": false,
+ "url": "https://example.com"
+ }
+ "#);
}
}
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index 67d2aceaf..452372ddd 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -456,45 +456,20 @@ mod tests {
}
#[test]
- fn test_format_summary_message_no_errors() {
- let msg = format_summary_message(&[], false, 0, 0, 0);
- assert!(msg.contains("Showing 0 worktrees"));
- assert!(!msg.contains("failed"));
- assert!(!msg.contains("timed out"));
- }
-
- #[test]
- fn test_format_summary_message_all_timeouts() {
- // 3 errors, all timeouts
- let msg = format_summary_message(&[], false, 0, 3, 3);
- assert!(msg.contains("3 tasks timed out"));
- assert!(!msg.contains("failed"));
- }
-
- #[test]
- fn test_format_summary_message_mixed_errors() {
- // 5 errors, 3 are timeouts
- let msg = format_summary_message(&[], false, 0, 5, 3);
- assert!(msg.contains("5 tasks failed (3 timed out)"));
- }
-
- #[test]
- fn test_format_summary_message_no_timeouts() {
- // 2 errors, none are timeouts
- let msg = format_summary_message(&[], false, 0, 2, 0);
- assert!(msg.contains("2 tasks failed"));
- assert!(!msg.contains("timed out"));
- }
-
- #[test]
- fn test_format_summary_message_single_error() {
- let msg = format_summary_message(&[], false, 0, 1, 0);
- assert!(msg.contains("1 task failed"));
- }
-
- #[test]
- fn test_format_summary_message_single_timeout() {
- let msg = format_summary_message(&[], false, 0, 1, 1);
- assert!(msg.contains("1 task timed out"));
+ fn test_format_summary_message_error_variants() {
+ use insta::assert_snapshot;
+
+ // No errors
+ assert_snapshot!(format_summary_message(&[], false, 0, 0, 0), @"β—‹ Showing 0 worktrees");
+ // All timeouts
+ assert_snapshot!(format_summary_message(&[], false, 0, 3, 3), @"β—‹ Showing 0 worktrees. 3 tasks timed out");
+ // Mixed errors and timeouts
+ assert_snapshot!(format_summary_message(&[], false, 0, 5, 3), @"β—‹ Showing 0 worktrees. 5 tasks failed (3 timed out)");
+ // Only failures, no timeouts
+ assert_snapshot!(format_summary_message(&[], false, 0, 2, 0), @"β—‹ Showing 0 worktrees. 2 tasks failed");
+ // Single error
+ assert_snapshot!(format_summary_message(&[], false, 0, 1, 0), @"β—‹ Showing 0 worktrees. 1 task failed");
+ // Single timeout
+ assert_snapshot!(format_summary_message(&[], false, 0, 1, 1), @"β—‹ Showing 0 worktrees. 1 task timed out");
}
}
diff --git a/src/commands/list/model/state.rs b/src/commands/list/model/state.rs
index 363abab11..6b10a06e2 100644
--- a/src/commands/list/model/state.rs
+++ b/src/commands/list/model/state.rs
@@ -376,21 +376,12 @@ mod tests {
#[test]
fn test_divergence_styled() {
- // None returns None
+ use insta::assert_snapshot;
assert!(Divergence::None.styled().is_none());
-
- // Other variants return styled strings
- let styled = Divergence::InSync.styled().unwrap();
- assert!(styled.contains("|"));
-
- let styled = Divergence::Ahead.styled().unwrap();
- assert!(styled.contains("⇑"));
-
- let styled = Divergence::Behind.styled().unwrap();
- assert!(styled.contains("⇣"));
-
- let styled = Divergence::Diverged.styled().unwrap();
- assert!(styled.contains("β‡…"));
+ assert_snapshot!(Divergence::InSync.styled().unwrap(), @"|");
+ assert_snapshot!(Divergence::Ahead.styled().unwrap(), @"⇑");
+ assert_snapshot!(Divergence::Behind.styled().unwrap(), @"⇣");
+ assert_snapshot!(Divergence::Diverged.styled().unwrap(), @"⇅");
}
// ============================================================================
@@ -442,23 +433,12 @@ mod tests {
#[test]
fn test_main_state_styled() {
- // None returns None
+ use insta::assert_snapshot;
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("↑"));
-
- // Orphan is dimmed (informational, not a warning)
- let styled = MainState::Orphan.styled().unwrap();
- assert!(styled.contains("βˆ…"));
+ assert_snapshot!(MainState::WouldConflict.styled().unwrap(), @"βœ—");
+ assert_snapshot!(MainState::IsMain.styled().unwrap(), @"^");
+ assert_snapshot!(MainState::Ahead.styled().unwrap(), @"↑");
+ assert_snapshot!(MainState::Orphan.styled().unwrap(), @"βˆ…");
}
#[test]
@@ -639,19 +619,11 @@ mod tests {
#[test]
fn test_operation_state_styled() {
- // None returns None
+ use insta::assert_snapshot;
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("‡"));
+ assert_snapshot!(OperationState::Conflicts.styled().unwrap(), @"✘");
+ assert_snapshot!(OperationState::Rebase.styled().unwrap(), @"‴");
+ assert_snapshot!(OperationState::Merge.styled().unwrap(), @"‡");
}
#[test]
diff --git a/src/commands/list/model/status_symbols.rs b/src/commands/list/model/status_symbols.rs
index 2516f196e..538f07096 100644
--- a/src/commands/list/model/status_symbols.rs
+++ b/src/commands/list/model/status_symbols.rs
@@ -319,6 +319,8 @@ impl StatusSymbols {
#[cfg(test)]
mod tests {
+ use insta::assert_snapshot;
+
use super::*;
#[test]
@@ -432,8 +434,7 @@ mod tests {
main_state: MainState::Ahead,
..Default::default()
};
- let compact = symbols.format_compact();
- assert!(compact.contains("↑"));
+ assert_snapshot!(symbols.format_compact(), @"↑");
// Multiple symbols
let symbols = StatusSymbols {
@@ -441,10 +442,7 @@ mod tests {
main_state: MainState::Ahead,
..Default::default()
};
- let compact = symbols.format_compact();
- assert!(compact.contains("+"));
- assert!(compact.contains("!"));
- assert!(compact.contains("↑"));
+ assert_snapshot!(symbols.format_compact(), @"+!↑");
}
#[test]
@@ -454,9 +452,7 @@ mod tests {
..Default::default()
};
let rendered = symbols.render_with_mask(&PositionMask::FULL);
- // Should have fixed-width output with spacing
- assert!(!rendered.is_empty());
- assert!(rendered.contains("↑"));
+ assert_snapshot!(rendered, @" ↑");
}
#[test]
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rs
index 6959ead57..843143f0b 100644
--- a/src/commands/list/render.rs
+++ b/src/commands/list/render.rs
@@ -1175,7 +1175,7 @@ mod tests {
},
);
assert_eq!(result.width(), total);
- assert!(result.render().contains("999"));
+ insta::assert_snapshot!(result.render(), @"+999 -999");
// Case 2: Positive overflow (1000 exceeds 3 digits)
// Should show: "+1K -500" (positive with K suffix, negative normal)
@@ -1195,9 +1195,7 @@ mod tests {
},
);
assert_eq!(overflow_result.width(), total);
- let rendered = overflow_result.render();
- assert!(rendered.contains("+1") && rendered.contains('K'));
- assert!(rendered.contains("500"));
+ insta::assert_snapshot!(overflow_result.render(), @" +1K -500");
// Case 3: Negative overflow
// Should show: "+500 -1K" (positive normal, negative with K suffix)
@@ -1217,9 +1215,7 @@ mod tests {
},
);
assert_eq!(overflow_result2.width(), total);
- let rendered2 = overflow_result2.render();
- assert!(rendered2.contains("500"));
- assert!(rendered2.contains("-1") && rendered2.contains('K'));
+ insta::assert_snapshot!(overflow_result2.render(), @"+500 -1K");
// Case 4: Extreme overflow (>= 10K values show ∞ to avoid false precision)
let extreme_overflow = format_diff_like_column(
@@ -1242,9 +1238,7 @@ mod tests {
total,
"100K overflow should fit in allocated width"
);
- let extreme_rendered = extreme_overflow.render();
- assert!(extreme_rendered.contains("+∞"));
- assert!(extreme_rendered.contains("-∞"));
+ insta::assert_snapshot!(extreme_overflow.render(), @" +∞ -∞");
// Test overflow with Arrows variant (↑ and ↓)
let arrow_total = 7;
@@ -1267,9 +1261,7 @@ mod tests {
},
);
assert_eq!(arrow_overflow.width(), arrow_total);
- let arrow_rendered = arrow_overflow.render();
- assert!(arrow_rendered.contains("↑1") && arrow_rendered.contains('K'));
- assert!(arrow_rendered.contains("50"));
+ insta::assert_snapshot!(arrow_overflow.render(), @"↑1K ↓50");
// Case 6: Arrow negative overflow
// Should show with K suffix
@@ -1289,9 +1281,7 @@ mod tests {
},
);
assert_eq!(arrow_overflow2.width(), arrow_total);
- let arrow_rendered2 = arrow_overflow2.render();
- assert!(arrow_rendered2.contains("50"));
- assert!(arrow_rendered2.contains("↓1") && arrow_rendered2.contains('K'));
+ insta::assert_snapshot!(arrow_overflow2.render(), @"↑50 ↓1K");
}
#[test]
@@ -1315,7 +1305,7 @@ mod tests {
let mut item = ListItem::new_branch("abc123".into(), "feat".into());
item.summary = None;
let cell = summary_col.render_cell(&item, &mask, &main_path, 50, 40);
- assert!(cell.render().contains('β‹―'));
+ insta::assert_snapshot!(cell.render(), @"β‹―");
// Case 2: summary = Some(None) (loaded, no summary β†’ blank)
item.summary = Some(None);
@@ -1325,7 +1315,6 @@ mod tests {
// Case 3: summary = Some(Some(text)) (has summary)
item.summary = Some(Some("Add user authentication".into()));
let cell = summary_col.render_cell(&item, &mask, &main_path, 50, 40);
- let rendered = cell.render();
- assert!(rendered.contains("Add user authentication"));
+ insta::assert_snapshot!(cell.render(), @"Add user authentication");
}
}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index e4d9db7a6..e6df7fc42 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -102,27 +102,11 @@ mod tests {
use super::*;
#[test]
- fn test_format_command_label_with_name() {
- let result = format_command_label("post-create", Some("install"));
- assert!(result.contains("Running"));
- assert!(result.contains("post-create"));
- assert!(result.contains("install"));
- }
-
- #[test]
- fn test_format_command_label_without_name() {
- let result = format_command_label("pre-merge", None);
- assert_eq!(result, "Running pre-merge");
- }
-
- #[test]
- fn test_format_command_label_various_types() {
- let result = format_command_label("post-start", Some("build"));
- assert!(result.contains("post-start"));
- assert!(result.contains("build"));
-
- let result = format_command_label("pre-commit", None);
- assert!(result.contains("pre-commit"));
- assert!(!result.contains("None"));
+ fn test_format_command_label() {
+ use insta::assert_snapshot;
+ assert_snapshot!(format_command_label("post-create", Some("install")), @"Running post-create install");
+ assert_snapshot!(format_command_label("pre-merge", None), @"Running pre-merge");
+ assert_snapshot!(format_command_label("post-start", Some("build")), @"Running post-start build");
+ assert_snapshot!(format_command_label("pre-commit", None), @"Running pre-commit");
}
}
diff --git a/src/commands/process.rs b/src/commands/process.rs
index f0c3deed3..14ef9de9f 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -464,29 +464,49 @@ pub fn build_remove_command(
#[cfg(test)]
mod tests {
+ use insta::assert_snapshot;
+
use super::*;
#[test]
fn test_sanitize_for_filename() {
- // Path separators (hash suffix appended)
- assert!(sanitize_for_filename("feature/branch").starts_with("feature-branch-"));
- assert!(sanitize_for_filename("feature\\branch").starts_with("feature-branch-"));
-
- // Windows-illegal characters
- assert!(sanitize_for_filename("bug:123").starts_with("bug-123-"));
- assert!(sanitize_for_filename("fix<angle>").starts_with("fix-angle-"));
- assert!(sanitize_for_filename("fix|pipe").starts_with("fix-pipe-"));
- assert!(sanitize_for_filename("fix?question").starts_with("fix-question-"));
- assert!(sanitize_for_filename("fix*wildcard").starts_with("fix-wildcard-"));
- assert!(sanitize_for_filename("fix\"quotes\"").starts_with("fix-quotes-"));
-
- // Multiple special characters
- assert!(sanitize_for_filename("a/b\\c<d>e:f\"g|h?i*j").starts_with("a-b-c-d-e-f-g-h-i-j-"));
-
- // Already safe (still gets hash suffix)
- assert!(sanitize_for_filename("normal-branch").starts_with("normal-branch-"));
- assert!(
- sanitize_for_filename("branch_with_underscore").starts_with("branch_with_underscore-")
+ // Path separators, Windows-illegal characters, multiple special chars,
+ // already-safe names, and reserved prefix names
+ assert_snapshot!(
+ [
+ ("path separator /", sanitize_for_filename("feature/branch")),
+ ("path separator \\", sanitize_for_filename("feature\\branch")),
+ ("colon", sanitize_for_filename("bug:123")),
+ ("angle brackets", sanitize_for_filename("fix<angle>")),
+ ("pipe", sanitize_for_filename("fix|pipe")),
+ ("question mark", sanitize_for_filename("fix?question")),
+ ("wildcard", sanitize_for_filename("fix*wildcard")),
+ ("quotes", sanitize_for_filename("fix\"quotes\"")),
+ ("multiple special", sanitize_for_filename("a/b\\c<d>e:f\"g|h?i*j")),
+ ("already safe", sanitize_for_filename("normal-branch")),
+ ("underscore", sanitize_for_filename("branch_with_underscore")),
+ ("reserved prefix CONSOLE", sanitize_for_filename("CONSOLE")),
+ ("reserved prefix COM10", sanitize_for_filename("COM10")),
+ ]
+ .into_iter()
+ .map(|(label, val)| format!("{label}: {val}"))
+ .collect::<Vec<_>>()
+ .join("\n"),
+ @r"
+ path separator /: feature-branch-30k
+ path separator \: feature-branch-k37
+ colon: bug-123-4xh
+ angle brackets: fix-angle-q9m
+ pipe: fix-pipe-68k
+ question mark: fix-question-ab6
+ wildcard: fix-wildcard-38y
+ quotes: fix-quotes-2xu
+ multiple special: a-b-c-d-e-f-g-h-i-j-obi
+ already safe: normal-branch-83y
+ underscore: branch_with_underscore-b65
+ reserved prefix CONSOLE: CONSOLE-8fv
+ reserved prefix COM10: COM10-1s2
+ "
);
// Windows reserved device names are handled (produce valid filenames)
@@ -499,10 +519,6 @@ mod tests {
assert!(!result.is_empty() && result.len() > 3, "{name} -> {result}");
}
- // Longer names containing reserved prefixes are fine
- assert!(sanitize_for_filename("CONSOLE").starts_with("CONSOLE-"));
- assert!(sanitize_for_filename("COM10").starts_with("COM10-"));
-
// Collision avoidance: different inputs produce different outputs
let a = sanitize_for_filename("feature/x");
let b = sanitize_for_filename("feature-x");
@@ -537,32 +553,20 @@ mod tests {
let path = PathBuf::from("/tmp/test-worktree");
// Without branch deletion, without force
- let cmd = build_remove_command(&path, None, false);
- assert!(cmd.contains("git worktree remove"));
- assert!(cmd.contains("/tmp/test-worktree"));
- assert!(!cmd.contains("branch -D"));
- assert!(!cmd.contains("--force"));
+ assert_snapshot!(build_remove_command(&path, None, false), @"sleep 1 && git -C /tmp/test-worktree fsmonitor--daemon stop 2>/dev/null || true && git worktree remove /tmp/test-worktree");
// With branch deletion, without force
- let cmd = build_remove_command(&path, Some("feature-branch"), false);
- assert!(cmd.contains("git worktree remove"));
- assert!(cmd.contains("git branch -D"));
- assert!(cmd.contains("feature-branch"));
- assert!(!cmd.contains("--force"));
+ assert_snapshot!(build_remove_command(&path, Some("feature-branch"), false), @"sleep 1 && git -C /tmp/test-worktree fsmonitor--daemon stop 2>/dev/null || true && git worktree remove /tmp/test-worktree && git branch -D feature-branch");
// With force flag
- let cmd = build_remove_command(&path, None, true);
- assert!(cmd.contains("git worktree remove --force"));
+ assert_snapshot!(build_remove_command(&path, None, true), @"sleep 1 && git -C /tmp/test-worktree fsmonitor--daemon stop 2>/dev/null || true && git worktree remove --force /tmp/test-worktree");
// With branch deletion and force
- let cmd = build_remove_command(&path, Some("feature-branch"), true);
- assert!(cmd.contains("git worktree remove --force"));
- assert!(cmd.contains("git branch -D"));
+ assert_snapshot!(build_remove_command(&path, Some("feature-branch"), true), @"sleep 1 && git -C /tmp/test-worktree fsmonitor--daemon stop 2>/dev/null || true && git worktree remove --force /tmp/test-worktree && git branch -D feature-branch");
// Shell escaping for special characters
let special_path = PathBuf::from("/tmp/test worktree");
- let cmd = build_remove_command(&special_path, Some("feature/branch"), false);
- assert!(cmd.contains("worktree remove"));
+ assert_snapshot!(build_remove_command(&special_path, Some("feature/branch"), false), @"sleep 1 && git -C '/tmp/test worktree' fsmonitor--daemon stop 2>/dev/null || true && git worktree remove '/tmp/test worktree' && git branch -D feature/branch");
}
#[test]
@@ -593,115 +597,39 @@ mod tests {
#[test]
fn test_build_remove_command_staged() {
let staged_path = PathBuf::from("/tmp/my-project.feature.wt-removing-1234567890");
+ assert_snapshot!(build_remove_command_staged(&staged_path), @"rm -rf -- /tmp/my-project.feature.wt-removing-1234567890");
- let cmd = build_remove_command_staged(&staged_path);
- assert!(cmd.starts_with("rm -rf -- ")); // -- prevents option parsing
- assert!(cmd.contains("wt-removing-1234567890"));
- assert!(!cmd.contains("branch -D")); // Branch deleted synchronously, not in background
- assert!(!cmd.contains("sleep")); // No sleep in staged removal
-
- // Shell escaping for special characters
+ // Shell escaping for special characters (space in path)
let special_path = PathBuf::from("/tmp/test worktree.wt-removing-123");
- let cmd = build_remove_command_staged(&special_path);
- assert!(cmd.contains("rm -rf "));
- // Verify the path is escaped (single-quoted for shell safety)
- assert!(
- cmd.contains("'/tmp/test worktree.wt-removing-123'"),
- "path should be escaped: {}",
- cmd
- );
+ assert_snapshot!(build_remove_command_staged(&special_path), @"rm -rf -- '/tmp/test worktree.wt-removing-123'");
}
#[test]
- fn test_hook_log_hook_suffix() {
+ fn test_hook_log_suffix() {
use worktrunk::git::HookType;
// Suffix includes sanitized name with hash for collision avoidance
- let log = HookLog::hook(HookSource::User, HookType::PostStart, "server");
- let suffix = log.suffix();
- assert!(
- suffix.starts_with("user-post-start-server-"),
- "Expected pattern: {suffix}"
- );
-
- let log = HookLog::hook(HookSource::Project, HookType::PostCreate, "build");
- let suffix = log.suffix();
- assert!(
- suffix.starts_with("project-post-create-build-"),
- "Expected pattern: {suffix}"
- );
-
- let log = HookLog::hook(HookSource::User, HookType::PreRemove, "cleanup");
- let suffix = log.suffix();
- assert!(
- suffix.starts_with("user-pre-remove-cleanup-"),
- "Expected pattern: {suffix}"
- );
- }
-
- #[test]
- fn test_hook_log_internal_suffix() {
- let log = HookLog::internal(InternalOp::Remove);
- assert_eq!(log.suffix(), "remove");
+ // Constructor and parse produce identical suffixes
+ assert_snapshot!(HookLog::hook(HookSource::User, HookType::PostStart, "server").suffix(), @"user-post-start-server-f4t");
+ assert_snapshot!(HookLog::hook(HookSource::Project, HookType::PostCreate, "build").suffix(), @"project-post-create-build-seq");
+ assert_snapshot!(HookLog::hook(HookSource::User, HookType::PreRemove, "cleanup").suffix(), @"user-pre-remove-cleanup-non");
+ assert_snapshot!(HookLog::parse("user:post-start:server").unwrap().suffix(), @"user-post-start-server-f4t");
+ assert_snapshot!(HookLog::parse("project:post-create:build").unwrap().suffix(), @"project-post-create-build-seq");
+
+ // Internal operation suffix
+ assert_eq!(HookLog::internal(InternalOp::Remove).suffix(), "remove");
}
#[test]
fn test_hook_log_filename() {
use worktrunk::git::HookType;
- // Filenames now include hash suffixes for collision avoidance
let log = HookLog::hook(HookSource::User, HookType::PostStart, "server");
- let filename = log.filename("main");
- assert!(
- filename.starts_with("main-"),
- "Expected main- prefix: {filename}"
- );
- assert!(
- filename.contains("-user-post-start-"),
- "Expected -user-post-start-: {filename}"
- );
- assert!(
- filename.ends_with(".log"),
- "Expected .log suffix: {filename}"
- );
+ assert_snapshot!(log.filename("main"), @"main-vfz-user-post-start-server-f4t.log");
+ // Slash in branch name gets sanitized
+ assert_snapshot!(log.filename("feature/auth"), @"feature-auth-j34-user-post-start-server-f4t.log");
- let filename = log.filename("feature/auth");
- assert!(
- filename.starts_with("feature-"),
- "Expected feature- prefix (slash sanitized): {filename}"
- );
- assert!(
- filename.contains("-user-post-start-"),
- "Expected -user-post-start-: {filename}"
- );
-
- let log = HookLog::internal(InternalOp::Remove);
- let filename = log.filename("main");
- assert!(
- filename.starts_with("main-"),
- "Expected main- prefix: {filename}"
- );
- assert!(
- filename.ends_with("-remove.log"),
- "Expected -remove.log suffix: {filename}"
- );
- }
-
- #[test]
- fn test_hook_log_parse_hook() {
- let log = HookLog::parse("user:post-start:server").unwrap();
- let suffix = log.suffix();
- assert!(
- suffix.starts_with("user-post-start-server-"),
- "Expected pattern: {suffix}"
- );
-
- let log = HookLog::parse("project:post-create:build").unwrap();
- let suffix = log.suffix();
- assert!(
- suffix.starts_with("project-post-create-build-"),
- "Expected pattern: {suffix}"
- );
+ assert_snapshot!(HookLog::internal(InternalOp::Remove).filename("main"), @"main-vfz-remove.log");
}
#[test]
@@ -712,40 +640,26 @@ mod tests {
}
#[test]
- fn test_hook_log_parse_invalid_source() {
- let result = HookLog::parse("invalid:post-start:server");
- assert!(result.is_err());
- assert!(result.unwrap_err().contains("Unknown source"));
- }
+ fn test_hook_log_parse_errors() {
+ // Unknown source
+ assert_snapshot!(HookLog::parse("invalid:post-start:server").unwrap_err(), @"Unknown source: invalid. Valid: user, project");
- #[test]
- fn test_hook_log_parse_invalid_hook_type() {
- let result = HookLog::parse("user:invalid-hook:server");
- assert!(result.is_err());
- assert!(result.unwrap_err().contains("Unknown hook type"));
- }
+ // Unknown hook type
+ assert_snapshot!(HookLog::parse("user:invalid-hook:server").unwrap_err(), @"Unknown hook type: invalid-hook. Valid: pre-switch, post-create, post-start, post-switch, pre-commit, pre-merge, post-merge, pre-remove, post-remove");
- #[test]
- fn test_hook_log_parse_invalid_internal_op() {
- let result = HookLog::parse("internal:unknown");
- assert!(result.is_err());
- assert!(result.unwrap_err().contains("Unknown internal operation"));
- }
+ // Unknown internal operation
+ assert_snapshot!(HookLog::parse("internal:unknown").unwrap_err(), @"Unknown internal operation: unknown. Valid: remove");
- #[test]
- fn test_hook_log_parse_invalid_format() {
- // Single word (no colons)
- let result = HookLog::parse("remove");
- assert!(result.is_err());
- assert!(result.unwrap_err().contains("Invalid log spec"));
-
- // Two parts but not internal:op (missing hook name)
- let result = HookLog::parse("foo:bar");
- assert!(result.is_err());
-
- // Missing hook-type segment
- let result = HookLog::parse("user:");
- assert!(result.is_err());
+ // Invalid formats: single word, two non-internal parts, missing segment
+ assert_snapshot!(HookLog::parse("remove").unwrap_err(), @"Invalid log spec: remove. Format: source:hook-type:name or internal:op");
+ assert_snapshot!(HookLog::parse("foo:bar").unwrap_err(), @"Invalid log spec: foo:bar. Format: source:hook-type:name or internal:op");
+ assert_snapshot!(HookLog::parse("user:").unwrap_err(), @"Invalid log spec: user:. Format: source:hook-type:name or internal:op");
+
+ // Colons in hook names (ambiguous parsing)
+ assert_snapshot!(HookLog::parse("user:post-start:my:server").unwrap_err(), @"Invalid log spec: user:post-start:my:server. Format: source:hook-type:name or internal:op");
+
+ // Empty hook name
+ assert_snapshot!(HookLog::parse("user:post-start:").unwrap_err(), @"Invalid log spec: user:post-start:. Format: source:hook-type:name or internal:op");
}
#[test]
@@ -789,20 +703,4 @@ mod tests {
let parsed = HookLog::parse(&spec).unwrap();
assert_eq!(original, parsed);
}
-
- #[test]
- fn test_hook_log_parse_rejects_colons_in_name() {
- // Hook names cannot contain colons (would make parsing ambiguous)
- let result = HookLog::parse("user:post-start:my:server");
- assert!(result.is_err(), "Colons in hook names should be rejected");
- assert!(result.unwrap_err().contains("Invalid log spec"));
- }
-
- #[test]
- fn test_hook_log_parse_rejects_empty_name() {
- // Empty hook name should be rejected
- let result = HookLog::parse("user:post-start:");
- assert!(result.is_err(), "Empty hook name should be rejected");
- assert!(result.unwrap_err().contains("Invalid log spec"));
- }
}
diff --git a/src/commands/select/items.rs b/src/commands/select/items.rs
index e986bbac6..0ec4f1ea2 100644
--- a/src/commands/select/items.rs
+++ b/src/commands/select/items.rs
@@ -416,139 +416,90 @@ impl WorktreeSkimItem {
#[cfg(test)]
mod tests {
use super::*;
+ use insta::assert_snapshot;
#[test]
- fn test_render_preview_tabs_working_tree_mode() {
- let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::WorkingTree);
- // Tab 1 should be bold (active), tabs 2/3/4/5 dimmed
- assert!(output.contains("1: HEADΒ±"));
- assert!(output.contains("2: log"));
- assert!(output.contains("3: main…±"));
- assert!(output.contains("4: remote⇅"));
- assert!(output.contains("5: summary"));
- assert!(output.contains("Enter: switch"));
- assert!(output.contains("alt-r: remove"));
- // Verify structure: tabs on first line, controls on second
- assert!(output.contains(" | "));
- assert!(output.ends_with("\n\n"));
- }
-
- #[test]
- fn test_render_preview_tabs_log_mode() {
- let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::Log);
- assert!(output.contains("1: HEADΒ±"));
- assert!(output.contains("2: log"));
- assert!(output.contains("3: main…±"));
- assert!(output.contains("4: remote⇅"));
- assert!(output.contains("5: summary"));
- }
-
- #[test]
- fn test_render_preview_tabs_branch_diff_mode() {
- let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::BranchDiff);
- assert!(output.contains("1: HEADΒ±"));
- assert!(output.contains("2: log"));
- assert!(output.contains("3: main…±"));
- assert!(output.contains("4: remote⇅"));
- assert!(output.contains("5: summary"));
- }
-
- #[test]
- fn test_render_preview_tabs_upstream_diff_mode() {
- let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::UpstreamDiff);
- assert!(output.contains("1: HEADΒ±"));
- assert!(output.contains("2: log"));
- assert!(output.contains("3: main…±"));
- assert!(output.contains("4: remote⇅"));
- assert!(output.contains("5: summary"));
- }
-
- #[test]
- fn test_render_preview_tabs_summary_mode() {
- let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::Summary);
- assert!(output.contains("1: HEADΒ±"));
- assert!(output.contains("2: log"));
- assert!(output.contains("3: main…±"));
- assert!(output.contains("4: remote⇅"));
- assert!(output.contains("5: summary"));
+ fn test_render_preview_tabs() {
+ // All PreviewMode variants: verify tab labels, active styling, and structure
+ for (name, mode) in [
+ ("working_tree", PreviewMode::WorkingTree),
+ ("log", PreviewMode::Log),
+ ("branch_diff", PreviewMode::BranchDiff),
+ ("upstream_diff", PreviewMode::UpstreamDiff),
+ ("summary", PreviewMode::Summary),
+ ] {
+ assert_snapshot!(name, WorktreeSkimItem::render_preview_tabs(mode));
+ }
}
#[test]
- fn test_compute_summary_preview_always_shows_generating() {
- // All items show the same "Generating..." placeholder synchronously.
- // The background thread produces the correct result (which may be
- // "No changes to summarize" for the default branch).
+ fn test_compute_summary_preview() {
+ // All inputs produce the same synchronous placeholder.
+ // The background thread produces the real summary (or "No changes to summarize"
+ // for the default branch).
use crate::commands::list::model::{ItemKind, WorktreeData};
- let mut item = ListItem::new_branch("abc123".to_string(), "main".to_string());
- item.kind = ItemKind::Worktree(Box::new(WorktreeData {
+ let mut main_item = ListItem::new_branch("abc123".to_string(), "main".to_string());
+ main_item.kind = ItemKind::Worktree(Box::new(WorktreeData {
is_main: true,
..Default::default()
}));
- let output = WorktreeSkimItem::compute_summary_preview(&item);
- assert!(output.contains("Generating summary..."));
- }
-
- #[test]
- fn test_compute_summary_preview_feature_branch() {
- let item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
-
- let output = WorktreeSkimItem::compute_summary_preview(&item);
- assert!(output.contains("Generating summary..."));
- assert!(output.contains("Press 5 again"));
- }
-
- #[test]
- fn test_compute_preview_summary_mode() {
- let item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
+ let feature_item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
- let output = WorktreeSkimItem::compute_preview(&item, PreviewMode::Summary, 80, 40);
- assert!(output.contains("Generating summary..."));
+ // Direct call and compute_preview dispatch both return the placeholder
+ assert_snapshot!(
+ "direct",
+ WorktreeSkimItem::compute_summary_preview(&main_item)
+ );
+ assert_snapshot!(
+ "via_compute_preview",
+ WorktreeSkimItem::compute_preview(&feature_item, PreviewMode::Summary, 80, 40)
+ );
}
#[test]
- fn test_preview_for_mode_summary_cache_hit() {
+ fn test_preview_for_mode_summary_cache() {
+ // Cache hit returns cached content; cache miss computes the placeholder
let item = Arc::new(ListItem::new_branch(
"abc123".to_string(),
"feature".to_string(),
));
- let preview_cache: PreviewCache = Arc::new(DashMap::new());
- preview_cache.insert(
- ("feature".to_string(), PreviewMode::Summary),
- "Add auth module\n\nImplements JWT-based authentication.".to_string(),
- );
- let skim_item = WorktreeSkimItem {
- display_text: String::new(),
- display_text_with_ansi: String::new(),
- branch_name: "feature".to_string(),
- item,
- preview_cache,
+ let cache_hit = {
+ let preview_cache: PreviewCache = Arc::new(DashMap::new());
+ preview_cache.insert(
+ ("feature".to_string(), PreviewMode::Summary),
+ "Add auth module\n\nImplements JWT-based authentication.".to_string(),
+ );
+ WorktreeSkimItem {
+ display_text: String::new(),
+ display_text_with_ansi: String::new(),
+ branch_name: "feature".to_string(),
+ item: Arc::clone(&item),
+ preview_cache,
+ }
};
- let output = skim_item.preview_for_mode(PreviewMode::Summary, 80, 40);
- assert!(output.contains("Add auth module"));
- }
-
- #[test]
- fn test_preview_for_mode_summary_cache_miss() {
- let item = Arc::new(ListItem::new_branch(
- "abc123".to_string(),
- "feature".to_string(),
- ));
- let preview_cache: PreviewCache = Arc::new(DashMap::new());
-
- let skim_item = WorktreeSkimItem {
- display_text: String::new(),
- display_text_with_ansi: String::new(),
- branch_name: "feature".to_string(),
- item,
- preview_cache,
+ let cache_miss = {
+ let preview_cache: PreviewCache = Arc::new(DashMap::new());
+ WorktreeSkimItem {
+ display_text: String::new(),
+ display_text_with_ansi: String::new(),
+ branch_name: "feature".to_string(),
+ item: Arc::clone(&item),
+ preview_cache,
+ }
};
- let output = skim_item.preview_for_mode(PreviewMode::Summary, 80, 40);
- assert!(output.contains("Generating summary..."));
+ assert_snapshot!(
+ "cache_hit",
+ cache_hit.preview_for_mode(PreviewMode::Summary, 80, 40)
+ );
+ assert_snapshot!(
+ "cache_miss",
+ cache_miss.preview_for_mode(PreviewMode::Summary, 80, 40)
+ );
}
#[test]
diff --git a/src/commands/select/log_formatter.rs b/src/commands/select/log_formatter.rs
index c6e1a6542..8dd8c4232 100644
--- a/src/commands/select/log_formatter.rs
+++ b/src/commands/select/log_formatter.rs
@@ -295,6 +295,8 @@ where
#[cfg(test)]
mod tests {
+ use insta::assert_snapshot;
+
use super::*;
// format_log_output tests use dependency injection for deterministic time formatting.
@@ -326,44 +328,37 @@ mod tests {
#[test]
fn test_format_log_output_single_commit() {
- // Simulate git log output with SOH/NUL markers: * SOH full_hash NUL short_hash \x1f timestamp \x1f message
let full_hash = "abc1234567890123456789012345678901234567ab";
+
+ // With insertions and deletions
let input = format!("* \x01{}\x00abc1234\x1f1699999000\x1f Fix bug", full_hash);
let stats = stats_for(full_hash, 5, 2);
let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);
+ assert_snapshot!(output, @"* abc1234 +5 -2  1h Fix bug");
- // Should contain the hash and message
- assert!(output.contains("abc1234"));
- assert!(output.contains("Fix bug"));
- // Should contain formatted time
- assert!(output.contains("1h"));
- // Should contain stats
- assert!(output.contains("+5"), "expected +5 in output: {}", output);
+ // With graph prefix (same structure, different message)
+ let input = format!(
+ "* \x01{}\x00abc1234\x1f1699999000\x1f Commit with graph",
+ full_hash
+ );
+ let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);
+ assert_snapshot!(output, @"* abc1234 +5 -2  1h Commit with graph");
}
#[test]
fn test_format_log_output_with_stats() {
- // Commit line with pre-computed stats
let full_hash = "abc1234567890123456789012345678901234567ab";
let input = format!(
"* \x01{}\x00abc1234\x1f1699999000\x1f Add feature",
full_hash
);
- // Stats are pre-computed (accumulated from numstat lines)
let stats = stats_for(full_hash, 13, 5);
let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);
-
- // Should contain the hash and message
- assert!(output.contains("abc1234"));
- assert!(output.contains("Add feature"));
- // Verify stats are present (green +13, red -5)
- assert!(output.contains("+13"), "expected +13 in output: {}", output);
- assert!(output.contains("-5"), "expected -5 in output: {}", output);
+ assert_snapshot!(output, @"* abc1234 +13 -5  1h Add feature");
}
#[test]
fn test_format_log_output_multiple_commits() {
- // Two commits with pre-computed stats
let hash1 = "abc1234567890123456789012345678901234567ab";
let hash2 = "def5678901234567890123456789012345678901cd";
let input = format!(
@@ -373,16 +368,10 @@ mod tests {
);
let stats = multi_stats(&[(hash1, 5, 2), (hash2, 10, 3)]);
let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);
-
- // Both commits should be in output
- assert!(output.contains("abc1234"));
- assert!(output.contains("def5678"));
- assert!(output.contains("First commit"));
- assert!(output.contains("Second commit"));
-
- // Output should be two lines (one per commit)
- let lines: Vec<&str> = output.lines().collect();
- assert_eq!(lines.len(), 2, "Expected 2 lines, got: {:?}", lines);
+ assert_snapshot!(output, @"
+ * abc1234 +5 -2  1h First commit
+ * def5678 +10 -3  1h Second commit
+ ");
}
#[test]
@@ -394,7 +383,6 @@ mod tests {
#[test]
fn test_format_log_output_preserves_graph_lines() {
- // Merge commit with graph continuation line between commits
let hash1 = "abc1234567890123456789012345678901234567ab";
let hash2 = "def5678901234567890123456789012345678901cd";
let input = format!(
@@ -405,93 +393,56 @@ mod tests {
);
let stats = multi_stats(&[(hash1, 0, 0), (hash2, 5, 2)]);
let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);
-
- // Graph line should be preserved between commits
- assert!(output.contains("|\\"), "graph line should be preserved");
- assert!(output.contains("abc1234"), "first commit should be present");
- assert!(
- output.contains("def5678"),
- "second commit should be present"
- );
-
- // Verify order: merge commit, graph line, feature commit
- let lines: Vec<&str> = output.lines().collect();
- assert_eq!(lines.len(), 3, "Expected 3 lines: {:?}", lines);
- assert!(lines[0].contains("abc1234"));
- assert!(lines[1].contains("\\"));
- assert!(lines[2].contains("def5678"));
+ assert_snapshot!(output, @r"
+ * abc1234  1h Merge branch
+ |\
+ | * def5678 +5 -2  1h Feature commit
+ ");
}
#[test]
- fn test_format_log_output_no_stats() {
- // Commit without stats (not in stats map)
+ fn test_format_log_output_no_or_zero_stats() {
let full_hash = "abc1234567890123456789012345678901234567ab";
- let input = format!(
- "* \x01{}\x00abc1234\x1f1699999000\x1f Just a commit",
- full_hash
- );
- let stats = HashMap::new(); // Empty stats - shows no diff
- let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);
-
- assert!(output.contains("abc1234"));
- assert!(output.contains("Just a commit"));
- }
- #[test]
- fn test_format_log_output_with_graph_prefix() {
- // Git graph output includes graph characters
- let full_hash = "abc1234567890123456789012345678901234567ab";
+ // Not in stats map
let input = format!(
- "* \x01{}\x00abc1234\x1f1699999000\x1f Commit with graph",
+ "* \x01{}\x00abc1234\x1f1699999000\x1f Just a commit",
full_hash
);
- let stats = stats_for(full_hash, 5, 2);
+ let stats = HashMap::new();
let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);
+ assert_snapshot!(output, @"* abc1234  1h Just a commit");
- assert!(output.contains("abc1234"));
- assert!(output.contains("Commit with graph"));
- // Verify stats are present
- assert!(output.contains("+5"), "expected +5 in output: {}", output);
- assert!(output.contains("-2"), "expected -2 in output: {}", output);
- }
-
- #[test]
- fn test_format_log_output_zero_stats() {
- // Commit with zero stats (e.g., binary-only changes)
- let full_hash = "abc1234567890123456789012345678901234567ab";
+ // Zero insertions and deletions (e.g., binary-only changes)
let input = format!("* \x01{}\x00abc1234\x1f1699999000\x1f Add image", full_hash);
let stats = stats_for(full_hash, 0, 0);
let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);
-
- assert!(output.contains("abc1234"));
- assert!(output.contains("Add image"));
+ assert_snapshot!(output, @"* abc1234  1h Add image");
}
#[test]
- fn test_format_log_output_malformed_commit_line() {
- // Line without proper field delimiters passes through
- let input = "abc1234 regular commit line";
+ fn test_format_log_output_malformed() {
let stats = HashMap::new();
- let output = format_log_output_with_formatter(input, &stats, fixed_time_formatter);
- // Lines without \x1f delimiter pass through unchanged
- assert!(output.contains("abc1234"));
- }
-
- #[test]
- fn test_format_log_output_commit_line_missing_second_delimiter() {
- // Only one delimiter - malformed
- let input = "abc1234\x1f1699999000 Fix bug";
- let stats = HashMap::new();
- let output = format_log_output_with_formatter(input, &stats, fixed_time_formatter);
+ // No field delimiters - passes through unchanged
+ let output = format_log_output_with_formatter(
+ "abc1234 regular commit line",
+ &stats,
+ fixed_time_formatter,
+ );
+ assert_snapshot!(output, @"abc1234 regular commit line");
- // Should output the line as-is since it's malformed (only one \x1f)
- assert!(output.contains("abc1234"));
+ // Only one delimiter - malformed, passes through
+ let output = format_log_output_with_formatter(
+ "abc1234\x1f1699999000 Fix bug",
+ &stats,
+ fixed_time_formatter,
+ );
+ assert_snapshot!(output, @"abc1234\u{1f}1699999000 Fix bug");
}
#[test]
fn test_format_log_output_stats_only_deletions() {
- // Commit with only deletions (no insertions)
let full_hash = "abc1234567890123456789012345678901234567ab";
let input = format!(
"* \x01{}\x00abc1234\x1f1699999000\x1f Remove old code",
@@ -499,16 +450,11 @@ mod tests {
);
let stats = stats_for(full_hash, 0, 50);
let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);
-
- assert!(output.contains("abc1234"));
- assert!(output.contains("Remove old code"));
- // Should show deletions
- assert!(output.contains("-50"), "expected -50 in output: {}", output);
+ assert_snapshot!(output, @"* abc1234 -50  1h Remove old code");
}
#[test]
fn test_format_log_output_large_stats() {
- // Commit with large stats (tests K notation)
let full_hash = "abc1234567890123456789012345678901234567ab";
let input = format!(
"* \x01{}\x00abc1234\x1f1699999000\x1f Big refactor",
@@ -516,41 +462,20 @@ mod tests {
);
let stats = stats_for(full_hash, 1500, 800);
let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);
-
- assert!(output.contains("abc1234"));
- // Large numbers should use K notation
- assert!(
- output.contains("+1K") || output.contains("+1.5K"),
- "expected K notation in output: {}",
- output
- );
+ assert_snapshot!(output, @"* abc1234 +1K -800  1h Big refactor");
}
#[test]
- fn test_format_commit_line_directly() {
- // Test the format_commit_line function directly
+ fn test_format_commit_line() {
+ // Standard case: hash, stats, time, message
let commit_line = "abc1234\x1f1699999000\x1f Test commit";
- let stats = (10, 5);
- let target_width = 7; // "abc1234" is 7 chars, no padding needed
- let output = format_commit_line(commit_line, stats, target_width, &fixed_time_formatter);
-
- assert!(output.contains("abc1234"));
- assert!(output.contains("Test commit"));
- assert!(output.contains("+10"), "expected +10 in output: {}", output);
- assert!(output.contains("-5"), "expected -5 in output: {}", output);
- assert!(output.contains("1h"), "expected time in output: {}", output);
- }
+ let output = format_commit_line(commit_line, (10, 5), 7, &fixed_time_formatter);
+ assert_snapshot!(output, @"abc1234 +10 -5  1h Test commit");
- #[test]
- fn test_format_commit_line_with_padding() {
- // Test that padding aligns shorter hashes to target width
+ // With padding: shorter hash padded to target width
let commit_line = "abc12\x1f1699999000\x1f Short hash";
- let stats = (5, 2);
- let target_width = 9; // Pad "abc12" (5 chars) to 9 chars
- let output = format_commit_line(commit_line, stats, target_width, &fixed_time_formatter);
-
- // Should have 4 spaces of padding after hash before stats
- assert!(output.contains("abc12 "), "expected padding: {}", output);
+ let output = format_commit_line(commit_line, (5, 2), 9, &fixed_time_formatter);
+ assert_snapshot!(output, @"abc12 +5 -2  1h Short hash");
}
// Tests for process_log_with_dimming
diff --git a/src/commands/select/snapshots/wt__commands__select__items__tests__branch_diff.snap b/src/commands/select/snapshots/wt__commands__select__items__tests__branch_diff.snap
new file mode 100644
index 000000000..4c0ca15fc
--- /dev/null
+++ b/src/commands/select/snapshots/wt__commands__select__items__tests__branch_diff.snap
@@ -0,0 +1,6 @@
+---
+source: src/commands/select/items.rs
+expression: "WorktreeSkimItem::render_preview_tabs(mode)"
+---
+1: HEADΒ± | 2: log | 3: main…± | 4: remoteβ‡… | 5: summary
+Enter: switch | alt-c: create | alt-r: remove | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
diff --git a/src/commands/select/snapshots/wt__commands__select__items__tests__cache_hit.snap b/src/commands/select/snapshots/wt__commands__select__items__tests__cache_hit.snap
new file mode 100644
index 000000000..6d057825d
--- /dev/null
+++ b/src/commands/select/snapshots/wt__commands__select__items__tests__cache_hit.snap
@@ -0,0 +1,7 @@
+---
+source: src/commands/select/items.rs
+expression: "cache_hit.preview_for_mode(PreviewMode::Summary, 80, 40)"
+---
+Add auth module
+
+Implements JWT-based authentication.
diff --git a/src/commands/select/snapshots/wt__commands__select__items__tests__cache_miss.snap b/src/commands/select/snapshots/wt__commands__select__items__tests__cache_miss.snap
new file mode 100644
index 000000000..95571e5c6
--- /dev/null
+++ b/src/commands/select/snapshots/wt__commands__select__items__tests__cache_miss.snap
@@ -0,0 +1,7 @@
+---
+source: src/commands/select/items.rs
+expression: "cache_miss.preview_for_mode(PreviewMode::Summary, 80, 40)"
+---
+β—‹ Generating summary...
+
+Press 5 again to refresh once generation completes.
diff --git a/src/commands/select/snapshots/wt__commands__select__items__tests__direct.snap b/src/commands/select/snapshots/wt__commands__select__items__tests__direct.snap
new file mode 100644
index 000000000..37a8ca104
--- /dev/null
+++ b/src/commands/select/snapshots/wt__commands__select__items__tests__direct.snap
@@ -0,0 +1,7 @@
+---
+source: src/commands/select/items.rs
+expression: "WorktreeSkimItem::compute_summary_preview(&main_item)"
+---
+β—‹ Generating summary...
+
+Press 5 again to refresh once generation completes.
diff --git a/src/commands/select/snapshots/wt__commands__select__items__tests__log.snap b/src/commands/select/snapshots/wt__commands__select__items__tests__log.snap
new file mode 100644
index 000000000..ef283bd7f
--- /dev/null
+++ b/src/commands/select/snapshots/wt__commands__select__items__tests__log.snap
@@ -0,0 +1,6 @@
+---
+source: src/commands/select/items.rs
+expression: "WorktreeSkimItem::render_preview_tabs(mode)"
+---
+1: HEADΒ± | 2: log | 3: main…± | 4: remoteβ‡… | 5: summary
+Enter: switch | alt-c: create | alt-r: remove | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
diff --git a/src/commands/select/snapshots/wt__commands__select__items__tests__summary.snap b/src/commands/select/snapshots/wt__commands__select__items__tests__summary.snap
new file mode 100644
index 000000000..453233466
--- /dev/null
+++ b/src/commands/select/snapshots/wt__commands__select__items__tests__summary.snap
@@ -0,0 +1,6 @@
+---
+source: src/commands/select/items.rs
+expression: "WorktreeSkimItem::render_preview_tabs(mode)"
+---
+1: HEADΒ± | 2: log | 3: main…± | 4: remoteβ‡… | 5: summary
+Enter: switch | alt-c: create | alt-r: remove | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
diff --git a/src/commands/select/snapshots/wt__commands__select__items__tests__upstream_diff.snap b/src/commands/select/snapshots/wt__commands__select__items__tests__upstream_diff.snap
new file mode 100644
index 000000000..e1e1bab9b
--- /dev/null
+++ b/src/commands/select/snapshots/wt__commands__select__items__tests__upstream_diff.snap
@@ -0,0 +1,6 @@
+---
+source: src/commands/select/items.rs
+expression: "WorktreeSkimItem::render_preview_tabs(mode)"
+---
+1: HEADΒ± | 2: log | 3: main…± | 4: remoteβ‡… | 5: summary
+Enter: switch | alt-c: create | alt-r: remove | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
diff --git a/src/commands/select/snapshots/wt__commands__select__items__tests__via_compute_preview.snap b/src/commands/select/snapshots/wt__commands__select__items__tests__via_compute_preview.snap
new file mode 100644
index 000000000..c75da5d0d
--- /dev/null
+++ b/src/commands/select/snapshots/wt__commands__select__items__tests__via_compute_preview.snap
@@ -0,0 +1,7 @@
+---
+source: src/commands/select/items.rs
+expression: "WorktreeSkimItem::compute_preview(&feature_item, PreviewMode::Summary, 80, 40)"
+---
+β—‹ Generating summary...
+
+Press 5 again to refresh once generation completes.
diff --git a/src/commands/select/snapshots/wt__commands__select__items__tests__working_tree.snap b/src/commands/select/snapshots/wt__commands__select__items__tests__working_tree.snap
new file mode 100644
index 000000000..a3ff33c0e
--- /dev/null
+++ b/src/commands/select/snapshots/wt__commands__select__items__tests__working_tree.snap
@@ -0,0 +1,6 @@
+---
+source: src/commands/select/items.rs
+expression: "WorktreeSkimItem::render_preview_tabs(mode)"
+---
+1: HEADΒ± | 2: log | 3: main…± | 4: remoteβ‡… | 5: summary
+Enter: switch | alt-c: create | alt-r: remove | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
diff --git a/src/commands/select/summary.rs b/src/commands/select/summary.rs
index f1eb0c2b4..5dde07f3c 100644
--- a/src/commands/select/summary.rs
+++ b/src/commands/select/summary.rs
@@ -53,6 +53,8 @@ pub(super) fn generate_and_cache_summary(
#[cfg(test)]
mod tests {
+ use insta::assert_snapshot;
+
use super::*;
use crate::commands::list::model::{ItemKind, WorktreeData};
use std::fs;
@@ -247,35 +249,79 @@ mod tests {
#[test]
fn test_render_prompt() {
use crate::summary::render_prompt;
- let result = render_prompt("diff content", "1 file changed");
- assert!(result.is_ok());
- let prompt = result.unwrap();
- assert!(prompt.contains("diff content"));
- assert!(prompt.contains("1 file changed"));
- }
- #[test]
- fn test_render_prompt_commit_message_format() {
- use crate::summary::render_prompt;
- let result = render_prompt("", "").unwrap();
- assert!(result.contains("commit message"));
- assert!(result.contains("imperative mood"));
- }
+ // With diff content and stat
+ let prompt = render_prompt("diff content", "1 file changed").unwrap();
+ assert_snapshot!(prompt, @r#"
+ Write a summary of this branch's changes as a commit message.
- #[test]
- fn test_render_summary_subject_bold() {
- let text = "Add new feature\n\nSome body text here.";
- let rendered = render_summary(text, 80);
- assert!(rendered.contains("\x1b[1m"));
- assert!(rendered.contains("Add new feature"));
+ <format>
+ - Subject line under 50 chars, imperative mood ("Add feature" not "Adds feature")
+ - Blank line, then a body paragraph or bullet list explaining the key changes
+ - Output only the message β€” no quotes, code blocks, or labels
+ </format>
+
+ <diffstat>
+ 1 file changed
+ </diffstat>
+
+ <diff>
+ diff content
+ </diff>
+ "#);
+
+ // Empty inputs still include format instructions
+ let empty_prompt = render_prompt("", "").unwrap();
+ assert_snapshot!(empty_prompt, @r#"
+ Write a summary of this branch's changes as a commit message.
+
+ <format>
+ - Subject line under 50 chars, imperative mood ("Add feature" not "Adds feature")
+ - Blank line, then a body paragraph or bullet list explaining the key changes
+ - Output only the message β€” no quotes, code blocks, or labels
+ </format>
+
+ <diffstat>
+
+ </diffstat>
+
+ <diff>
+
+ </diff>
+ "#);
}
#[test]
- fn test_render_summary_single_line() {
- let text = "Add new feature";
- let rendered = render_summary(text, 80);
- assert!(rendered.contains("\x1b[1m"));
- assert!(rendered.contains("Add new feature"));
+ fn test_render_summary() {
+ // Multi-line: subject promoted to bold H4, body preserved
+ assert_snapshot!(
+ render_summary("Add new feature\n\nSome body text here.", 80),
+ @"
+ Add new feature
+
+ Some body text here.
+ "
+ );
+
+ // Single line: also promoted to bold H4
+ assert_snapshot!(render_summary("Add new feature", 80), @"Add new feature");
+
+ // Bullet list body preserved
+ assert_snapshot!(
+ render_summary("Subject\n\n- First bullet\n- Second bullet", 80),
+ @"
+ Subject
+
+ - First bullet
+ - Second bullet
+ "
+ );
+
+ // Pre-styled text (ANSI escapes) skips H4 promotion
+ assert_snapshot!(
+ render_summary("\x1b[2mNo changes to summarize.\x1b[0m", 80),
+ @"No changes to summarize."
+ );
}
#[test]
@@ -285,22 +331,6 @@ mod tests {
assert!(rendered.lines().count() > 3);
}
- #[test]
- fn test_render_summary_body_preserved() {
- let text = "Subject\n\n- First bullet\n- Second bullet";
- let rendered = render_summary(text, 80);
- assert!(rendered.contains("First bullet"));
- assert!(rendered.contains("Second bullet"));
- }
-
- #[test]
- fn test_render_summary_prestyled_skips_h4() {
- let text = "\x1b[2mNo changes to summarize.\x1b[0m";
- let rendered = render_summary(text, 80);
- assert!(!rendered.contains("####"));
- assert!(rendered.contains("No changes to summarize."));
- }
-
#[test]
fn test_compute_combined_diff_with_branch_changes() {
use crate::summary::compute_combined_diff;
@@ -438,7 +468,7 @@ mod tests {
"echo 'should not run'",
&repo,
);
- assert!(summary.contains("No changes to summarize"));
+ assert_snapshot!(summary, @"No changes to summarize on main.");
}
#[test]
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index aa157f11b..3f49d61d9 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -1753,47 +1753,6 @@ pub fn step_relocate(
mod tests {
use super::*;
- #[test]
- fn test_squash_result_variants() {
- // Test Debug implementation
- let result = SquashResult::Squashed;
- let debug = format!("{:?}", result);
- assert!(debug.contains("Squashed"));
-
- let result = SquashResult::NoCommitsAhead("main".to_string());
- let debug = format!("{:?}", result);
- assert!(debug.contains("NoCommitsAhead"));
- assert!(debug.contains("main"));
-
- let result = SquashResult::AlreadySingleCommit;
- let debug = format!("{:?}", result);
- assert!(debug.contains("AlreadySingleCommit"));
-
- let result = SquashResult::NoNetChanges;
- let debug = format!("{:?}", result);
- assert!(debug.contains("NoNetChanges"));
- }
-
- #[test]
- fn test_rebase_result_variants() {
- // RebaseResult doesn't derive Debug/Clone by default, just test matching
- let result = RebaseResult::Rebased;
- assert!(matches!(result, RebaseResult::Rebased));
-
- let result = RebaseResult::UpToDate("main".to_string());
- assert!(matches!(result, RebaseResult::UpToDate(ref s) if s == "main"));
- }
-
- #[test]
- fn test_rebase_result_up_to_date_branch_extraction() {
- let result = RebaseResult::UpToDate("feature-branch".to_string());
- if let RebaseResult::UpToDate(branch) = result {
- assert_eq!(branch, "feature-branch");
- } else {
- panic!("Expected UpToDate variant");
- }
- }
-
#[test]
fn test_remove_if_exists_nonexistent() {
// NotFound is silently ignored
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index 140aaa84c..0fa4a930d 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -307,19 +307,6 @@ mod tests {
assert_eq!(ops.rebased, copied.rebased);
}
- #[test]
- fn test_merge_operations_debug() {
- let ops = MergeOperations {
- committed: true,
- squashed: false,
- rebased: true,
- };
- let debug = format!("{:?}", ops);
- assert!(debug.contains("committed: true"));
- assert!(debug.contains("squashed: false"));
- assert!(debug.contains("rebased: true"));
- }
-
#[test]
fn test_remove_result_removed_worktree() {
let result = RemoveResult::RemovedWorktree {
diff --git a/src/config/commands.rs b/src/config/commands.rs
index 24c877ce3..08f1189ee 100644
--- a/src/config/commands.rs
+++ b/src/config/commands.rs
@@ -161,6 +161,8 @@ impl Serialize for CommandConfig {
#[cfg(test)]
mod tests {
+ use insta::assert_snapshot;
+
use super::*;
// ============================================================================
@@ -301,8 +303,7 @@ third = "echo 3"
},
};
- let serialized = toml::to_string(&wrapper).unwrap();
- assert!(serialized.contains("cmd = \"npm install\""));
+ assert_snapshot!(toml::to_string(&wrapper).unwrap(), @r#"cmd = "npm install""#);
}
#[test]
@@ -322,11 +323,11 @@ third = "echo 3"
},
};
- 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"));
+ assert_snapshot!(toml::to_string(&wrapper).unwrap(), @r#"
+ [cmd]
+ build = "cargo build"
+ test = "cargo test"
+ "#);
}
#[test]
@@ -474,8 +475,10 @@ third = "echo 3"
// Should not panic - generates "_1" for unnamed command
let wrapper = Wrapper { cmd: merged };
- let serialized = toml::to_string(&wrapper).unwrap();
- assert!(serialized.contains("npm install"), "{serialized}");
- assert!(serialized.contains("echo setup"), "{serialized}");
+ assert_snapshot!(toml::to_string(&wrapper).unwrap(), @r#"
+ [cmd]
+ _1 = "npm install"
+ setup = "echo setup"
+ "#);
}
}
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 5f7baabdd..1eb8bf988 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -434,6 +434,8 @@ pub fn expand_template(
#[cfg(test)]
mod tests {
+ use insta::assert_snapshot;
+
use super::*;
/// Test fixture that creates a real temporary git repository.
@@ -657,12 +659,10 @@ mod tests {
assert!(expand_template("{{ 1 + }}", &vars, false, &test.repo, "test").is_err());
// Display impl renders source line but no available vars hint for syntax errors
- let display = err.to_string();
- assert!(display.contains("{{ unclosed"), "should show source line");
- assert!(
- !display.contains("Available variables:"),
- "syntax errors should not show available vars"
- );
+ assert_snapshot!(err, @"
+ βœ— Failed to expand test: syntax error: unexpected end of input, expected end of variable block @ line 1
+   {{ unclosed
+ ");
}
#[test]
@@ -684,13 +684,11 @@ mod tests {
assert_eq!(err.source_line.as_deref(), Some("echo {{ target }}"));
// Display impl renders source line and available vars hint
- let display = err.to_string();
- assert!(
- display.contains("echo {{ target }}"),
- "should show source line"
- );
- assert!(display.contains("Available variables:"), "should show hint");
- assert!(display.contains("branch"), "should list available vars");
+ assert_snapshot!(err, @"
+ βœ— Failed to expand test: undefined value @ line 1
+   echo {{ target }}
+ ↳ Available variables: branch, remote
+ ");
}
#[test]
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 90ad42e52..fce9b3904 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -103,6 +103,8 @@ pub use user::{
#[cfg(test)]
mod tests {
+ use insta::assert_snapshot;
+
use super::*;
use crate::git::Repository;
@@ -131,17 +133,10 @@ mod tests {
#[test]
fn test_config_serialization() {
- let config = UserConfig::default();
- let toml = toml::to_string(&config).unwrap();
- // worktree-path is not serialized when None (uses built-in default)
- assert!(!toml.contains("worktree-path"));
- // commit and commit-generation sections are not serialized when None
- assert!(!toml.contains("[commit]"));
- assert!(!toml.contains("[commit-generation]"));
- }
+ // Default config serializes to empty (no optional fields)
+ assert_snapshot!(toml::to_string(&UserConfig::default()).unwrap(), @"[projects]");
- #[test]
- fn test_config_serialization_with_worktree_path() {
+ // With worktree-path set
let config = UserConfig {
configs: OverridableConfig {
worktree_path: Some("custom/{{ branch }}".to_string()),
@@ -149,9 +144,11 @@ mod tests {
},
..Default::default()
};
- let toml = toml::to_string(&config).unwrap();
- assert!(toml.contains("worktree-path"));
- assert!(toml.contains("custom/{{ branch }}"));
+ assert_snapshot!(toml::to_string(&config).unwrap(), @r#"
+ worktree-path = "custom/{{ branch }}"
+
+ [projects]
+ "#);
}
#[test]
@@ -450,8 +447,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
let serialized = toml::to_string(&config).unwrap();
let config2: ProjectConfig = toml::from_str(&serialized).unwrap();
assert_eq!(config, config2);
- // Verify it serialized back as a string
- assert!(serialized.contains(r#"post-create = "npm install""#));
+ assert_snapshot!(serialized, @r#"post-create = "npm install""#);
}
#[test]
@@ -465,10 +461,11 @@ task2 = "echo 'Task 2 running' > task2.txt"
let serialized = toml::to_string(&config).unwrap();
let config2: ProjectConfig = toml::from_str(&serialized).unwrap();
assert_eq!(config, config2);
- // Verify it serialized back as a named table
- assert!(serialized.contains("[post-start]"));
- assert!(serialized.contains(r#"server = "npm run dev""#));
- assert!(serialized.contains(r#"watch = "npm run watch""#));
+ assert_snapshot!(serialized, @r#"
+ [post-start]
+ server = "npm run dev"
+ watch = "npm run watch"
+ "#);
}
#[test]
@@ -622,9 +619,10 @@ squash-template-file = "~/file.txt"
squash_template_file: None,
};
- let toml = toml::to_string(&config).unwrap();
- assert!(toml.contains("llm -m model"));
- assert!(toml.contains("template"));
+ assert_snapshot!(toml::to_string(&config).unwrap(), @r#"
+ command = "llm -m model"
+ template = "template content"
+ "#);
}
#[test]
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index 57ecdcc09..2a97685d1 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -188,8 +188,10 @@ fn test_user_project_config_with_worktree_path_serde() {
..Default::default()
};
let toml = toml::to_string(&config).unwrap();
- assert!(toml.contains("worktree-path"));
- assert!(toml.contains(".worktrees/{{ branch | sanitize }}"));
+ insta::assert_snapshot!(toml, @r#"
+ approved-commands = ["npm install"]
+ worktree-path = ".worktrees/{{ branch | sanitize }}"
+ "#);
let parsed: UserProjectOverrides = toml::from_str(&toml).unwrap();
assert_eq!(
@@ -1514,9 +1516,8 @@ args = ["-m", "claude-haiku-4.5"]
fn test_validation_empty_worktree_path() {
let content = r#"worktree-path = """#;
let result = UserConfig::load_from_str(content);
- assert!(result.is_err());
let err = result.unwrap_err().to_string();
- assert!(err.contains("worktree-path cannot be empty"), "{err}");
+ insta::assert_snapshot!(err, @"worktree-path cannot be empty");
}
#[test]
@@ -1542,9 +1543,8 @@ fn test_validation_project_empty_worktree_path() {
worktree-path = ""
"#;
let result = UserConfig::load_from_str(content);
- assert!(result.is_err());
let err = result.unwrap_err().to_string();
- assert!(err.contains("worktree-path cannot be empty"), "{err}");
+ insta::assert_snapshot!(err, @"projects.github.com/user/repo.worktree-path cannot be empty");
}
#[test]
@@ -1571,108 +1571,23 @@ worktree-path = "/worktrees/{{ branch | sanitize }}"
#[test]
fn test_validation_template_mutual_exclusivity() {
- let content = r#"
-[commit-generation]
-template = "inline template"
-template-file = "path/to/file"
-"#;
- let result = UserConfig::load_from_str(content);
- assert!(result.is_err());
- let err = result.unwrap_err().to_string();
- assert!(err.contains("mutually exclusive"), "{err}");
-}
-
-#[test]
-fn test_validation_squash_template_mutual_exclusivity() {
- let content = r#"
-[commit-generation]
-squash-template = "inline template"
-squash-template-file = "path/to/file"
-"#;
- let result = UserConfig::load_from_str(content);
- assert!(result.is_err());
- let err = result.unwrap_err().to_string();
- assert!(err.contains("mutually exclusive"), "{err}");
-}
-
-#[test]
-fn test_validation_project_template_mutual_exclusivity() {
- let content = r#"
-[projects."github.com/user/repo".commit-generation]
-template = "inline template"
-template-file = "path/to/file"
-"#;
- let result = UserConfig::load_from_str(content);
- assert!(result.is_err());
- let err = result.unwrap_err().to_string();
- assert!(err.contains("mutually exclusive"), "{err}");
-}
-
-#[test]
-fn test_validation_project_squash_template_mutual_exclusivity() {
- let content = r#"
-[projects."github.com/user/repo".commit-generation]
-squash-template = "inline template"
-squash-template-file = "path/to/file"
-"#;
- let result = UserConfig::load_from_str(content);
- assert!(result.is_err());
- let err = result.unwrap_err().to_string();
- assert!(err.contains("mutually exclusive"), "{err}");
-}
-
-// New format [commit.generation] validation tests
-
-#[test]
-fn test_validation_new_format_template_mutual_exclusivity() {
- let content = r#"
-[commit.generation]
-template = "inline template"
-template-file = "path/to/file"
-"#;
- let result = UserConfig::load_from_str(content);
- assert!(result.is_err());
- let err = result.unwrap_err().to_string();
- assert!(err.contains("mutually exclusive"), "{err}");
-}
-
-#[test]
-fn test_validation_new_format_squash_template_mutual_exclusivity() {
- let content = r#"
-[commit.generation]
-squash-template = "inline template"
-squash-template-file = "path/to/file"
-"#;
- let result = UserConfig::load_from_str(content);
- assert!(result.is_err());
- let err = result.unwrap_err().to_string();
- assert!(err.contains("mutually exclusive"), "{err}");
-}
-
-#[test]
-fn test_validation_new_format_project_template_mutual_exclusivity() {
- let content = r#"
-[projects."github.com/user/repo".commit.generation]
-template = "inline template"
-template-file = "path/to/file"
-"#;
- let result = UserConfig::load_from_str(content);
- assert!(result.is_err());
- let err = result.unwrap_err().to_string();
- assert!(err.contains("mutually exclusive"), "{err}");
-}
-
-#[test]
-fn test_validation_new_format_project_squash_template_mutual_exclusivity() {
- let content = r#"
-[projects."github.com/user/repo".commit.generation]
-squash-template = "inline template"
-squash-template-file = "path/to/file"
-"#;
- let result = UserConfig::load_from_str(content);
- assert!(result.is_err());
- let err = result.unwrap_err().to_string();
- assert!(err.contains("mutually exclusive"), "{err}");
+ let cases = [
+ ("[commit-generation]\ntemplate = \"inline\"\ntemplate-file = \"path\""),
+ ("[commit-generation]\nsquash-template = \"inline\"\nsquash-template-file = \"path\""),
+ ("[projects.\"github.com/user/repo\".commit-generation]\ntemplate = \"inline\"\ntemplate-file = \"path\""),
+ ("[projects.\"github.com/user/repo\".commit-generation]\nsquash-template = \"inline\"\nsquash-template-file = \"path\""),
+ ("[commit.generation]\ntemplate = \"inline\"\ntemplate-file = \"path\""),
+ ("[commit.generation]\nsquash-template = \"inline\"\nsquash-template-file = \"path\""),
+ ("[projects.\"github.com/user/repo\".commit.generation]\ntemplate = \"inline\"\ntemplate-file = \"path\""),
+ ("[projects.\"github.com/user/repo\".commit.generation]\nsquash-template = \"inline\"\nsquash-template-file = \"path\""),
+ ];
+ for content in cases {
+ let err = UserConfig::load_from_str(content).unwrap_err().to_string();
+ assert!(
+ err.contains("mutually exclusive"),
+ "{content}: expected 'mutually exclusive', got: {err}"
+ );
+ }
}
// =========================================================================
diff --git a/src/diagnostic.rs b/src/diagnostic.rs
index d50def756..a7096d420 100644
--- a/src/diagnostic.rs
+++ b/src/diagnostic.rs
@@ -372,8 +372,10 @@ mod tests {
#[test]
fn test_format_config_section_file_not_found() {
let result = format_config_section(std::path::Path::new("/nonexistent/path.toml"), "Test");
- assert!(result.contains("Test: /nonexistent/path.toml"));
- assert!(result.contains("(file not found)"));
+ insta::assert_snapshot!(result, @"
+ Test: /nonexistent/path.toml
+ (file not found)
+ ");
}
#[test]
diff --git a/src/git/diff.rs b/src/git/diff.rs
index 5e9eaab9d..776ee385a 100644
--- a/src/git/diff.rs
+++ b/src/git/diff.rs
@@ -117,6 +117,8 @@ impl DiffStats {
#[cfg(test)]
mod tests {
+ use insta::assert_snapshot;
+
use super::*;
// ============================================================================
@@ -319,11 +321,7 @@ mod tests {
insertions: 45,
deletions: 12,
};
- let summary = stats.format_summary();
- assert_eq!(summary.len(), 3);
- assert_eq!(summary[0], "3 files");
- assert!(summary[1].contains("45"));
- assert!(summary[2].contains("12"));
+ assert_snapshot!(stats.format_summary().join(", "), @"3 files, +45, -12");
}
#[test]
@@ -333,10 +331,7 @@ mod tests {
insertions: 10,
deletions: 0,
};
- let summary = stats.format_summary();
- assert_eq!(summary.len(), 2);
- assert_eq!(summary[0], "1 file");
- assert!(summary[1].contains("10"));
+ assert_snapshot!(stats.format_summary().join(", "), @"1 file, +10");
}
// ============================================================================
diff --git a/src/git/error.rs b/src/git/error.rs
index fd063ee2d..c8ee48723 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -1151,7 +1151,7 @@ mod tests {
}
#[test]
- fn test_add_hook_skip_hint() {
+ fn snapshot_add_hook_skip_hint() {
// Wraps HookCommandFailed with --no-verify hint
let inner: anyhow::Error = WorktrunkError::HookCommandFailed {
hook_type: HookType::PreMerge,
@@ -1160,26 +1160,49 @@ mod tests {
exit_code: Some(1),
}
.into();
- let display = format!("{}", add_hook_skip_hint(inner));
- assert!(display.contains("--no-verify") && display.contains("pre-merge"));
+ assert_snapshot!(add_hook_skip_hint(inner).to_string(), @"
+ βœ— pre-merge command failed: test: failed
+ ↳ To skip pre-merge hooks, re-run with --no-verify
+ ");
+
+ // pre-commit hook type
+ let inner: anyhow::Error = WorktrunkError::HookCommandFailed {
+ hook_type: HookType::PreCommit,
+ command_name: Some("build".into()),
+ error: "Build failed".into(),
+ exit_code: Some(1),
+ }
+ .into();
+ assert_snapshot!(add_hook_skip_hint(inner).to_string(), @"
+ βœ— pre-commit command failed: build: Build failed
+ ↳ To skip pre-commit hooks, re-run with --no-verify
+ ");
- // Passes through non-hook errors
+ // Passes through non-hook errors unchanged (no --no-verify hint)
let err: anyhow::Error = WorktrunkError::ChildProcessExited {
code: 1,
message: "test".into(),
}
.into();
- assert!(!format!("{}", add_hook_skip_hint(err)).contains("--no-verify"));
+ assert!(!add_hook_skip_hint(err).to_string().contains("--no-verify"));
let err: anyhow::Error = GitError::DetachedHead { action: None }.into();
- assert!(!format!("{}", add_hook_skip_hint(err)).contains("--no-verify"));
+ assert!(!add_hook_skip_hint(err).to_string().contains("--no-verify"));
+
+ let err: anyhow::Error = GitError::Other {
+ message: "some error".into(),
+ }
+ .into();
+ assert!(!add_hook_skip_hint(err).to_string().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"));
+ assert_snapshot!(format_error_block(header.clone(), " some error text "), @"
+ Error occurred
+   some error text
+ ");
// Empty/whitespace returns header only
assert_eq!(format_error_block(header.clone(), ""), header);
@@ -1187,23 +1210,20 @@ mod tests {
}
#[test]
- fn test_worktrunk_error_display() {
- // ChildProcessExited
+ fn snapshot_worktrunk_error_display() {
let err = WorktrunkError::ChildProcessExited {
code: 1,
message: "Command failed".into(),
};
- assert!(format!("{err}").contains("Command failed"));
+ assert_snapshot!(err.to_string(), @"βœ— 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"));
+ assert_snapshot!(err.to_string(), @"βœ— pre-merge command failed: lint: lint failed");
let err = WorktrunkError::HookCommandFailed {
hook_type: HookType::PostCreate,
@@ -1211,10 +1231,9 @@ mod tests {
error: "setup failed".into(),
exit_code: None,
};
- let display = format!("{err}");
- assert!(display.contains("post-create") && display.contains("setup failed"));
+ assert_snapshot!(err.to_string(), @"βœ— post-create command failed: setup failed");
- // Silent errors
+ // Silent errors produce empty output
assert_eq!(format!("{}", WorktrunkError::CommandNotApproved), "");
assert_eq!(
format!("{}", WorktrunkError::AlreadyDisplayed { exit_code: 1 }),
@@ -1223,75 +1242,69 @@ mod tests {
}
#[test]
- fn test_git_error_not_in_worktree() {
- // With action
+ fn snapshot_not_in_worktree() {
let err = GitError::NotInWorktree {
action: Some("resolve @".into()),
};
- let display = err.to_string();
- assert!(display.contains("Cannot resolve @"));
- assert!(display.contains("not in a worktree"));
- assert!(display.contains("specify a branch name"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— Cannot resolve @: not in a worktree
+ ↳ Run from inside a worktree, or specify a branch name
+ ");
- // Without action
let err = GitError::NotInWorktree { action: None };
- let display = err.to_string();
- assert!(display.contains("Not in a worktree"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— Not in a worktree
+ ↳ Run from inside a worktree, or specify a branch name
+ ");
}
#[test]
- fn test_git_error_worktree_path_occupied() {
- // With occupant branch
+ fn snapshot_worktree_path_occupied() {
let err = GitError::WorktreePathOccupied {
branch: "feature".into(),
path: PathBuf::from("/tmp/repo"),
occupant: Some("main".into()),
};
- let display = err.to_string();
- assert!(display.contains("Cannot switch to"));
- assert!(display.contains("feature"));
- assert!(display.contains("there's a worktree at the expected path"));
- assert!(display.contains("on branch"));
- assert!(display.contains("main"));
- assert!(display.contains("To switch the worktree at"));
- assert!(display.contains(", run ")); // ANSI codes follow, then command
- assert!(display.contains("cd /tmp/repo && git switch feature"));
-
- // Without occupant (detached)
+ assert_snapshot!(err.to_string(), @"
+ βœ— Cannot switch to feature β€” there's a worktree at the expected path /tmp/repo on branch main
+ ↳ To switch the worktree at /tmp/repo to feature, run cd /tmp/repo && git switch feature
+ ");
+
let err = GitError::WorktreePathOccupied {
branch: "feature".into(),
path: PathBuf::from("/tmp/repo"),
occupant: None,
};
- let display = err.to_string();
- assert!(display.contains("detached worktree"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— Cannot switch to feature β€” there's a detached worktree at the expected path /tmp/repo
+ ↳ To switch the worktree at /tmp/repo to feature, run cd /tmp/repo && git switch feature
+ ");
}
#[test]
- fn test_git_error_worktree_creation_failed() {
- // With base branch
+ fn snapshot_worktree_creation_failed() {
let err = GitError::WorktreeCreationFailed {
branch: "feature".into(),
base_branch: Some("main".into()),
error: "git error".into(),
command: None,
};
- let display = err.to_string();
- assert!(display.contains("feature"));
- assert!(display.contains("main"));
- assert!(display.contains("git error"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— Failed to create worktree for feature from base main
+   git error
+ ");
- // Without base branch
let err = GitError::WorktreeCreationFailed {
branch: "feature".into(),
base_branch: None,
error: "git error".into(),
command: None,
};
- let display = err.to_string();
- assert!(display.contains("feature"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— Failed to create worktree for feature
+   git error
+ ");
- // With command info
let err = GitError::WorktreeCreationFailed {
branch: "feature".into(),
base_branch: Some("main".into()),
@@ -1301,110 +1314,109 @@ mod tests {
exit_info: "exit code 128".into(),
}),
};
- let display = err.to_string();
- assert!(display.contains("fatal: ref exists"));
- assert!(display.contains("worktree add"));
- assert!(display.contains("Failed command"));
- assert!(display.contains("exit code 128"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— Failed to create worktree for feature from base main
+   fatal: ref exists
+ ↳ Failed command, exit code 128:
+   git worktree add /path -b feature main
+ ");
}
#[test]
- fn test_git_error_worktree_locked_with_reason() {
+ fn snapshot_worktree_locked() {
let err = GitError::WorktreeLocked {
branch: "feature".into(),
path: PathBuf::from("/tmp/repo.feature"),
reason: Some("Testing lock".into()),
};
- let display = err.to_string();
- assert!(display.contains("Cannot remove"));
- assert!(display.contains("feature"));
- assert!(display.contains(", worktree is locked"));
- assert!(display.contains("(Testing lock)"));
- assert!(display.contains("git worktree unlock /tmp/repo.feature"));
- }
+ assert_snapshot!(err.to_string(), @"
+ βœ— Cannot remove feature, worktree is locked (Testing lock)
+ ↳ To unlock, run git worktree unlock /tmp/repo.feature
+ ");
- #[test]
- fn test_git_error_worktree_locked_no_reason() {
- // When git outputs "locked" without a reason, we get Some("")
+ // Empty reason should not show parentheses
let err = GitError::WorktreeLocked {
branch: "feature".into(),
path: PathBuf::from("/tmp/repo.feature"),
reason: Some("".into()),
};
let display = err.to_string();
- assert!(display.contains("Cannot remove"));
- assert!(display.contains("feature"));
- assert!(display.contains(", worktree is locked"));
+ assert_snapshot!(display, @"
+ βœ— Cannot remove feature, worktree is locked
+ ↳ To unlock, run git worktree unlock /tmp/repo.feature
+ ");
assert!(
!display.contains("locked ("),
"should not show parentheses without reason"
);
- assert!(display.contains("git worktree unlock /tmp/repo.feature"));
}
#[test]
- fn test_git_error_not_rebased() {
+ fn snapshot_not_rebased() {
let err = GitError::NotRebased {
target_branch: "main".into(),
};
- let display = err.to_string();
- assert!(display.contains("main"));
- assert!(display.contains("not rebased"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— Branch not rebased onto main
+ ↳ To rebase first, run wt step rebase main; or remove --no-rebase
+ ");
}
#[test]
- fn test_git_error_hook_command_not_found() {
- // With available commands
+ fn snapshot_hook_command_not_found() {
let err = GitError::HookCommandNotFound {
name: "unknown".into(),
available: vec!["lint".into(), "test".into()],
};
- let display = err.to_string();
- assert!(display.contains("unknown"));
- assert!(display.contains("lint"));
+ assert_snapshot!(err.to_string(), @"βœ— No command named unknown (available: lint, test)");
- // No available commands
let err = GitError::HookCommandNotFound {
name: "unknown".into(),
available: vec![],
};
- let display = err.to_string();
- assert!(display.contains("no named commands"));
+ assert_snapshot!(err.to_string(), @"βœ— No command named unknown (hook has no named commands)");
}
#[test]
- fn test_git_error_llm_command_failed() {
- // With reproduction command
+ fn snapshot_llm_command_failed() {
let err = GitError::LlmCommandFailed {
command: "llm".into(),
error: "connection failed".into(),
reproduction_command: Some("wt step commit --show-prompt | llm".into()),
};
- let display = err.to_string();
- assert!(display.contains("connection failed"));
- assert!(display.contains("wt step commit"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— Commit generation command failed
+   connection failed
+ β—‹ Ran command:
+   wt step commit --show-prompt | llm
+ ");
- // Without reproduction command
let err = GitError::LlmCommandFailed {
command: "llm --model gpt-4".into(),
error: "timeout".into(),
reproduction_command: None,
};
- let display = err.to_string();
- assert!(display.contains("llm --model gpt-4"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— Commit generation command failed
+   timeout
+ β—‹ Ran command:
+   llm --model gpt-4
+ ");
}
#[test]
- fn test_git_error_uncommitted_changes_variants() {
- // Action only
+ fn snapshot_uncommitted_changes() {
+ // Action only (negative assertion kept: no --force)
let err = GitError::UncommittedChanges {
action: Some("push".into()),
branch: None,
force_hint: false,
};
let display = err.to_string();
- assert!(display.contains("Cannot push"));
- assert!(display.contains("working tree"));
+ assert_snapshot!(display, @"
+ βœ— Cannot push: working tree has uncommitted changes
+ ↳ Commit or stash changes first
+ ");
assert!(!display.contains("--force"));
// Branch only
@@ -1413,18 +1425,21 @@ mod tests {
branch: Some("feature".into()),
force_hint: false,
};
- let display = err.to_string();
- assert!(display.contains("feature"));
- assert!(display.contains("uncommitted"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— feature has uncommitted changes
+ ↳ Commit or stash changes first
+ ");
- // Neither
+ // Neither action nor branch
let err = GitError::UncommittedChanges {
action: None,
branch: None,
force_hint: false,
};
- let display = err.to_string();
- assert!(display.contains("Working tree"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— Working tree has uncommitted changes
+ ↳ Commit or stash changes first
+ ");
// With force_hint
let err = GitError::UncommittedChanges {
@@ -1432,157 +1447,101 @@ mod tests {
branch: Some("feature".into()),
force_hint: true,
};
- let display = err.to_string();
- assert!(display.contains("Cannot remove worktree"));
- assert!(display.contains("wt remove --force feature"));
- assert!(display.contains("to lose uncommitted changes, run"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— Cannot remove worktree: feature has uncommitted changes
+ ↳ Commit or stash changes first, or to lose uncommitted changes, run wt remove --force feature
+ ");
}
#[test]
- fn test_git_error_not_fast_forward_empty_commits() {
- // Test with empty commits_formatted to cover that branch
+ fn snapshot_not_fast_forward() {
+ // Empty commits, outside merge context
let err = GitError::NotFastForward {
target_branch: "main".into(),
commits_formatted: "".into(),
in_merge_context: false,
};
- let display = err.to_string();
- assert!(display.contains("main"));
- assert!(display.contains("newer commits"));
- // Should still have hint
- assert!(display.contains("rebase"));
- }
+ assert_snapshot!(err.to_string(), @"
+ βœ— Can't push to local main branch: it has newer commits
+ ↳ To rebase onto main, run wt step rebase main
+ ");
- #[test]
- fn test_git_error_not_fast_forward_outside_merge() {
- // Test outside merge context (in_merge_context = false)
+ // With commits, outside merge context
let err = GitError::NotFastForward {
target_branch: "develop".into(),
commits_formatted: "abc123 Some commit".into(),
in_merge_context: false,
};
- let display = err.to_string();
- assert!(display.contains("develop"));
- // Should have generic rebase hint, not "wt merge"
- assert!(display.contains("rebase"));
- // commits_formatted should be in gutter
- assert!(display.contains("abc123"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— Can't push to local develop branch: it has newer commits
+   abc123 Some commit
+ ↳ To rebase onto develop, run wt step rebase develop
+ ");
+
+ // In merge context
+ let err = GitError::NotFastForward {
+ target_branch: "main".into(),
+ commits_formatted: "def456 Another commit".into(),
+ in_merge_context: true,
+ };
+ assert_snapshot!(err.to_string(), @"
+ βœ— Can't push to local main branch: it has newer commits
+   def456 Another commit
+ ↳ To incorporate these changes, run wt merge main again
+ ");
}
#[test]
- fn test_git_error_conflicting_changes_empty_files() {
- // Test with empty files list
+ fn snapshot_conflicting_changes_empty_files() {
let err = GitError::ConflictingChanges {
target_branch: "main".into(),
files: vec![],
worktree_path: PathBuf::from("/tmp/repo"),
};
- let display = err.to_string();
- assert!(display.contains("conflicting"));
- // Should still have hint about commit/stash
- assert!(display.contains("Commit or stash"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— Can't push to local main branch: conflicting uncommitted changes
+ ↳ Commit or stash these changes in /tmp/repo first
+ ");
}
#[test]
- fn test_git_error_cli_api_error() {
+ fn snapshot_cli_api_error() {
let err = GitError::CliApiError {
ref_type: RefType::Pr,
message: "gh api failed for PR #42".into(),
stderr: "error: unexpected response\ncode: 500".into(),
};
- let display = err.to_string();
- // Verify header and gutter content are present
- assert!(display.contains("gh api failed"));
- assert!(display.contains("unexpected response"));
- assert!(display.contains("500"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— gh api failed for PR #42
+   error: unexpected response
+   code: 500
+ ");
}
#[test]
- fn test_git_error_no_remote_for_repo() {
+ fn snapshot_no_remote_for_repo() {
let err = GitError::NoRemoteForRepo {
owner: "upstream-owner".into(),
repo: "upstream-repo".into(),
suggested_url: "https://github.com/upstream-owner/upstream-repo.git".into(),
};
- let display = err.to_string();
- // Verify error message and hint
- assert!(display.contains("No remote found"));
- assert!(display.contains("upstream-owner/upstream-repo"));
- assert!(display.contains("git remote add upstream"));
- assert!(display.contains("https://github.com/upstream-owner/upstream-repo.git"));
- }
-
- #[test]
- fn test_hook_error_with_hint_source() {
- use crate::HookType;
-
- // Create a WorktrunkError with hook_type
- let inner_error: anyhow::Error = WorktrunkError::HookCommandFailed {
- hook_type: HookType::PreMerge,
- command_name: Some("test".into()),
- error: "Test failed".into(),
- exit_code: Some(1),
- }
- .into();
-
- // Wrap it using add_hook_skip_hint
- let wrapped = add_hook_skip_hint(inner_error);
-
- // The source() method should return the underlying error
- let source = wrapped.source();
- // source can be Some or None depending on implementation
- let _ = source;
- }
-
- #[test]
- fn test_add_hook_skip_hint_with_hook_type() {
- use crate::HookType;
-
- let inner: anyhow::Error = WorktrunkError::HookCommandFailed {
- hook_type: HookType::PreCommit,
- command_name: Some("build".into()),
- error: "Build failed".into(),
- exit_code: Some(1),
- }
- .into();
-
- let wrapped = add_hook_skip_hint(inner);
- let display = wrapped.to_string();
-
- // Should include the original error
- assert!(display.contains("build"));
- // Should include the hint
- assert!(display.contains("--no-verify"));
- assert!(display.contains("pre-commit"));
- }
-
- #[test]
- fn test_add_hook_skip_hint_non_hook_error() {
- // Test with a non-hook error (should pass through unchanged)
- let inner: anyhow::Error = GitError::Other {
- message: "some error".into(),
- }
- .into();
-
- let wrapped = add_hook_skip_hint(inner);
- let display = wrapped.to_string();
-
- // Should include the original error
- assert!(display.contains("some error"));
- // Should NOT include hint (not a hook error)
- assert!(!display.contains("--no-verify"));
+ assert_snapshot!(err.to_string(), @"
+ βœ— No remote found for upstream-owner/upstream-repo
+ ↳ Add the remote: git remote add upstream https://github.com/upstream-owner/upstream-repo.git
+ ");
}
#[test]
- fn test_rebase_conflict_empty_output() {
+ fn snapshot_rebase_conflict_empty_output() {
let err = GitError::RebaseConflict {
target_branch: "main".into(),
git_output: "".into(),
};
- let display = err.to_string();
- assert!(display.contains("incomplete"));
- assert!(display.contains("main"));
- // Empty output shouldn't cause issues
+ assert_snapshot!(err.to_string(), @"
+ βœ— Rebase onto main incomplete
+ ↳ To continue after resolving conflicts, run git rebase --continue
+ ↳ To abort, run git rebase --abort
+ ");
}
#[test]
diff --git a/src/git/remote_ref/gitlab.rs b/src/git/remote_ref/gitlab.rs
index 802108e27..7f46fcce0 100644
--- a/src/git/remote_ref/gitlab.rs
+++ b/src/git/remote_ref/gitlab.rs
@@ -330,7 +330,6 @@ mod tests {
};
let result = fetch_gitlab_project_urls(&github_info, std::path::Path::new("."));
- assert!(result.is_err());
- assert!(result.unwrap_err().to_string().contains("non-GitLab ref"));
+ insta::assert_snapshot!(result.unwrap_err(), @"fetch_gitlab_project_urls called on non-GitLab ref");
}
}
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index 2494103ab..ed8f1f175 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -270,28 +270,6 @@ fn test_parse_remote_default_branch_branch_with_slash() {
use super::ResolvedWorktree;
-#[test]
-fn test_resolved_worktree_debug() {
- let wt = ResolvedWorktree::Worktree {
- path: PathBuf::from("/path/to/worktree"),
- branch: Some("feature".to_string()),
- };
- let debug = format!("{:?}", wt);
- assert!(debug.contains("Worktree"));
- assert!(debug.contains("/path/to/worktree"));
- assert!(debug.contains("feature"));
-}
-
-#[test]
-fn test_resolved_worktree_branch_only_debug() {
- let wt = ResolvedWorktree::BranchOnly {
- branch: "feature".to_string(),
- };
- let debug = format!("{:?}", wt);
- assert!(debug.contains("BranchOnly"));
- assert!(debug.contains("feature"));
-}
-
#[test]
fn test_resolved_worktree_clone() {
let wt = ResolvedWorktree::Worktree {
diff --git a/src/llm.rs b/src/llm.rs
index 53e92a14d..90bb810b4 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -718,6 +718,7 @@ pub(crate) fn test_commit_generation(
#[cfg(test)]
mod tests {
use super::*;
+ use insta::assert_snapshot;
/// Helper to create a commit context (no squash-specific fields)
fn commit_context<'a>(
@@ -760,42 +761,107 @@ mod tests {
#[test]
fn test_build_commit_prompt_with_default_template() {
let config = CommitGenerationConfig::default();
+
+ // No recent commits
let context = commit_context("diff content", "main", None, "myrepo");
- let result = build_prompt(&config, TemplateType::Commit, &context);
- assert!(result.is_ok());
- let prompt = result.unwrap();
- assert!(prompt.contains("diff content"));
- assert!(prompt.contains("main"));
- }
+ let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
+ assert_snapshot!(prompt, @r#"
+ Write a commit message for the staged changes below.
- #[test]
- fn test_build_commit_prompt_with_recent_commits() {
- let config = CommitGenerationConfig::default();
+ <format>
+ - Subject line under 50 chars
+ - For material changes, add a blank line then a body paragraph explaining the change
+ - Output only the commit message, no quotes or code blocks
+ </format>
+
+ <style>
+ - Imperative mood: "Add feature" not "Added feature"
+ - Match recent commit style (conventional commits if used)
+ - Describe the change, not the intent or benefit
+ </style>
+
+ <diffstat>
+
+ </diffstat>
+
+ <diff>
+ diff content
+ </diff>
+
+ <context>
+ Branch: main
+
+ </context>
+ "#);
+
+ // With recent commits
let commits = vec!["feat: add feature".to_string(), "fix: bug".to_string()];
let context = commit_context("diff", "main", Some(&commits), "repo");
- let result = build_prompt(&config, TemplateType::Commit, &context);
- assert!(result.is_ok());
- let prompt = result.unwrap();
- assert!(prompt.contains("feat: add feature"));
- assert!(prompt.contains("fix: bug"));
- assert!(prompt.contains("<recent_commits>"));
- }
-
- #[test]
- fn test_build_commit_prompt_empty_recent_commits() {
- let config = CommitGenerationConfig::default();
+ let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
+ assert_snapshot!(prompt, @r#"
+ Write a commit message for the staged changes below.
+
+ <format>
+ - Subject line under 50 chars
+ - For material changes, add a blank line then a body paragraph explaining the change
+ - Output only the commit message, no quotes or code blocks
+ </format>
+
+ <style>
+ - Imperative mood: "Add feature" not "Added feature"
+ - Match recent commit style (conventional commits if used)
+ - Describe the change, not the intent or benefit
+ </style>
+
+ <diffstat>
+
+ </diffstat>
+
+ <diff>
+ diff
+ </diff>
+
+ <context>
+ Branch: main
+ <recent_commits>
+ - feat: add feature
+ - fix: bug
+ </recent_commits>
+ </context>
+ "#);
+
+ // Empty recent commits list β€” should not render commit data section
let commits = vec![];
let context = commit_context("diff", "main", Some(&commits), "repo");
- let result = build_prompt(&config, TemplateType::Commit, &context);
- assert!(result.is_ok());
- // Should not render the recent commits data section if empty
- // Note: <recent_commits> is mentioned in the style text, but the actual
- // data section (with commit list) should not be rendered
- let prompt = result.unwrap();
- // The context section should have the branch but no recent_commits content
- assert!(prompt.contains("Branch: main"));
- assert!(!prompt.contains("- feat:"));
- assert!(!prompt.contains("- fix:"));
+ let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
+ assert_snapshot!(prompt, @r#"
+ Write a commit message for the staged changes below.
+
+ <format>
+ - Subject line under 50 chars
+ - For material changes, add a blank line then a body paragraph explaining the change
+ - Output only the commit message, no quotes or code blocks
+ </format>
+
+ <style>
+ - Imperative mood: "Add feature" not "Added feature"
+ - Match recent commit style (conventional commits if used)
+ - Describe the change, not the intent or benefit
+ </style>
+
+ <diffstat>
+
+ </diffstat>
+
+ <diff>
+ diff
+ </diff>
+
+ <context>
+ Branch: main
+
+ </context>
+ "#);
}
#[test]
@@ -838,13 +904,7 @@ mod tests {
};
let context = commit_context("diff", "main", None, "repo");
let result = build_prompt(&config, TemplateType::Commit, &context);
- assert!(result.is_err());
- assert!(
- result
- .unwrap_err()
- .to_string()
- .contains("Template is empty")
- );
+ assert_snapshot!(result.unwrap_err().to_string(), @"βœ— Template is empty");
}
#[test]
@@ -875,15 +935,35 @@ mod tests {
let config = CommitGenerationConfig::default();
let commits = vec!["feat: A".to_string(), "fix: B".to_string()];
let context = squash_context("diff content", "feature", None, "repo", &commits, "main");
- let result = build_prompt(&config, TemplateType::Squash, &context);
- assert!(result.is_ok());
- let prompt = result.unwrap();
- // Commits should be reversed (chronological order: B first, then A)
- assert!(prompt.contains("fix: B"));
- assert!(prompt.contains("feat: A"));
- assert!(prompt.contains("main"));
- // Default squash template now includes the diff
- assert!(prompt.contains("diff content"));
+ let prompt = build_prompt(&config, TemplateType::Squash, &context).unwrap();
+ assert_snapshot!(prompt, @r#"
+ Combine these commits into a single commit message.
+
+ <format>
+ - Subject line under 50 chars
+ - For material changes, add a blank line then a body paragraph explaining the change
+ - Output only the commit message, no quotes or code blocks
+ </format>
+
+ <style>
+ - Imperative mood: "Add feature" not "Added feature"
+ - Match the style of commits being squashed (conventional commits if used)
+ - Describe the change, not the intent or benefit
+ </style>
+
+ <commits branch="feature" target="main">
+ - fix: B
+ - feat: A
+ </commits>
+
+ <diffstat>
+
+ </diffstat>
+
+ <diff>
+ diff content
+ </diff>
+ "#);
}
#[test]
@@ -942,13 +1022,7 @@ mod tests {
let commits: Vec<String> = vec![];
let context = squash_context("diff", "feature", None, "repo", &commits, "main");
let result = build_prompt(&config, TemplateType::Squash, &context);
- assert!(result.is_err());
- assert!(
- result
- .unwrap_err()
- .to_string()
- .contains("Squash template is empty")
- );
+ assert_snapshot!(result.unwrap_err().to_string(), @"βœ— Squash template is empty");
}
#[test]
@@ -1008,60 +1082,38 @@ Diff follows:
squash_template: None,
squash_template_file: None,
};
+
+ // With commits β€” exercises if-branch, filters, loop.index, whitespace control
let commits = vec![
"feat: add auth".to_string(),
"fix: bug".to_string(),
"docs: update".to_string(),
];
let context = commit_context("my diff content", "feature-x", Some(&commits), "myapp");
- let result = build_prompt(&config, TemplateType::Commit, &context);
- assert!(result.is_ok());
- let prompt = result.unwrap();
-
- // Verify filters work (upper)
- assert!(prompt.contains("=== MYAPP ==="));
-
- // Verify length filter
- assert!(prompt.contains("Commits: 3"));
-
- // Verify loop.index
- assert!(prompt.contains(" - 1. feat: add auth"));
- assert!(prompt.contains(" - 2. fix: bug"));
- assert!(prompt.contains(" - 3. docs: update"));
-
- // Verify whitespace control (no blank lines after "Branch:")
- assert!(prompt.contains("Branch: feature-x\nCommits: 3"));
-
- // Verify diff is included
- assert!(prompt.contains("Diff follows:\nmy diff content"));
- }
-
- #[test]
- fn test_build_commit_prompt_with_sophisticated_jinja_no_commits() {
- // Test the else branch of conditionals
- let config = CommitGenerationConfig {
- command: None,
- template: Some(
- r#"Repo: {{ repo | upper }}
-{%- if recent_commits %}
-Has commits: {{ recent_commits | length }}
-{%- else %}
-No recent commits
-{%- endif %}"#
- .to_string(),
- ),
- template_file: None,
- squash_template: None,
- squash_template_file: None,
- };
+ let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
+ assert_snapshot!(prompt, @"
+ === MYAPP ===
+ Branch: feature-x
+ Commits: 3
+ - 1. feat: add auth
+ - 2. fix: bug
+ - 3. docs: update
+
+ Diff follows:
+ my diff content
+ ");
+
+ // Without commits β€” exercises else-branch
let context = commit_context("diff", "main", None, "test");
- let result = build_prompt(&config, TemplateType::Commit, &context);
- assert!(result.is_ok());
- let prompt = result.unwrap();
-
- assert!(prompt.contains("Repo: TEST"));
- assert!(prompt.contains("No recent commits"));
- assert!(!prompt.contains("Has commits"));
+ let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
+ assert_snapshot!(prompt, @"
+ === TEST ===
+ Branch: main
+ No recent commits
+
+ Diff follows:
+ diff
+ ");
}
#[test]
@@ -1086,34 +1138,30 @@ Single commit: {{ commits[0] }}
squash_template_file: None,
};
- // Test with multiple commits
+ // Multiple commits β€” reversed for chronological order (C, B, A)
let commits = vec![
"commit A".to_string(),
"commit B".to_string(),
"commit C".to_string(),
];
let context = squash_context("diff", "feature", None, "repo", &commits, "main");
- let result = build_prompt(&config, TemplateType::Squash, &context);
- assert!(result.is_ok());
- let prompt = result.unwrap();
-
- // Commits are reversed for chronological order, so we expect C, B, A
- assert!(prompt.contains("Squashing 3 commit(s) from feature to main"));
- assert!(prompt.contains("Multiple commits detected:"));
- assert!(prompt.contains("1/3: commit C")); // First in chronological order
- assert!(prompt.contains("2/3: commit B"));
- assert!(prompt.contains("3/3: commit A")); // Last in chronological order
-
- // Test with single commit
+ let prompt = build_prompt(&config, TemplateType::Squash, &context).unwrap();
+ assert_snapshot!(prompt, @"
+ Squashing 3 commit(s) from feature to main
+ Multiple commits detected:
+ 1/3: commit C
+ 2/3: commit B
+ 3/3: commit A
+ ");
+
+ // Single commit β€” exercises else-branch
let single_commit = vec!["solo commit".to_string()];
let context = squash_context("diff", "feature", None, "repo", &single_commit, "main");
- let result = build_prompt(&config, TemplateType::Squash, &context);
- assert!(result.is_ok());
- let prompt = result.unwrap();
-
- assert!(prompt.contains("Squashing 1 commit(s)"));
- assert!(prompt.contains("Single commit: solo commit"));
- assert!(!prompt.contains("Multiple commits detected"));
+ let prompt = build_prompt(&config, TemplateType::Squash, &context).unwrap();
+ assert_snapshot!(prompt, @"
+ Squashing 1 commit(s) from feature to main
+ Single commit: solo commit
+ ");
}
#[test]
@@ -1156,8 +1204,10 @@ Single commit: {{ commits[0] }}
};
let context = commit_context("diff", "main", None, "repo");
let result = build_prompt(&config, TemplateType::Commit, &context);
- assert!(result.is_err());
- assert!(result.unwrap_err().to_string().contains("Failed to read"));
+ // OS error text varies by platform, so use contains
+ let err = result.unwrap_err().to_string();
+ assert!(err.contains("Failed to read template-file"), "{err}");
+ assert!(err.contains("/nonexistent/path/template.txt"), "{err}");
}
#[test]
@@ -1202,11 +1252,10 @@ Single commit: {{ commits[0] }}
let context = commit_context("diff", "main", None, "repo");
let result = build_prompt(&config, TemplateType::Commit, &context);
// Should fail because file doesn't exist
- assert!(result.is_err());
+ // OS error text varies by platform, so use contains
let err = result.unwrap_err().to_string();
- assert!(err.contains("Failed to read"));
- // Error message may display ~ for readability, but the actual file read
- // should have used the expanded path (verified by the error occurring)
+ assert!(err.contains("Failed to read template-file"), "{err}");
+ assert!(err.contains("~/nonexistent_template_for_test.txt"), "{err}");
}
#[test]
@@ -1235,19 +1284,35 @@ Single commit: {{ commits[0] }}
#[test]
fn test_is_lock_file() {
+ // Matches
assert!(is_lock_file("Cargo.lock"));
assert!(is_lock_file("package-lock.json"));
assert!(is_lock_file("pnpm-lock.yaml"));
+ assert!(is_lock_file("yarn-lock.yaml"));
assert!(is_lock_file(".terraform.lock.hcl"));
+ assert!(is_lock_file("terraform.lock.hcl"));
assert!(is_lock_file("path/to/Cargo.lock"));
+ // Non-matches
assert!(!is_lock_file("src/main.rs"));
+ assert!(!is_lock_file("README.md"));
+ assert!(!is_lock_file("config.toml"));
assert!(!is_lock_file("lockfile.txt"));
assert!(!is_lock_file("my.lock.rs")); // Not a standard lock pattern
}
#[test]
fn test_parse_diff_sections() {
+ // Empty input
+ assert!(parse_diff_sections("").is_empty());
+
+ // Single file
+ let diff = "diff --git a/foo.rs b/foo.rs\nsome content\n";
+ let sections = parse_diff_sections(diff);
+ assert_eq!(sections.len(), 1);
+ assert_eq!(sections[0].0, "foo.rs");
+
+ // Multiple files
let diff = r#"diff --git a/src/foo.rs b/src/foo.rs
index abc..def 100644
--- a/src/foo.rs
@@ -1262,13 +1327,27 @@ index 111..222 100644
@@ -1,100 +1,150 @@
lots of lock content
"#;
-
let sections = parse_diff_sections(diff);
assert_eq!(sections.len(), 2);
assert_eq!(sections[0].0, "src/foo.rs");
- assert!(sections[0].1.contains("fn foo()"));
+ assert_snapshot!(sections[0].1, @"
+ diff --git a/src/foo.rs b/src/foo.rs
+ index abc..def 100644
+ --- a/src/foo.rs
+ +++ b/src/foo.rs
+ @@ -1,3 +1,4 @@
+ fn foo() {}
+ +fn bar() {}
+ ");
assert_eq!(sections[1].0, "Cargo.lock");
- assert!(sections[1].1.contains("lots of lock content"));
+ assert_snapshot!(sections[1].1, @"
+ diff --git a/Cargo.lock b/Cargo.lock
+ index 111..222 100644
+ --- a/Cargo.lock
+ +++ b/Cargo.lock
+ @@ -1,100 +1,150 @@
+ lots of lock content
+ ");
}
#[test]
@@ -1292,10 +1371,18 @@ index abc..def 100644
// Truncate to 8 lines (should keep header + first few content lines)
let truncated = truncate_diff_section(section, 8);
- assert!(truncated.contains("diff --git"));
- assert!(truncated.contains("@@"));
- assert!(truncated.contains("... ("));
- assert!(truncated.contains("lines omitted)"));
+ assert_snapshot!(truncated, @"
+ diff --git a/file.rs b/file.rs
+ index abc..def 100644
+ --- a/file.rs
+ +++ b/file.rs
+ @@ -1,10 +1,15 @@
+ line 1
+ line 2
+ line 3
+
+ ... (7 lines omitted)
+ ");
}
#[test]
@@ -1351,20 +1438,6 @@ diff --git a/Cargo.lock b/Cargo.lock
assert!(prepared.diff.contains("files omitted"));
}
- #[test]
- fn test_parse_diff_sections_empty() {
- let sections = parse_diff_sections("");
- assert!(sections.is_empty());
- }
-
- #[test]
- fn test_parse_diff_sections_single_file() {
- let diff = "diff --git a/foo.rs b/foo.rs\nsome content\n";
- let sections = parse_diff_sections(diff);
- assert_eq!(sections.len(), 1);
- assert_eq!(sections[0].0, "foo.rs");
- }
-
#[test]
fn test_truncate_diff_section_short() {
// Section shorter than max lines should pass through unchanged
@@ -1378,44 +1451,27 @@ diff --git a/Cargo.lock b/Cargo.lock
// Section without @@ marker
let section = "line1\nline2\nline3\nline4\nline5\nline6\nline7\nline8\n";
let truncated = truncate_diff_section(section, 3);
- assert!(truncated.contains("line1"));
- assert!(truncated.contains("lines omitted"));
+ assert_snapshot!(truncated, @"
+ line1
+ line2
+ line3
+
+ ... (5 lines omitted)
+ ");
}
#[test]
- fn test_format_reproduction_command_simple() {
- // Simple command without shell metacharacters - no wrapping needed
+ fn test_format_reproduction_command() {
+ // Simple command β€” no wrapping needed
let result = format_reproduction_command("git diff", "llm -m haiku");
- assert_eq!(result, "git diff | llm -m haiku");
- }
+ assert_snapshot!(result, @"git diff | llm -m haiku");
- #[test]
- fn test_format_reproduction_command_with_env_var() {
- // Command starting with env var assignment needs shell wrapping
+ // Env var assignment β€” needs shell wrapping
let result = format_reproduction_command("git diff", "MAX_THINKING_TOKENS=0 claude -p");
- assert!(result.contains("sh -c"));
- assert!(result.contains("git diff |"));
- }
+ assert_snapshot!(result, @"git diff | sh -c 'MAX_THINKING_TOKENS=0 claude -p'");
- #[test]
- fn test_format_reproduction_command_with_metacharacters() {
- // Commands with shell metacharacters need wrapping
+ // Shell metacharacters β€” needs wrapping
let result = format_reproduction_command("git diff", "cmd1 && cmd2");
- assert!(result.contains("sh -c"));
- }
-
- #[test]
- fn test_is_lock_file_matches() {
- assert!(is_lock_file("Cargo.lock"));
- assert!(is_lock_file("package-lock.json"));
- assert!(is_lock_file("yarn-lock.yaml"));
- assert!(is_lock_file("terraform.lock.hcl"));
- }
-
- #[test]
- fn test_is_lock_file_non_matches() {
- assert!(!is_lock_file("main.rs"));
- assert!(!is_lock_file("README.md"));
- assert!(!is_lock_file("config.toml"));
+ assert_snapshot!(result, @"git diff | sh -c 'cmd1 && cmd2'");
}
}
diff --git a/src/md_help.rs b/src/md_help.rs
index 67d4c8610..72bc4b73a 100644
--- a/src/md_help.rs
+++ b/src/md_help.rs
@@ -439,12 +439,17 @@ fn colorize_status_symbols(text: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
+ use insta::assert_snapshot;
/// Test helper: render markdown without prose wrapping
fn render_markdown_in_help(help: &str) -> String {
render_markdown_in_help_with_width(help, None)
}
+ // ============================================================================
+ // strip_markdown_links / unescape_table_pipes (exact transformations)
+ // ============================================================================
+
#[test]
fn test_render_inline_formatting_strips_links() {
assert_eq!(render_inline_formatting("[text](url)"), "text");
@@ -454,16 +459,6 @@ mod tests {
);
}
- #[test]
- fn test_render_inline_formatting_backticks_in_link() {
- // Backticks inside link text should be preserved and rendered as code
- let result = render_inline_formatting("See [`wt hook`](@/hook.md) for details");
- // Should contain dimmed "wt hook" (code style)
- assert!(result.contains("\u{1b}[2mwt hook\u{1b}[0m"));
- assert!(result.contains("See "));
- assert!(result.contains(" for details"));
- }
-
#[test]
fn test_render_inline_formatting_nested_brackets() {
assert_eq!(
@@ -497,150 +492,133 @@ mod tests {
#[test]
fn test_unescape_table_pipes() {
- // Basic conversion
assert_eq!(unescape_table_pipes(r"a \| b"), "a | b");
- // Multiple escapes
assert_eq!(
unescape_table_pipes(r"\| start \| end \|"),
"| start | end |"
);
- // No escapes - unchanged
assert_eq!(unescape_table_pipes("no pipes here"), "no pipes here");
- // Regular pipe - unchanged
assert_eq!(unescape_table_pipes("a | b"), "a | b");
}
- #[test]
- fn test_render_table_escaped_pipe() {
- // In markdown tables, \| represents a literal pipe character
- // We preprocess to convert \| to | before sending to termimad
- let lines = vec![
- "| Category | Symbol | Meaning |",
- "| --- | --- | --- |",
- r"| Remote | `\|` | In sync |",
- ];
- let result = render_table(&lines, None);
- // Table should render with the content
- assert!(
- result.contains("Remote"),
- "Table should contain cell content"
- );
- assert!(
- result.contains("In sync"),
- "Table should contain cell content"
- );
- // The escaped pipe should be converted to a literal pipe
- assert!(result.contains('|'));
- assert!(!result.contains(r"\|"));
- }
-
// ============================================================================
- // render_markdown_in_help Tests
+ // render_inline_formatting (ANSI styling)
// ============================================================================
#[test]
- fn test_render_markdown_in_help_h1() {
- let result = render_markdown_in_help("# Header");
- // H1 should be UPPERCASE green
- assert!(result.contains("HEADER")); // Uppercase
- assert!(result.contains("\u{1b}[32m")); // Green
- }
+ fn test_render_inline_formatting_styles() {
+ // Inline code
+ let code = render_inline_formatting("`code`");
+ assert_snapshot!(code, @"code");
- #[test]
- fn test_render_markdown_in_help_h2() {
- let result = render_markdown_in_help("## Section");
- // H2 should be bold green (anstyle emits separate codes)
- assert!(result.contains("Section"));
- assert!(result.contains("\u{1b}[1m")); // Bold
- assert!(result.contains("\u{1b}[32m")); // Green
- }
+ // Bold
+ let bold = render_inline_formatting("**bold**");
+ assert_snapshot!(bold, @"bold");
- #[test]
- fn test_render_markdown_in_help_h3() {
- let result = render_markdown_in_help("### Subsection");
- // H3 should be green (no bold)
- assert!(result.contains("Subsection"));
- assert!(result.contains("\u{1b}[32m")); // Green
- assert!(!result.contains("\u{1b}[1m")); // Not bold
+ // Nested: code inside bold
+ let bold_code = render_inline_formatting("**`wt list`:**");
+ assert_snapshot!(bold_code, @"wt list:");
+
+ // Mixed formatting
+ let mixed = render_inline_formatting("text `code` more **bold** end");
+ assert_snapshot!(mixed, @"text code more bold end");
+
+ // Backticks inside link text
+ let link_code = render_inline_formatting("See [`wt hook`](@/hook.md) for details");
+ assert_snapshot!(link_code, @"See wt hook for details");
+
+ // Unclosed backtick
+ let unclosed_code = render_inline_formatting("`unclosed");
+ assert_snapshot!(unclosed_code, @"unclosed");
+
+ // Unclosed bold
+ let unclosed_bold = render_inline_formatting("**unclosed");
+ assert_snapshot!(unclosed_bold, @"unclosed");
}
+ // ============================================================================
+ // render_markdown_in_help
+ // ============================================================================
+
#[test]
- fn test_render_markdown_in_help_h4() {
- let result = render_markdown_in_help("#### Nested");
- // H4 should be bold (no color)
- assert!(result.contains("Nested"));
- assert!(result.contains("\u{1b}[1m")); // Bold
- assert!(!result.contains("\u{1b}[32m")); // Not green
+ fn test_render_markdown_in_help_headers() {
+ // All header levels in one snapshot to show the visual hierarchy:
+ // H1: UPPERCASE green, H2: bold green, H3: green, H4: bold
+ let md = "# Title\n## Section\n### Subsection\n#### Nested";
+ let result = render_markdown_in_help(md);
+ assert_snapshot!(result, @"
+ TITLE
+ Section
+ Subsection
+ Nested
+ ");
}
#[test]
fn test_render_markdown_in_help_horizontal_rule() {
let result = render_markdown_in_help("before\n\n---\n\n## Section");
- // Horizontal rule becomes visible divider line
- assert!(!result.contains("---"));
- assert!(result.contains("────────────────────────────────────────"));
- assert!(result.contains("before"));
- assert!(result.contains("Section"));
+ assert_snapshot!(result, @"
+ before
+
+ ────────────────────────────────────────
+
+ Section
+ ");
}
#[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"));
+ let result = render_markdown_in_help("```\ncode here\n```\nafter");
+ assert_snapshot!(result, @"
+   code here
+ after
+ ");
}
#[test]
fn test_render_markdown_in_help_toml_code_block() {
- let md = "```toml\n[section]\nkey = \"value\"\n```\nafter";
- let result = render_markdown_in_help(md);
- // TOML blocks get syntax highlighting with gutter
- assert!(result.contains("section"));
- assert!(result.contains("after"));
- // Should have gutter (BrightWhite background = SGR 107)
- assert!(result.contains("\u{1b}[107m"));
+ let result = render_markdown_in_help("```toml\n[section]\nkey = \"value\"\n```\nafter");
+ assert_snapshot!(result, @r#"
+   [section]
+   key = "value"
+ 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"));
+ let result = render_markdown_in_help("<!-- comment -->\nvisible");
+ assert_snapshot!(result, @"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"));
+ assert_snapshot!(result, @"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"));
+ let result = render_markdown_in_help("| A | B |\n| - | - |\n| 1 | 2 |");
+ assert_snapshot!(result, @"
+ A B
+ ─── ───
+ 1 2
+ ");
}
// ============================================================================
- // render_markdown_table Tests
+ // render_markdown_table
// ============================================================================
#[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"));
+ let result = render_markdown_table("| Col1 | Col2 |\n| ---- | ---- |\n| A | B |");
+ assert_snapshot!(result, @"
+ Col1 Col2
+ ──── ────
+ A B
+ ");
}
#[test]
@@ -651,135 +629,72 @@ mod tests {
#[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"));
+ let result =
+ render_markdown_table("Not a table\n| A | B |\nAlso not\n| - | - |\n| 1 | 2 |");
+ assert_snapshot!(result, @"
+ A B
+ ─── ───
+ 1 2
+ ");
}
// ============================================================================
- // colorize_status_symbols Tests
+ // colorize_status_symbols
// ============================================================================
#[test]
- fn test_colorize_status_symbols_working_tree() {
- // These symbols should become cyan
+ fn test_colorize_status_symbols() {
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✘"));
- }
+ // Working tree symbols β†’ cyan
+ let working_tree = colorize_status_symbols(&format!("{dim}+{dim:#} staged"));
+ assert_snapshot!(working_tree, @"+ staged");
- #[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‴"));
- }
+ // Conflicts β†’ red
+ let conflicts = colorize_status_symbols(&format!("{dim}✘{dim:#} conflicts"));
+ assert_snapshot!(conflicts, @"✘ conflicts");
- #[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●"));
- }
+ // Git operations β†’ yellow
+ let git_ops = colorize_status_symbols(&format!("{dim}‴{dim:#} rebase"));
+ assert_snapshot!(git_ops, @"‴ rebase");
- #[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●"));
- }
+ // CI status: passed β†’ green, failed β†’ red, running β†’ blue
+ let ci_passed = colorize_status_symbols("● passed");
+ assert_snapshot!(ci_passed, @"● passed");
- #[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●"));
+ let ci_failed = colorize_status_symbols("● failed");
+ assert_snapshot!(ci_failed, @"● failed");
+
+ let ci_running = colorize_status_symbols("● running");
+ assert_snapshot!(ci_running, @"● running");
}
#[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
+ // render_table
// ============================================================================
#[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_bold_with_code() {
- // Nested formatting: **`wt list`:** should render code inside bold
- let result = render_inline_formatting("**`wt list`:**");
- assert!(result.contains("wt list"));
- assert!(result.contains("\u{1b}[1m")); // Bold
- assert!(result.contains("\u{1b}[2m")); // Dimmed (for code)
- assert!(!result.contains('`')); // Backticks should be consumed
- }
-
- #[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"));
+ fn test_render_table_escaped_pipe() {
+ let lines = vec![
+ "| Category | Symbol | Meaning |",
+ "| --- | --- | --- |",
+ r"| Remote | `\|` | In sync |",
+ ];
+ let result = render_table(&lines, None);
+ assert_snapshot!(result, @"
+ Category Symbol Meaning
+ ──────── ────── ───────
+ Remote | In sync
+ ");
}
- // ============================================================================
- // render_markdown_table_impl Tests (via render_table)
- // ============================================================================
-
#[test]
fn test_render_table_column_alignment() {
let lines = vec![
@@ -788,38 +703,36 @@ mod tests {
"| A | B |",
];
let result = render_table(&lines, None);
- // Should have proper column alignment
- assert!(result.contains("Short"));
- assert!(result.contains("LongerHeader"));
- // Should have separator line with ─
- assert!(result.contains('─'));
+ assert_snapshot!(result, @"
+ Short LongerHeader
+ ───── ────────────
+ A B
+ ");
}
#[test]
fn test_render_table_uneven_columns() {
let lines = vec!["| A | B | C |", "| --- | --- | --- |", "| 1 | 2 |"];
let result = render_table(&lines, None);
- // Should handle rows with different column counts
- assert!(result.contains("A"));
- assert!(result.contains("1"));
+ assert_snapshot!(result, @"
+ A B C
+ ─── ─── ───
+ 1 2
+ ");
}
#[test]
fn test_render_table_no_separator() {
- // Table without separator row
let lines = vec!["| A | B |", "| 1 | 2 |"];
let result = render_table(&lines, None);
- // Should still render, just without separator line
- assert!(result.contains("A"));
- assert!(result.contains("1"));
- // Should NOT have separator line
- assert!(!result.contains('─'));
+ assert_snapshot!(result, @"
+ A B
+ 1 2
+ ");
}
#[test]
fn test_render_markdown_in_help_table_wrapping() {
- // Test the full render_markdown_in_help_with_width function
- // which is what actually runs on the help text
let help = r#"### Other environment variables
| Variable | Purpose |
@@ -829,20 +742,18 @@ mod tests {
| `WORKTRUNK_MAX_CONCURRENT_COMMANDS` | Max parallel git commands (default: 32). Lower if hitting resource limits. |
| NO_COLOR | Disable colored output (standard) |
"#;
- let rendered = render_markdown_in_help_with_width(help, Some(80));
-
- // Check for pipe characters
- for line in rendered.lines() {
- assert!(
- !line.trim_start().starts_with("| "),
- "Line should not start with '| ': {:?}",
- line
- );
- assert!(
- !line.trim_end().ends_with(" |"),
- "Line should not end with ' |': {:?}",
- line
- );
- }
+ let result = render_markdown_in_help_with_width(help, Some(80));
+ assert_snapshot!(result, @"
+ Other environment variables
+
+ Variable Purpose
+ ───────────────────────────────── ────────────────────────────────────────────
+ WORKTRUNK_BIN Override binary path for shell wrappers
+ (useful for testing dev builds)
+ WORKTRUNK_CONFIG_PATH Override user config file location
+ WORKTRUNK_MAX_CONCURRENT_COMMANDS Max parallel git commands (default: 32).
+ Lower if hitting resource limits.
+ NO_COLOR Disable colored output (standard)
+ ");
}
}
diff --git a/src/output/commit_generation.rs b/src/output/commit_generation.rs
index 166c84db0..38cabad77 100644
--- a/src/output/commit_generation.rs
+++ b/src/output/commit_generation.rs
@@ -188,6 +188,7 @@ pub fn prompt_commit_generation(config: &mut UserConfig) -> anyhow::Result<bool>
#[cfg(test)]
mod tests {
use super::*;
+ use insta::assert_snapshot;
#[test]
fn test_llm_tool_command_name() {
@@ -197,13 +198,8 @@ mod tests {
#[test]
fn test_llm_tool_recommended_config() {
- let claude_config = LlmTool::Claude.recommended_config();
- assert!(claude_config.contains("claude"));
- assert!(claude_config.contains("haiku"));
-
- let codex_config = LlmTool::Codex.recommended_config();
- assert!(codex_config.contains("codex exec"));
- assert!(codex_config.contains("gpt-5.1-codex-mini"));
+ assert_snapshot!(LlmTool::Claude.recommended_config(), @"MAX_THINKING_TOKENS=0 claude -p --model=haiku --tools='' --disable-slash-commands --setting-sources='' --system-prompt=''");
+ assert_snapshot!(LlmTool::Codex.recommended_config(), @r#"codex exec -m gpt-5.1-codex-mini -c model_reasoning_effort='low' --sandbox=read-only --json - | jq -sr '[.[] | select(.item.type? == "agent_message")] | last.item.text'"#);
}
#[test]
@@ -221,19 +217,13 @@ mod tests {
// Long commands stay as single-line TOML
let cmd = LlmTool::Claude.recommended_config();
let result = format_command_for_display(cmd);
- assert!(result.starts_with('"') || result.starts_with('\''));
- assert!(result.contains("claude"));
- assert!(result.contains("haiku"));
+ assert_snapshot!(result, @r#""MAX_THINKING_TOKENS=0 claude -p --model=haiku --tools='' --disable-slash-commands --setting-sources='' --system-prompt=''""#);
}
#[test]
fn test_format_command_special_chars() {
let result = format_command_for_display(r#"echo "hello""#);
- // toml crate may use literal strings ('...') or basic strings ("...")
- assert!(
- result.contains("echo") && result.contains("hello"),
- "Command content should be preserved: {result}"
- );
+ assert_snapshot!(result, @r#"'echo "hello"'"#);
}
#[test]
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 34efa4a61..234ee1134 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1341,6 +1341,7 @@ pub fn execute_command_in_worktree(
#[cfg(test)]
mod tests {
use super::*;
+ use insta::assert_snapshot;
#[test]
fn test_format_switch_message() {
@@ -1348,29 +1349,21 @@ mod tests {
// Switched to existing worktree (no creation)
let msg = format_switch_message("feature", &path, false, false, None, None);
- assert!(msg.contains("Switched to worktree for"));
- assert!(msg.contains("feature"));
+ assert_snapshot!(msg, @"Switched to worktree for feature @ /tmp/test");
// Created branch and worktree with --create
let msg = format_switch_message("feature", &path, true, true, Some("main"), None);
- assert!(msg.contains("Created branch"));
- assert!(msg.contains("and worktree"));
- assert!(msg.contains("from"));
- assert!(msg.contains("main"));
+ assert_snapshot!(msg, @"Created branch feature from main and worktree @ /tmp/test");
// Created worktree from remote (DWIM) - also creates local tracking branch
let msg =
format_switch_message("feature", &path, true, false, None, Some("origin/feature"));
- assert!(msg.contains("Created branch"));
- assert!(msg.contains("tracking"));
- assert!(msg.contains("origin/feature"));
- assert!(msg.contains("and worktree"));
+ assert_snapshot!(msg, @"Created branch feature (tracking origin/feature) and worktree @ /tmp/test");
// Created worktree only (local branch already existed)
let msg = format_switch_message("feature", &path, true, false, None, None);
- assert!(msg.contains("Created worktree for"));
- assert!(msg.contains("feature"));
assert!(!msg.contains("branch")); // Should NOT mention branch creation
+ assert_snapshot!(msg, @"Created worktree for feature @ /tmp/test");
}
#[test]
@@ -1497,13 +1490,12 @@ mod tests {
#[test]
fn test_shell_integration_hint() {
let hint = shell_integration_hint();
- assert!(hint.contains("wt config shell install"));
+ assert_snapshot!(hint, @"To enable automatic cd, run wt config shell install");
}
#[test]
fn test_git_subcommand_warning() {
let warning = git_subcommand_warning();
- assert!(warning.contains("git-wt"));
- assert!(warning.contains("with the"));
+ assert_snapshot!(warning, @"For automatic cd, invoke directly (with the -): git-wt");
}
}
diff --git a/src/output/shell_integration.rs b/src/output/shell_integration.rs
index 2821f8d1e..2ab7d2881 100644
--- a/src/output/shell_integration.rs
+++ b/src/output/shell_integration.rs
@@ -454,47 +454,42 @@ pub fn prompt_shell_integration(
#[cfg(test)]
mod tests {
use super::*;
+ use insta::assert_snapshot;
#[test]
fn test_shell_integration_hint() {
let hint = shell_integration_hint();
- assert!(hint.contains("wt config shell install"));
+ assert_snapshot!(hint, @"To enable automatic cd, run wt config shell install");
}
#[test]
fn test_git_subcommand_warning() {
let warning = git_subcommand_warning();
- assert!(warning.contains("git-wt"));
- assert!(warning.contains("with the"));
+ assert_snapshot!(warning, @"For automatic cd, invoke directly (with the -): git-wt");
}
#[test]
- fn test_compute_shell_warning_reason_not_installed() {
+ fn test_compute_shell_warning_reason() {
// Shell integration not configured -> "not installed"
let reason = compute_shell_warning_reason_inner(false, false, "wt", "wt");
assert_eq!(reason, "shell integration not installed");
- }
- #[test]
- fn test_compute_shell_warning_reason_explicit_path_same_name() {
// When filename matches wraps, show full path (the path IS the useful info)
let reason = compute_shell_warning_reason_inner(true, true, "./target/debug/wt", "wt");
- assert!(reason.contains("./target/debug/wt"));
- assert!(reason.contains("wraps"));
- }
+ assert_snapshot!(reason, @"ran ./target/debug/wt; shell integration wraps wt");
- #[test]
- fn test_compute_shell_warning_reason_explicit_path_different_binary() {
// When invoked binary differs from wrapped binary, show both
let reason = compute_shell_warning_reason_inner(true, true, "/usr/local/bin/git-wt", "wt");
- assert!(reason.contains("git-wt"));
- assert!(reason.contains("wt"));
- assert!(reason.contains("wraps"));
+ assert_snapshot!(reason, @"ran git-wt; shell integration wraps wt");
+
+ // Shell integration configured + NOT explicit path -> "shell requires restart"
+ let reason = compute_shell_warning_reason_inner(true, false, "wt", "wt");
+ assert_eq!(reason, "shell requires restart");
}
#[test]
#[cfg(windows)]
- fn test_compute_shell_warning_reason_windows_exe_suffix() {
+ fn test_compute_shell_warning_reason_windows() {
// Windows: invoked as git-wt.exe, wraps git-wt -> targeted .exe message
let reason = compute_shell_warning_reason_inner(
true,
@@ -503,32 +498,26 @@ mod tests {
"git-wt",
);
// Should extract filename and give targeted advice
- assert!(reason.contains("git-wt.exe"));
- assert!(reason.contains("without .exe"));
assert!(!reason.contains(r"C:\Users")); // No full path
- }
+ assert!(reason.contains("git-wt.exe"), "{reason}");
+ assert!(reason.contains("without .exe"), "{reason}");
- #[test]
- #[cfg(windows)]
- fn test_compute_shell_warning_reason_windows_exe_case_insensitive() {
// Windows paths are case-insensitive
let reason = compute_shell_warning_reason_inner(true, true, r"C:\path\to\WT.EXE", "wt");
- assert!(reason.contains("without .exe"));
- }
-
- #[test]
- fn test_compute_shell_warning_reason_needs_restart() {
- // Shell integration configured + NOT explicit path -> "shell requires restart"
- let reason = compute_shell_warning_reason_inner(true, false, "wt", "wt");
- assert_eq!(reason, "shell requires restart");
+ assert!(
+ reason.contains("WT.EXE") || reason.contains(".exe"),
+ "{reason}"
+ );
}
#[test]
fn test_explicit_path_hint_format() {
- // Verify hint contains the branch name and "switch" command
let hint = explicit_path_hint("feature-branch");
- assert!(hint.contains("switch"));
- assert!(hint.contains("feature-branch"));
- assert!(hint.contains("To change directory"));
+ // binary_name() returns the test binary hash in test context; normalize it
+ let mut settings = insta::Settings::clone_current();
+ settings.add_filter(r"wt-[0-9a-f]+", "wt");
+ settings.bind(|| {
+ assert_snapshot!(hint, @"To change directory, run wt switch feature-branch");
+ });
}
}
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index f53c672ed..21c3ec769 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -1075,14 +1075,6 @@ mod tests {
);
}
- #[test]
- fn test_shell_config_debug() {
- let config = ShellConfig::get().unwrap();
- let debug = format!("{:?}", config);
- assert!(debug.contains("ShellConfig"));
- assert!(debug.contains(&config.name));
- }
-
#[test]
fn test_shell_config_clone() {
let config = ShellConfig::get().unwrap();
diff --git a/src/styling/constants.rs b/src/styling/constants.rs
index 83511c2ea..4cfaaca31 100644
--- a/src/styling/constants.rs
+++ b/src/styling/constants.rs
@@ -244,151 +244,49 @@ pub fn format_heading(title: &str, suffix: Option<&str>) -> String {
#[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"));
- }
+ use insta::assert_snapshot;
- // ============================================================================
- // Symbol Constants Tests
- // ============================================================================
+ use super::*;
#[test]
fn test_symbol_constants() {
- // Symbols are pre-colored with ANSI codes, but contain the Unicode character
- assert!(PROGRESS_SYMBOL.contains("β—Ž"));
- assert!(SUCCESS_SYMBOL.contains("βœ“"));
- assert!(ERROR_SYMBOL.contains("βœ—"));
- assert!(WARNING_SYMBOL.contains("β–²"));
- assert!(HINT_SYMBOL.contains("↳"));
- assert!(INFO_SYMBOL.contains("β—‹"));
- assert!(PROMPT_SYMBOL.contains("❯"));
+ assert_snapshot!(PROGRESS_SYMBOL, @"β—Ž");
+ assert_snapshot!(SUCCESS_SYMBOL, @"βœ“");
+ assert_snapshot!(ERROR_SYMBOL, @"βœ—");
+ assert_snapshot!(WARNING_SYMBOL, @"β–²");
+ assert_snapshot!(HINT_SYMBOL, @"↳");
+ assert_snapshot!(INFO_SYMBOL, @"β—‹");
+ assert_snapshot!(PROMPT_SYMBOL, @"❯");
}
- // ============================================================================
- // Message Formatting Functions Tests
- // ============================================================================
-
#[test]
- fn test_error_message() {
- let msg = error_message("Something went wrong");
- assert!(msg.as_str().contains(ERROR_SYMBOL));
- assert!(msg.as_str().contains("Something went wrong"));
+ fn test_message_formatting() {
+ assert_snapshot!(error_message("Something went wrong").as_str(), @"βœ— Something went wrong");
+ assert_snapshot!(hint_message("Try running --help").as_str(), @"↳ Try running --help");
+ assert_snapshot!(warning_message("Deprecated option").as_str(), @"β–² Deprecated option");
+ assert_snapshot!(success_message("Operation completed").as_str(), @"βœ“ Operation completed");
+ assert_snapshot!(progress_message("Loading data...").as_str(), @"β—Ž Loading data...");
+ assert_snapshot!(info_message("5 items found").as_str(), @"β—‹ 5 items found");
+ assert_snapshot!(prompt_message("Continue?").as_str(), @"❯ Continue?");
}
#[test]
fn test_error_message_with_inner_styling() {
let name = "feature";
let msg = error_message(cformat!("Branch <bold>{name}</> not found"));
- assert!(msg.as_str().contains(ERROR_SYMBOL));
- assert!(msg.as_str().contains("Branch"));
- assert!(msg.as_str().contains("feature"));
- }
-
- #[test]
- fn test_hint_message() {
- let msg = hint_message("Try running --help");
- assert!(msg.as_str().contains(HINT_SYMBOL));
- assert!(msg.as_str().contains("Try running --help"));
+ assert_snapshot!(msg.as_str(), @"βœ— Branch feature not found");
}
#[test]
- fn test_warning_message() {
- let msg = warning_message("Deprecated option");
- assert!(msg.as_str().contains(WARNING_SYMBOL));
- assert!(msg.as_str().contains("Deprecated option"));
+ fn test_format_heading() {
+ assert_snapshot!(format_heading("BINARIES", None), @"BINARIES");
+ assert_snapshot!(format_heading("USER CONFIG", Some("~/.config/wt.toml")), @"USER CONFIG ~/.config/wt.toml");
+ assert_snapshot!(format_heading("", None), @"");
}
- #[test]
- fn test_success_message() {
- let msg = success_message("Operation completed");
- assert!(msg.as_str().contains(SUCCESS_SYMBOL));
- assert!(msg.as_str().contains("Operation completed"));
- }
-
- #[test]
- fn test_progress_message() {
- let msg = progress_message("Loading data...");
- assert!(msg.as_str().contains(PROGRESS_SYMBOL));
- assert!(msg.as_str().contains("Loading data..."));
- }
-
- #[test]
- fn test_info_message() {
- let msg = info_message("5 items found");
- assert!(msg.as_str().contains(INFO_SYMBOL));
- assert!(msg.as_str().contains("5 items found"));
- }
-
- #[test]
- fn test_prompt_message() {
- let msg = prompt_message("Continue?");
- assert!(msg.as_str().contains(PROMPT_SYMBOL));
- assert!(msg.as_str().contains("Continue?"));
- }
-
- // ============================================================================
- // 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"));
- // Title and suffix separated by single space (plus ANSI reset between them)
- 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}'));
- }
-
- // ============================================================================
- // FormattedMessage Tests
- // ============================================================================
-
#[test]
fn test_formatted_message_into_inner() {
let msg = success_message("Done");
- let inner: String = msg.into_inner();
- assert!(inner.contains(SUCCESS_SYMBOL));
- assert!(inner.contains("Done"));
+ assert_snapshot!(msg.into_inner(), @"βœ“ Done");
}
}
diff --git a/src/styling/format.rs b/src/styling/format.rs
index e49402c1a..68b200ab4 100644
--- a/src/styling/format.rs
+++ b/src/styling/format.rs
@@ -420,79 +420,55 @@ pub fn format_bash_with_gutter(content: &str) -> String {
#[cfg(test)]
mod tests {
- use super::*;
-
- #[test]
- fn test_wrap_text_at_width_no_wrap_needed() {
- let result = wrap_text_at_width("short text", 20);
- assert_eq!(result, vec!["short text"]);
- }
-
- #[test]
- fn test_wrap_text_at_width_basic_wrap() {
- let result = wrap_text_at_width("hello world foo bar", 10);
- // Words wrap at boundaries, each line fits within max_width
- assert_eq!(result, vec!["hello", "world foo", "bar"]);
- }
-
- #[test]
- fn test_wrap_text_at_width_zero_width() {
- let result = wrap_text_at_width("hello world", 0);
- assert_eq!(result, vec!["hello world"]);
- }
-
- #[test]
- fn test_wrap_text_at_width_empty_input() {
- let result = wrap_text_at_width("", 20);
- assert_eq!(result, vec![""]);
- }
-
- #[test]
- fn test_wrap_text_at_width_single_long_word() {
- // Single word longer than max_width should still be included
- let result = wrap_text_at_width("superlongword", 5);
- assert_eq!(result, vec!["superlongword"]);
- }
-
- #[test]
- fn test_wrap_styled_text_no_wrap_needed() {
- let result = wrap_styled_text("short text", 20);
- assert_eq!(result, vec!["short text"]);
- }
+ use insta::assert_snapshot;
- #[test]
- fn test_wrap_styled_text_zero_width() {
- let result = wrap_styled_text("hello world", 0);
- assert_eq!(result, vec!["hello world"]);
- }
-
- #[test]
- fn test_wrap_styled_text_empty_input() {
- let result = wrap_styled_text("", 20);
- assert_eq!(result, vec![""]);
- }
+ use super::*;
+ /// Wraps at word boundaries; never breaks a word; degrades gracefully on edge cases.
#[test]
- fn test_wrap_styled_text_preserves_leading_whitespace() {
- let result = wrap_styled_text(" Print help", 80);
- assert_eq!(result, vec![" Print help"]);
+ fn test_wrap_text_at_width() {
+ assert_eq!(wrap_text_at_width("short text", 20), vec!["short text"]);
+ assert_eq!(
+ wrap_text_at_width("hello world foo bar", 10),
+ vec!["hello", "world foo", "bar"]
+ );
+ // Single long word is never broken
+ assert_eq!(
+ wrap_text_at_width("superlongword", 5),
+ vec!["superlongword"]
+ );
+ // Multiple spaces preserved when no wrapping needed
+ assert_eq!(
+ wrap_text_at_width("hello world", 20),
+ vec!["hello world"]
+ );
+ // Edge cases: zero width and empty input
+ assert_eq!(wrap_text_at_width("hello world", 0), vec!["hello world"]);
+ assert_eq!(wrap_text_at_width("", 20), vec![""]);
}
+ /// Same word-boundary contract as wrap_text_at_width, plus preserves leading indent.
#[test]
- fn test_wrap_styled_text_only_whitespace() {
- let result = wrap_styled_text(" ", 80);
- assert_eq!(result, vec![" "]);
+ fn test_wrap_styled_text_edge_cases() {
+ assert_eq!(wrap_styled_text("short text", 20), vec!["short text"]);
+ assert_eq!(wrap_styled_text("hello world", 0), vec!["hello world"]);
+ assert_eq!(wrap_styled_text("", 20), vec![""]);
+ // Whitespace is preserved
+ assert_eq!(
+ wrap_styled_text(" Print help", 80),
+ vec![" Print help"]
+ );
+ assert_eq!(wrap_styled_text(" ", 80), vec![" "]);
}
+ /// Continuation lines keep the same leading indent as the first line.
#[test]
fn test_wrap_styled_text_preserves_indent_on_wrap() {
- // Force wrapping by using a narrow width - text should wrap and preserve indent
let result = wrap_styled_text(
" This is a longer text that should wrap across multiple lines",
40,
);
assert!(result.len() > 1);
- // All lines should have the 10-space indent
for line in &result {
assert!(
line.starts_with(" "),
@@ -502,142 +478,75 @@ mod tests {
}
}
+ /// Gutter formatting: single, multiline, empty, and wrapping cases.
#[test]
- fn test_format_with_gutter_basic() {
- let result = format_with_gutter("hello", Some(80));
- // Should have gutter formatting, no trailing newline (caller adds it)
- assert!(result.contains("hello"));
- assert!(!result.ends_with('\n'));
- }
-
- #[test]
- fn test_format_with_gutter_multiline() {
- let result = format_with_gutter("line1\nline2", Some(80));
- // Each line should be formatted separately
- assert!(result.contains("line1"));
- assert!(result.contains("line2"));
- // Should have 1 newline (between lines, not trailing)
- assert_eq!(result.matches('\n').count(), 1);
- }
-
- #[test]
- fn test_gutter_overhead_constant() {
- // Verify the overhead matches documented value
- assert_eq!(GUTTER_OVERHEAD, 2);
- }
-
- #[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_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 (newlines between, not trailing)
- let line_count = result.matches('\n').count();
- assert!(
- line_count >= 1,
- "Expected at least one newline (between wrapped 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"));
- }
-
+ fn test_format_with_gutter() {
+ assert_snapshot!(format_with_gutter("hello", Some(80)), @"  hello");
+ assert_snapshot!(format_with_gutter("line1\nline2", Some(80)), @"
+   line1
+   line2
+ ");
+ assert_snapshot!(format_with_gutter("", Some(80)), @"");
+ assert_snapshot!(format_with_gutter("word1 word2 word3 word4", Some(15)), @"
+   word1 word2
+   word3 word4
+ ");
+ }
+
+ /// ANSI codes don't affect wrapping width and are preserved in output.
#[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"));
+ assert_snapshot!(result[0], @"bold text here");
}
+ /// wrap_ansi's injected [39m]/[49m] resets are stripped (we use [0m] only).
#[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"));
}
+ /// Continuation lines after wrap restore dim styling (wrap_ansi drops it).
#[test]
fn test_wrap_styled_text_restores_dim_on_continuation() {
- // When wrap_ansi wraps dim+color text, it restores the color but not dim.
- // We fix this by prepending dim to continuation lines that start with a color.
let dim = "\x1b[2m";
let green = "\x1b[32m";
let reset = "\x1b[0m";
-
- // Simulate what format_bash_with_gutter_impl produces for a string token
let styled = format!(
"{dim}{green}This is a very long string that definitely needs to wrap across multiple lines{reset}"
);
- // Force wrapping at 30 chars - should produce multiple lines
let result = wrap_styled_text(&styled, 30);
assert!(result.len() > 1);
-
- // First line should have dim+green (as input)
assert!(result[0].starts_with("\x1b[2m\x1b[32m"));
-
- // Continuation lines should ALSO have dim before the color (restored by our fix)
for line in result.iter().skip(1) {
assert!(line.starts_with("\x1b[2m\x1b[32m") || line.starts_with("\x1b[2m"));
}
}
+ /// Bash syntax highlighting with gutter: single-line, multi-line, complex commands.
#[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"));
- // No trailing newline - caller is responsible for element separation
- 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 one newline (between, not trailing)
- assert_eq!(result.matches('\n').count(), 1);
- }
-
- #[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"));
+ fn test_format_bash_with_gutter() {
+ assert_snapshot!(format_bash_with_gutter_at_width("echo hello", 80), @"  echo hello");
+ assert_snapshot!(
+ format_bash_with_gutter_at_width("echo line1\necho line2", 80),
+ @"
+   echo line1
+   echo line2
+ "
+ );
+ assert_snapshot!(
+ format_bash_with_gutter_at_width("npm install && cargo build --release", 100),
+ @"  npm install && cargo build --release"
+ );
}
- /// Regression test: tree-sitter 0.26 properly highlights multi-line commands.
- ///
- /// With tree-sitter-bash 0.25.1+, unified highlighting (processing the entire
- /// command at once) correctly identifies `&&` as operators even when they appear
- /// at line ends. This enables switching from line-by-line to unified highlighting.
+ /// Regression: tree-sitter identifies `&&` as operators even at line ends.
#[test]
#[cfg(feature = "syntax-highlighting")]
fn test_unified_multiline_highlighting() {
@@ -659,7 +568,6 @@ mod tests {
let mut highlighter = Highlighter::new();
- // Collect highlight events as tagged text for verification
let mut output = String::new();
let highlights = highlighter
.highlight(&config, cmd.as_bytes(), None, |_| None)
@@ -678,26 +586,14 @@ mod tests {
}
}
- // Unified highlighting should identify && as operators
- assert!(
- output.contains("[operator:&&]"),
- "Should identify && as operator in multi-line command"
- );
-
- // Should identify echo as function on each line
- assert_eq!(
- output.matches("[function:echo]").count(),
- 3,
- "Should identify all three echo commands"
- );
+ assert_snapshot!(output, @"
+ [function:echo] [string:'line1'] [operator:&&]
+ [function:echo] [string:'line2'] [operator:&&]
+ [function:echo] [string:'line3']
+ ");
}
- /// Regression test: template variables inside quotes are restored correctly.
- ///
- /// When `{{ }}` appears inside double quotes (e.g., `"{{ target }}"`), the
- /// placeholder must not contain quote characters β€” otherwise tree-sitter
- /// reinterprets quote boundaries and ANSI codes break the contiguous
- /// placeholder, making the restore `.replace()` fail silently.
+ /// Regression: `{{ }}` inside double quotes are restored without breaking highlighting.
#[test]
#[cfg(feature = "syntax-highlighting")]
fn test_template_vars_inside_quotes_restored() {
@@ -706,18 +602,10 @@ mod tests {
let cmd = r#"if [ "{{ target }}" = "main" ]; then git pull && git push; fi"#;
let result = format_bash_with_gutter_at_width(cmd, 120);
- let plain = result.ansi_strip();
-
- // The output must contain {{ and }}, not the placeholders
- assert!(plain.contains("{{"), "{plain}");
- assert!(plain.contains("}}"), "{plain}");
- assert!(!plain.contains("WTO"), "{plain}");
- assert!(!plain.contains("WTC"), "{plain}");
+ assert_snapshot!(result.ansi_strip(), @r#" if [ "{{ target }}" = "main" ]; then git pull && git push; fi"#);
}
- /// Regression test: template syntax ({{ }}) doesn't break highlighting.
- ///
- /// Tree-sitter parses around template variables, still identifying commands.
+ /// Regression: template syntax `{{ }}` doesn't prevent command identification.
#[test]
#[cfg(feature = "syntax-highlighting")]
fn test_highlighting_with_template_syntax() {
@@ -754,18 +642,6 @@ mod tests {
}
}
- // Commands should still be identified despite template syntax
- assert!(
- output.contains("[function:echo]"),
- "Should identify echo despite template syntax"
- );
- assert!(
- output.contains("[function:mkdir]"),
- "Should identify mkdir despite template syntax"
- );
- assert!(
- output.contains("[operator:&&]"),
- "Should identify && operator"
- );
+ assert_snapshot!(output, @"[function:echo] {{ branch }} [operator:&&] [function:mkdir] {{ path }}");
}
}
diff --git a/src/styling/highlighting.rs b/src/styling/highlighting.rs
index 3e830ed37..9eef3313d 100644
--- a/src/styling/highlighting.rs
+++ b/src/styling/highlighting.rs
@@ -173,154 +173,87 @@ fn toml_token_style(kind: &str) -> Option<Style> {
#[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)));
- }
+ use insta::assert_snapshot;
- #[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)));
- }
+ use super::*;
+ /// Each bash token type maps to the expected color.
#[test]
#[cfg(feature = "syntax-highlighting")]
- fn test_bash_token_style_unknown() {
- // Unknown tokens should return None
+ fn test_bash_token_styles() {
+ let cases = [
+ ("function", AnsiColor::Blue),
+ ("keyword", AnsiColor::Magenta),
+ ("string", AnsiColor::Green),
+ ("operator", AnsiColor::Cyan),
+ ("constant", AnsiColor::Cyan),
+ ("property", AnsiColor::Yellow),
+ ("number", AnsiColor::Yellow),
+ ];
+ for (name, expected_color) in cases {
+ let style =
+ bash_token_style(name).unwrap_or_else(|| panic!("{name} should have a style"));
+ assert_eq!(
+ style.get_fg_color(),
+ Some(Color::Ansi(expected_color)),
+ "{name} should be {expected_color:?}"
+ );
+ }
+ // Unknown/unstyled tokens return None
assert!(bash_token_style("unknown").is_none());
assert!(bash_token_style("comment").is_none());
assert!(bash_token_style("embedded").is_none());
}
+ /// Each TOML token type maps to the expected color.
#[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
+ fn test_toml_token_styles() {
+ let cases = [
+ ("string", AnsiColor::Green),
+ ("table", AnsiColor::Cyan),
+ ("boolean", AnsiColor::Yellow),
+ ("digit", AnsiColor::Yellow),
+ ];
+ for (name, expected_color) in cases {
+ let style =
+ toml_token_style(name).unwrap_or_else(|| panic!("{name} should have a style"));
+ assert_eq!(
+ style.get_fg_color(),
+ Some(Color::Ansi(expected_color)),
+ "{name} should be {expected_color:?}"
+ );
+ }
+ // Comments have a style but no specific color (dimmed)
+ assert!(toml_token_style("comment").is_some());
+ // Unknown tokens return None
assert!(toml_token_style("unknown").is_none());
assert!(toml_token_style("key").is_none());
assert!(toml_token_style("operator").is_none());
}
+ /// format_toml produces highlighted, guttered output for various inputs.
#[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);
+ fn test_format_toml() {
+ assert_snapshot!(format_toml("[section]\nkey = \"value\""), @r#"
+   [section]
+   key = "value"
+ "#);
+ assert_snapshot!(
+ format_toml("[table]\nkey1 = \"value1\"\nkey2 = 42\n# comment\nkey3 = false"),
+ @r#"
+   [table]
+   key1 = "value1"
+   key2 = 42
+   # comment
+   key3 = false
+ "#
+ );
+ assert_snapshot!(format_toml(""), @"");
}
+ /// format_toml handles both styled tokens (string, table) and unstyled text.
#[test]
fn test_format_toml_has_styled_and_unstyled_text() {
- // This test verifies that format_toml handles both styled tokens (string, table)
- // and unstyled text (TokOpt::None for whitespace, punctuation)
use synoptic::{TokOpt, from_extension};
let content = "key = \"value\"";
@@ -328,7 +261,6 @@ mod tests {
let lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
highlighter.run(&lines);
- // Collect token types
let mut has_styled = false;
let mut has_unstyled = false;
for (y, line) in lines.iter().enumerate() {
@@ -346,32 +278,10 @@ mod tests {
}
}
- // Should have styled token (the string "value")
assert!(has_styled, "Should have at least one styled token");
- // Should have unstyled text (whitespace, "=", "key")
assert!(
has_unstyled,
"Should have at least one unstyled text segment"
);
}
-
- #[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 65b824317..9404f331a 100644
--- a/src/styling/line.rs
+++ b/src/styling/line.rs
@@ -159,239 +159,128 @@ impl StyledLine {
#[cfg(test)]
mod tests {
+ use insta::assert_snapshot;
+
use super::*;
+ /// Width calculation ignores ANSI escape codes and OSC 8 hyperlinks.
#[test]
- fn test_width_strips_osc_hyperlinks() {
- // Text with OSC 8 hyperlink should have visual width of just the text
+ fn test_width_ignores_invisible_characters() {
+ // OSC 8 hyperlink: visual width is just the link text
let url = "https://github.com/user/repo/pull/123";
- let text_content = "●";
let hyperlinked = format!(
"{}{}{}",
osc8::Hyperlink::new(url),
- text_content,
+ "●",
osc8::Hyperlink::END
);
+ assert_eq!(StyledString::raw(&hyperlinked).width(), 1);
- let styled_str = StyledString::raw(&hyperlinked);
- assert_eq!(
- styled_str.width(),
- 1,
- "Hyperlinked '●' should have width 1, not {}",
- styled_str.width()
- );
- }
-
- #[test]
- fn test_width_strips_sgr_codes() {
- // Text with SGR color codes should have visual width of just the text
+ // SGR color codes are invisible
use anstyle::{AnsiColor, Color, Style};
let green = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green)));
let colored = format!("{}●{}", green.render(), green.render_reset());
+ assert_eq!(StyledString::raw(colored).width(), 1);
- let styled_str = StyledString::raw(colored);
- assert_eq!(
- styled_str.width(),
- 1,
- "Colored '●' should have width 1, not {}",
- styled_str.width()
- );
- }
-
- #[test]
- fn test_width_with_combined_ansi_codes() {
- // Text with both color and hyperlink
- use anstyle::{AnsiColor, Color, Style};
- let url = "https://example.com";
+ // Combined color + hyperlink
let yellow = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)));
let combined = format!(
"{}{}● passed{}{}",
yellow.render(),
- osc8::Hyperlink::new(url),
+ osc8::Hyperlink::new("https://example.com"),
osc8::Hyperlink::END,
yellow.render_reset()
);
+ assert_eq!(StyledString::raw(&combined).width(), 8); // "● passed"
- let styled_str = StyledString::raw(&combined);
- // "● passed" = 1 + 1 (space) + 6 = 8
- assert_eq!(
- styled_str.width(),
- 8,
- "Combined styled text should have width 8, not {}",
- styled_str.width()
- );
- }
-
- /// Helper to compute visible width for tests
- fn visible_width(rendered: &str) -> usize {
- UnicodeWidthStr::width(rendered.ansi_strip().as_ref())
- }
-
- #[test]
- fn test_visible_width_strips_osc8() {
+ // OSC-8 via raw escape sequences
let s = "\u{1b}]8;;https://example.com\u{1b}\\A\u{1b}]8;;\u{1b}\\";
- assert_eq!(visible_width(s), 1, "OSC-8 should be zero-width");
+ assert_eq!(UnicodeWidthStr::width(s.ansi_strip().as_ref()), 1,);
}
+ /// truncate_visible respects visual width, handles emoji, and appends reset codes.
#[test]
- fn test_truncate_visible_preserves_budget_and_resets() {
+ fn test_truncate_visible() {
+ use ansi_str::AnsiStr;
+
+ let visible_width = |s: &str| UnicodeWidthStr::width(s.ansi_strip().as_ref());
+
+ // Truncates colored text to budget, ends with reset
let colored = "\u{1b}[31mhello\u{1b}[0m";
let out = truncate_visible(colored, 3);
assert_eq!(visible_width(&out), 3);
assert!(out.ends_with("\u{1b}[0m"));
- }
- #[test]
- fn test_truncate_visible_handles_wide_emoji() {
- let rocket = "πŸš€";
- let out = truncate_visible(rocket, 1);
+ // Wide emoji (width 2) truncated to budget 1
+ let out = truncate_visible("πŸš€", 1);
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 β†’ empty
+ assert!(truncate_visible("hello world", 0).is_empty());
- #[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");
- }
+ // No truncation when text fits
+ assert_eq!(truncate_visible("short", 100), "short");
- #[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"
- );
+ // Budget of 1 stays within limit
+ let out = truncate_visible("hello", 1);
+ assert!(visible_width(&out) <= 1);
}
+ /// StyledLine composition: push, extend, render, plain_text all produce correct output.
#[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() {
+ fn test_styled_line_composition() {
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
- }
+ assert_eq!(line.width(), 12);
+ assert_eq!(line.plain_text(), "hello world!");
- #[test]
- fn test_styled_line_extend() {
- let mut line1 = StyledLine::new();
- line1.push_raw("hello");
+ // render() includes ANSI codes but preserves text
+ assert_snapshot!(line.render(), @"hello world!");
- 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");
+ // extend merges segments
+ let mut a = StyledLine::new();
+ a.push_raw("hello");
+ let mut b = StyledLine::new();
+ b.push_raw(" world");
+ a.extend(b);
+ assert_eq!(a.plain_text(), "hello world");
}
+ /// pad_to adds spaces up to target width; never shrinks.
#[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
- }
+ assert!(line.plain_text().ends_with(" "));
- #[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");
+ // Already wider than target: no change
+ line.pad_to(3);
+ assert_eq!(line.width(), 5);
}
+ /// truncate_to_width clips long lines and preserves short ones.
#[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");
- }
+ fn test_styled_line_truncate_to_width() {
+ let mut short = StyledLine::new();
+ short.push_raw("hello");
+ assert_eq!(short.clone().truncate_to_width(100).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);
+ let mut long = StyledLine::new();
+ long.push_raw("hello world this is a long message");
+ assert!(long.truncate_to_width(10).width() <= 10);
}
+ /// StyledString render with style includes ANSI escape codes.
#[test]
- fn test_styled_line_default() {
- let line = StyledLine::default();
- assert!(line.segments.is_empty());
- assert_eq!(line.width(), 0);
+ fn test_styled_string_render_styled() {
+ let style = Style::new().bold();
+ let s = StyledString::styled("test", style);
+ assert_snapshot!(s.render(), @"test");
}
}
diff --git a/src/styling/mod.rs b/src/styling/mod.rs
index 96493a09c..ca1908467 100644
--- a/src/styling/mod.rs
+++ b/src/styling/mod.rs
@@ -177,6 +177,8 @@ pub fn fix_dim_after_color_reset(s: &str) -> String {
#[cfg(test)]
mod tests {
+ use insta::assert_snapshot;
+
use super::*;
use anstyle::Style;
use unicode_width::UnicodeWidthStr;
@@ -194,43 +196,17 @@ project = "github.com/user/repo"
command = "npm install"
"#;
- let output = format_toml(toml_content);
-
- // Check that output contains ANSI escape codes
- assert!(
- output.contains("\x1b["),
- "Output should contain ANSI escape codes"
- );
-
- // Check that strings are highlighted (green = 32)
- assert!(
- output.contains("\x1b[32m"),
- "Should contain green color for strings"
- );
-
- // Check that comments are dimmed (dim = 2)
- assert!(
- output.contains("\x1b[2m"),
- "Should contain dim style for comments"
- );
-
- // Check that table headers are highlighted (cyan = 36, bold = 1)
- assert!(
- output.contains("\x1b[36m") || output.contains("\x1b[1m"),
- "Should contain cyan or bold for tables"
- );
-
- // Check that gutter is present (BrightWhite background = 107)
- assert!(
- output.contains("\x1b[107m"),
- "Should contain gutter (BrightWhite background)"
- );
-
- // Check that lines have content (not just gutter)
- assert!(
- output.lines().any(|line| line.len() > 20),
- "Should have lines with actual content beyond gutter and indent"
- );
+ assert_snapshot!(format_toml(toml_content), @r#"
+   worktree-path = "../{{ repo }}.{{ branch }}"
+  
+   [llm]
+   args = []
+  
+   # This is a comment
+   [[approved-commands]]
+   project = "github.com/user/repo"
+   command = "npm install"
+ "#);
}
// StyledString tests
@@ -372,16 +348,11 @@ command = "npm install"
#[test]
fn test_format_with_gutter_preserves_newlines() {
- let multi_line = "Line 1\nLine 2\nLine 3";
- let result = format_with_gutter(multi_line, None);
-
- // Should have at least 3 lines (one for each input line)
- assert!(result.lines().count() >= 3);
-
- // Each original line should be present
- assert!(result.contains("Line 1"));
- assert!(result.contains("Line 2"));
- assert!(result.contains("Line 3"));
+ assert_snapshot!(format_with_gutter("Line 1\nLine 2\nLine 3", Some(80)), @"
+   Line 1
+   Line 2
+   Line 3
+ ");
}
#[test]
@@ -392,7 +363,7 @@ command = "npm install"
// Use fixed width for consistent testing (80 columns)
let result = format_with_gutter(commit_msg, Some(80));
- insta::assert_snapshot!(result, @"
+ assert_snapshot!(result, @"
  This commit refactors the authentication system to use a more secure
  token-based approach instead of the previous session-based system which had
  several security vulnerabilities that were identified during the security
@@ -617,7 +588,7 @@ command = "npm install"
let result = format_bash_with_gutter_at_width(command, 80);
// Snapshot the raw output to verify ANSI codes are consistent
- insta::assert_snapshot!(result);
+ assert_snapshot!(result);
}
#[test]
@@ -647,92 +618,18 @@ cp -cR {{ repo_root }}/target/debug/.fingerprint {{ repo_root }}/target/debug/bu
let result = format_bash_with_gutter_at_width(multiline_command, 80);
// Snapshot the output - each line should have consistent dim styling
- insta::assert_snapshot!(result);
+ assert_snapshot!(result);
}
#[test]
fn test_unhighlighted_text_has_consistent_dim_across_lines() {
- // Verify that unhighlighted text (like template variables) has consistent
- // styling whether it appears at the end of one line or start of another.
- //
- // The template text `{{ worktree` and `}}` should have identical ANSI codes.
-
- let multiline = "echo {{ worktree\n}}/path";
- let result = format_bash_with_gutter(multiline);
-
- let lines: Vec<&str> = result.lines().collect();
- assert_eq!(lines.len(), 2);
-
- // Extract the styling for unhighlighted text on each line
- // Line 1 ends with `{{ worktree` - find what style it's under
- // Line 2 starts with `}}` - find what style it's under
-
- let dim_code = "\x1b[2m";
-
- // Both lines should contain dim code for the unhighlighted text
- // Line 1: after "echo" (highlighted), the `{{ worktree` should be dimmed
- // Line 2: the `}}` at the start should be dimmed
-
- // Check that line 2 starts with dim after the gutter
- // Gutter pattern: [107m [0m (then content)
- // The search string "\x1b[0m " is 6 characters, so content starts at index + 6
- let line2 = lines[1];
- let content_start = line2.find("\x1b[0m ").map(|i| i + 6);
- if let Some(start) = content_start {
- let content = &line2[start..];
- assert!(
- content.starts_with(dim_code),
- "Line 2 content should start with dim for `}}`, got: {:?}",
- &content[..content.len().min(20)]
- );
- }
-
- // Snapshot for visual verification
- insta::assert_snapshot!(result);
+ assert_snapshot!(format_bash_with_gutter("echo {{ worktree\n}}/path"));
}
#[test]
fn test_syntax_highlighting_produces_multiple_colors() {
- // Verify that bash syntax highlighting produces different colors for different
- // token types, not just a single dim color for everything.
- //
- // This catches regressions where all text becomes the same color.
-
let command = "echo 'hello' | grep hello > output.txt && cat output.txt";
- let result = format_bash_with_gutter(command);
-
- // Check for presence of different ANSI color codes:
- // - Blue (34m) for commands like echo, grep, cat
- // - Green (32m) for strings like 'hello'
- // - Cyan (36m) for operators like |, >
- let has_blue = result.contains("\x1b[34m");
- let has_green = result.contains("\x1b[32m");
- let has_cyan = result.contains("\x1b[36m");
-
- assert!(
- has_blue,
- "Output should contain blue (34m) for commands, got: {:?}",
- result
- );
- assert!(
- has_green,
- "Output should contain green (32m) for strings, got: {:?}",
- result
- );
- assert!(
- has_cyan,
- "Output should contain cyan (36m) for operators, got: {:?}",
- result
- );
-
- // Also verify dim is present (base styling)
- assert!(
- result.contains("\x1b[2m"),
- "Output should contain dim (2m) for base styling"
- );
-
- // Snapshot for visual verification
- insta::assert_snapshot!(result);
+ assert_snapshot!(format_bash_with_gutter(command));
}
#[test]
diff --git a/src/summary.rs b/src/summary.rs
index 361ff55ac..c59db9282 100644
--- a/src/summary.rs
+++ b/src/summary.rs
@@ -258,8 +258,23 @@ mod tests {
#[test]
fn test_render_prompt_includes_diff_and_stat() {
let result = render_prompt("diff content here", "stat content here").unwrap();
- assert!(result.contains("diff content here"));
- assert!(result.contains("stat content here"));
+ insta::assert_snapshot!(result, @r#"
+ Write a summary of this branch's changes as a commit message.
+
+ <format>
+ - Subject line under 50 chars, imperative mood ("Add feature" not "Adds feature")
+ - Blank line, then a body paragraph or bullet list explaining the key changes
+ - Output only the message β€” no quotes, code blocks, or labels
+ </format>
+
+ <diffstat>
+ stat content here
+ </diffstat>
+
+ <diff>
+ diff content here
+ </diff>
+ "#);
}
#[test]
diff --git a/tests/CLAUDE.md b/tests/CLAUDE.md
index fc59eba3d..361caf8ad 100644
--- a/tests/CLAUDE.md
+++ b/tests/CLAUDE.md
@@ -285,6 +285,74 @@ fn test_config_loading() {
For environment-dependent tests, use `Command::new()` with `.env()` to set variables in a subprocess, or use the test isolation helpers (`repo.wt_command()`, `wt_command()`).
+## Test Style
+
+### Inline snapshots over multi-assert
+
+When a test checks formatted output, use `insta::assert_snapshot!` with an
+inline snapshot instead of multiple `assert!(x.contains(...))` calls. Snapshots
+capture the complete output, so a single snapshot replaces many contains checks
+and catches regressions that spot-checks miss.
+
+```rust
+use insta::assert_snapshot;
+
+// βœ… GOOD: One snapshot captures all formatting
+assert_snapshot!(format_message("hello"), @" β”‚ hello");
+
+// ❌ BAD: Spot-checks that miss structural regressions
+assert!(result.contains("β”‚"));
+assert!(result.contains("hello"));
+assert!(!result.contains("error"));
+```
+
+Import `assert_snapshot` directly (`use insta::assert_snapshot;`) rather than
+using the qualified `insta::assert_snapshot!` form.
+
+For first-time snapshot creation, leave the inline value empty (`@""`), then
+run `cargo insta test --accept` to fill it.
+
+### One test per belief
+
+Group related inputs into a single test when they verify the same belief about
+the code. A test named `test_wrap_text_at_width` that exercises short text, long
+text, single words, and edge cases is better than five separate test functions
+testing each input individually.
+
+```rust
+// βœ… GOOD: One test for the belief "wrapping respects word boundaries"
+#[test]
+fn test_wrap_text_at_width() {
+ assert_eq!(wrap_text_at_width("short text", 20), vec!["short text"]);
+ assert_eq!(wrap_text_at_width("hello world foo bar", 10), vec!["hello", "world foo", "bar"]);
+ assert_eq!(wrap_text_at_width("superlongword", 5), vec!["superlongword"]);
+ assert_eq!(wrap_text_at_width("", 20), vec![""]);
+}
+```
+
+Table-driven tests work well for functions that map inputs to expected outputs:
+
+```rust
+#[test]
+fn test_bash_token_styles() {
+ let cases = [
+ ("function", AnsiColor::Blue),
+ ("keyword", AnsiColor::Magenta),
+ ("string", AnsiColor::Green),
+ ];
+ for (name, expected) in cases {
+ let style = bash_token_style(name).expect(name);
+ assert_eq!(style.get_fg_color(), Some(Color::Ansi(expected)), "{name}");
+ }
+}
+```
+
+### Don't test constructors or dependencies
+
+Tests that verify `Style::new().bold()` produces a bold style, or that
+`StyledString::raw("x")` stores `"x"`, are testing the dependency β€” not our
+code. Delete these. Test the behavior that uses these types instead.
+
## Deterministic Time in Tests
Tests use `TEST_EPOCH` (2025-01-01) for reproducible timestamps. The constant is defined in `tests/common/mod.rs` and automatically set as `WORKTRUNK_TEST_EPOCH` in the test environment.