Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add content expectations to PTY tests for async preview panels
Maximilian Roos620e8c3f9567
diff --git a/CLAUDE.md b/CLAUDE.mdindex 3eb9a5b4c..6ee27a982 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -393,15 +393,11 @@ See `src/commands/list/render.rs` for advanced usage.### Gutter Formatting for Quoted Content-Use `format_with_gutter()` for quoted content. Gutter content displays external output (git errors, command output) in a visually distinct block.+Use `format_with_gutter()` for **external data** — anything read from outside the application: git output, shell commands, commit messages, config values, cached data. Gutter visually quotes this content to distinguish it from application-generated output.-```rust-// Show warning message, then external error in gutter-output::print(warning_message(cformat!("Could not delete branch <bold>{branch_name}</>")))?;-output::gutter(format_with_gutter(&e.to_string(), "", None))?;-```+**Gutter vs Table:** Tabular data structured by the application should use `output::table()` with markdown formatting via `render_markdown_in_help()`. Tables are artifacts; gutter is for quoting external data.-**Linebreaks:** Gutter content requires a single newline before it, never double newlines. The `output::print()` function uses `println!()` internally, adding a trailing newline. Messages passed to it should not include `\n`:+**Linebreaks:** Gutter requires a single newline before it, never double. `output::print()` adds a trailing newline, so messages should not include `\n`:```rust// ✅ GOOD - no trailing \ndiff --git a/src/commands/config.rs b/src/commands/config.rsindex 99fe87602..b1f8d1e3e 100644--- a/src/commands/config.rs+++ b/src/commands/config.rs@@ -656,7 +656,7 @@ pub fn handle_var_clear(key: &str, branch: Option<String>, all: bool) -> anyhow:pub fn handle_cache_show() -> anyhow::Result<()> {let repo = Repository::current();- // Show default branch cache+ // Show default branch cache (value from git config, so use gutter)crate::output::print(info_message("Default branch cache:"))?;match repo.default_branch() {Ok(branch) => crate::output::gutter(format_with_gutter(&branch, "", None))?,@@ -673,12 +673,20 @@ pub fn handle_cache_show() -> anyhow::Result<()> {return Ok(());}- let now_secs = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_secs())- .unwrap_or(0);-- let mut ci_lines = Vec::new();+ // Respect SOURCE_DATE_EPOCH for reproducible test output+ let now_secs = std::env::var("SOURCE_DATE_EPOCH")+ .ok()+ .and_then(|val| val.parse::<u64>().ok())+ .unwrap_or_else(|| {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0)+ });++ // Build markdown table+ let mut table = String::from("| Branch | Status | Age | Head |\n");+ table.push_str("|--------|--------|-----|------|\n");for (branch, cached) in entries {let status = match &cached.status {Some(pr_status) => serde_json::to_string(&pr_status.ci_status)@@ -689,9 +697,11 @@ pub fn handle_cache_show() -> anyhow::Result<()> {let age = now_secs.saturating_sub(cached.checked_at);let head: String = cached.head.chars().take(8).collect();- ci_lines.push(format!("{branch}: {status} (age: {age}s, head: {head})"));+ table.push_str(&format!("| {branch} | {status} | {age}s | {head} |\n"));}- crate::output::gutter(format_with_gutter(&ci_lines.join("\n"), "", None))?;++ let rendered = crate::md_help::render_markdown_table(&table);+ crate::output::table(rendered.trim_end())?;Ok(())}diff --git a/src/md_help.rs b/src/md_help.rsindex e214456ed..1b8960559 100644--- a/src/md_help.rs+++ b/src/md_help.rs@@ -77,8 +77,22 @@ pub fn render_markdown_in_help(help: &str) -> String {colorize_status_symbols(&result)}-/// Render a markdown table with proper column alignment+/// Render a markdown table with proper column alignment (for help text, adds 2-space indent)fn render_table(lines: &[&str]) -> String {+ render_markdown_table_impl(lines, " ")+}++/// Render a markdown table from markdown source string (no indent)+pub fn render_markdown_table(markdown: &str) -> String {+ let lines: Vec<&str> = markdown+ .lines()+ .filter(|l| l.trim().starts_with('|') && l.trim().ends_with('|'))+ .collect();+ render_markdown_table_impl(&lines, "")+}++/// Core table rendering with configurable indent+fn render_markdown_table_impl(lines: &[&str], indent: &str) -> String {// Parse table cellslet mut rows: Vec<Vec<String>> = Vec::new();let mut separator_idx: Option<usize> = None;@@ -132,7 +146,7 @@ fn render_table(lines: &[&str]) -> String {let has_header = separator_idx.is_some();for (row_idx, row) in rows.iter().enumerate() {- result.push_str(" "); // Indent+ result.push_str(indent);for (col_idx, cell) in row.iter().enumerate() {if col_idx > 0 {@@ -155,7 +169,7 @@ fn render_table(lines: &[&str]) -> String {// Add visual separator after header rowif has_header && row_idx == 0 {- result.push_str(" ");+ result.push_str(indent);for (col_idx, width) in col_widths.iter().enumerate() {if col_idx > 0 {result.push_str(" ");diff --git a/tests/CLAUDE.md b/tests/CLAUDE.mdindex 1d68e4099..b3eb0cf39 100644--- a/tests/CLAUDE.md+++ b/tests/CLAUDE.md@@ -107,3 +107,20 @@ When converting a README example test from `insta_cmd` to PTY-based:### Implementation NoteThe PTY approach is specifically for **user-facing output documentation**. It's not a replacement for standard integration tests - both approaches serve different purposes and should coexist in the test suite.++## 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 `SOURCE_DATE_EPOCH` in the test environment.++**For test data with timestamps** (cache entries, etc.), use the constant:++```rust+use crate::common::TEST_EPOCH;++repo.git_command(&[+ "config", "worktrunk.ci.feature",+ &format!(r#"{{"checked_at":{TEST_EPOCH},"head":"abc123"}}"#),+]);+```++**For production code** that calculates age/duration, check `SOURCE_DATE_EPOCH` (see `src/display.rs::get_now()` for pattern). Using `SystemTime::now()` directly causes flaky tests.diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex eb80d3f96..4cc24c02f 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -47,6 +47,10 @@ pub const HOUR: i64 = 60 * MINUTE;pub const DAY: i64 = 24 * HOUR;pub const WEEK: i64 = 7 * DAY;+/// The epoch used for deterministic timestamps in tests (2025-01-01T00:00:00Z).+/// Use this when creating test data with timestamps (cache entries, etc.).+pub const TEST_EPOCH: u64 = 1735776000;+/// Create a `wt` CLI command with standardized test environment settings.////// The command has the following guarantees:@@ -125,9 +129,7 @@ pub fn configure_cli_command(cmd: &mut Command) {// but correctness (isolating from host WORKTRUNK_* vars) trumps snapshot aesthetics.cmd.env("WORKTRUNK_CONFIG_PATH", "/nonexistent/test/config.toml");cmd.env("CLICOLOR_FORCE", "1");- // Jan 2, 2025 - 1 day after default commit date (2025-01-01)- // for deterministic "1d" in Age column- cmd.env("SOURCE_DATE_EPOCH", "1735776000");+ cmd.env("SOURCE_DATE_EPOCH", TEST_EPOCH.to_string());cmd.env("COLUMNS", "150");}@@ -219,8 +221,7 @@ impl TestRepo {cmd.env("GIT_COMMITTER_DATE", "2025-01-01T00:00:00Z");cmd.env("LC_ALL", "C");cmd.env("LANG", "C");- // Jan 2, 2025 - 1 day after commit date for deterministic "1d" in Age column- cmd.env("SOURCE_DATE_EPOCH", "1735776000");+ cmd.env("SOURCE_DATE_EPOCH", TEST_EPOCH.to_string());}/// Get standard test environment variables as a vector@@ -231,7 +232,6 @@ impl TestRepo {vec![("CLICOLOR_FORCE".to_string(), "1".to_string()),("COLUMNS".to_string(), "150".to_string()),- // Use test git config file with advice settings disabled("GIT_CONFIG_GLOBAL".to_string(),self.git_config_path.display().to_string(),@@ -247,7 +247,7 @@ impl TestRepo {),("LC_ALL".to_string(), "C".to_string()),("LANG".to_string(), "C".to_string()),- ("SOURCE_DATE_EPOCH".to_string(), "1735776000".to_string()),+ ("SOURCE_DATE_EPOCH".to_string(), TEST_EPOCH.to_string()),("WORKTRUNK_CONFIG_PATH".to_string(),self.test_config_path().display().to_string(),@@ -391,10 +391,7 @@ impl TestRepo {/// repo.commit_with_age("Add feature", 600); // Shows "10m"/// ```pub fn commit_with_age(&self, message: &str, age_seconds: i64) {- // SOURCE_DATE_EPOCH used in tests - must match configure_git_cmd/test_env_vars- // This is Jan 2, 2025 00:00:00 UTC- const SOURCE_DATE_EPOCH: i64 = 1735776000;- let commit_time = SOURCE_DATE_EPOCH - age_seconds;+ let commit_time = TEST_EPOCH as i64 - age_seconds;// Use ISO 8601 format for consistent behavior across git versionslet timestamp = unix_to_iso8601(commit_time);@@ -431,8 +428,7 @@ impl TestRepo {/// repo.commit_staged_with_age("Add feature", 2 * HOUR, &wt);/// ```pub fn commit_staged_with_age(&self, message: &str, age_seconds: i64, dir: &Path) {- const SOURCE_DATE_EPOCH: i64 = 1735776000;- let commit_time = SOURCE_DATE_EPOCH - age_seconds;+ let commit_time = TEST_EPOCH as i64 - age_seconds;let timestamp = unix_to_iso8601(commit_time);let mut cmd = Command::new("git");diff --git a/tests/integration_tests/config_cache.rs b/tests/integration_tests/config_cache.rsindex 6794a3b69..a76a653df 100644--- a/tests/integration_tests/config_cache.rs+++ b/tests/integration_tests/config_cache.rs@@ -1,4 +1,4 @@-use crate::common::{TestRepo, wt_command};+use crate::common::{TEST_EPOCH, TestRepo, wt_command};use insta::assert_snapshot;use std::process::Command;@@ -52,6 +52,41 @@ fn test_config_cache_show_with_default_branch() {");}+#[test]+fn test_config_cache_show_with_ci_entries() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Add CI cache entries - use TEST_EPOCH for deterministic age=0s in snapshots+ repo.git_command(&[+ "config",+ "worktrunk.ci.feature",+ &format!(r#"{{"status":{{"ci_status":"passed","source":"pullrequest","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890"}}"#),+ ])+ .status()+ .unwrap();++ repo.git_command(&[+ "config",+ "worktrunk.ci.bugfix",+ &format!(r#"{{"status":{{"ci_status":"failed","source":"branch","is_stale":true}},"checked_at":{TEST_EPOCH},"head":"111222333444555"}}"#),+ ])+ .status()+ .unwrap();++ repo.git_command(&[+ "config",+ "worktrunk.ci.main",+ &format!(r#"{{"status":null,"checked_at":{TEST_EPOCH},"head":"deadbeef12345678"}}"#),+ ])+ .status()+ .unwrap();++ let output = wt_config_cache_cmd(&repo, &["show"]).output().unwrap();+ assert!(output.status.success());+ assert_snapshot!(String::from_utf8_lossy(&output.stderr));+}+// ============================================================================// cache clear// ============================================================================diff --git a/tests/integration_tests/snapshots/integration__integration_tests__config_cache__config_cache_show_with_ci_entries.snap b/tests/integration_tests/snapshots/integration__integration_tests__config_cache__config_cache_show_with_ci_entries.snapnew file mode 100644index 000000000..08e440156--- /dev/null+++ b/tests/integration_tests/snapshots/integration__integration_tests__config_cache__config_cache_show_with_ci_entries.snap@@ -0,0 +1,13 @@+---+source: tests/integration_tests/config_cache.rs+expression: "String::from_utf8_lossy(&output.stderr)"+---+⚪ Default branch cache:+[107m [0m main++⚪ CI status cache:+Branch Status Age Head+─────── ────── ─── ────────+feature passed 0s abc12345+bugfix failed 0s 11122233+main none 0s deadbeef