60255
Zn
Zoea-Nova / files
Zoea-Nova / documentation / guides / TUI_TESTING.md
26.5 KB
1# TUI Testing Guide 2 3## Overview 4 5Zoea Nova's TUI test suite uses three complementary testing approaches: 61. **Unit tests** - Model state and business logic 72. **Golden file tests** - Visual regression testing 83. **Integration tests** - End-to-end user flows with teatest 9 10This document describes testing practices, patterns, and lessons learned. 11 12## Test Categories 13 14### 1. Unit Tests (`tui_test.go`, `focus_test.go`, etc.) 15 16Test model state transitions and business logic without rendering concerns. 17 18**What to test:** 19- Model initialization and state 20- Navigation logic (up/down, view switching) 21- Input mode transitions 22- Help toggle, history navigation 23- Error handling 24- Business logic (truncation, formatting) 25 26**Pattern:** 27```go 28func TestModelNavigation(t *testing.T) { 29 m, cleanup := setupTestModel(t) 30 defer cleanup() 31 32 m, _ = m.Update(tea.KeyMsg{Type: tea.KeyDown}) 33 if m.selectedIdx != 1 { 34 t.Errorf("expected selectedIdx=1, got %d", m.selectedIdx) 35 } 36} 37``` 38 39**DO NOT test:** 40- Width arithmetic (use golden files instead) 41- ANSI codes directly (use golden files instead) 42- Implementation details (padding, spacing calculations) 43 44### 2. Golden File Tests (`golden_test.go`) 45 46Visual regression tests using snapshot comparison. Each test has ANSI and Stripped variants. 47 48**What to test:** 49- Dashboard rendering 50- Focus view layouts 51- Log entry formatting 52- JSON tree rendering 53- Scrollbar positioning 54- Any visual output 55 56**Pattern:** 57```go 58func TestDashboard(t *testing.T) { 59 defer setupGoldenTest(t)() // Force TrueColor output 60 61 output := renderDashboard(...) 62 63 t.Run("ANSI", func(t *testing.T) { 64 golden.RequireEqual(t, []byte(output)) 65 }) 66 67 t.Run("Stripped", func(t *testing.T) { 68 stripped := stripANSIForGolden(output) 69 golden.RequireEqual(t, []byte(stripped)) 70 }) 71} 72``` 73 74**Update golden files:** 75```bash 76go test ./internal/tui -update 77``` 78 79**Golden files location:** `internal/tui/testdata/` 80 81**Golden file naming convention:** 82- Directory: `testdata/Test<FunctionName>/<test_case_name>/` 83- Files: `ANSI.golden` (with ANSI codes) and `Stripped.golden` (content only) 84- Example: `testdata/TestDashboard/empty_swarm/ANSI.golden` 85 86**Why two variants:** 87- **ANSI** - Catches color and style regressions (RGB codes, bold, etc.) 88- **Stripped** - Catches content and layout regressions (easier to read diffs) 89 90### 3. Integration Tests (`integration_test.go`) 91 92End-to-end tests using teatest to simulate full user interactions. 93 94**What to test:** 95- Complete user flows (create mysis, send broadcast, etc.) 96- Async event handling 97- Window resize behavior 98- Viewport scrolling 99- Multi-step interactions 100 101**Pattern:** 102```go 103func TestIntegration_Example(t *testing.T) { 104 m, cleanup := setupTestModel(t) 105 defer cleanup() 106 107 tm := teatest.NewTestModel(t, m, 108 teatest.WithInitialTermSize(120, 40)) 109 defer tm.Quit() 110 111 // Wait for initial render 112 teatest.WaitFor(t, tm.Output(), func(bts []byte) bool { 113 return bytes.Contains(bts, []byte("expected")) 114 }, teatest.WithDuration(2*time.Second)) 115 116 // Send input 117 tm.Send(tea.KeyMsg{Type: tea.KeyDown}) 118 119 // Wait briefly 120 time.Sleep(100 * time.Millisecond) 121 122 // Send quit to allow FinalModel to complete 123 tm.Send(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("q")}) 124 125 // Verify final state 126 fm := tm.FinalModel(t, teatest.WithFinalTimeout(time.Second)) 127 finalModel := fm.(Model) 128 // ... assertions 129} 130``` 131 132**Known Issue:** Integration tests must send quit command before calling `FinalModel()` to avoid timeouts. 133 134## Testing Guidelines 135 136### DO 137- Test model state and logic with unit tests 138- Test visual output with golden files 139- Test user flows with integration tests 140- Use `lipgloss.Width()` for display width calculations 141- Use `setupGoldenTest(t)` for consistent ANSI output 142- Update golden files when intentionally changing UI 143 144### DO NOT 145- Test width arithmetic (false positives, environment-dependent) 146- Test ANSI codes directly (use golden files) 147- Use `len()` on styled strings (use `lipgloss.Width()`) 148- Test implementation details (padding calculations, internal spacing) 149- Skip golden file updates after UI changes 150 151## Lipgloss Testing Notes 152 153### Width Calculations 154Multi-byte Unicode characters cause width bugs: 155 156- **`len()` returns BYTES, not display width**: Characters like `◈`, `◆`, `╭`, `─` are 3 bytes each but display as 1 column 157- **ALWAYS use `lipgloss.Width()`**: Correctly calculates display width for Unicode and ANSI-styled strings 158- **Test with Unicode-heavy content**: Section titles and borders use Unicode box-drawing characters 159 160### Style Padding and Alignment 161- `lipgloss.Style.Padding(0, 1)` adds 1 space on each side 162- If one element has padding and another doesn't, decorations won't align 163- `lipgloss.Width()` sets CONTENT width - borders and padding are added on top 164- Example: `style.Width(98)` with border produces total width 100 165 166### Background Color Rendering 167**Critical lesson from Unicode character overlap fix:** 168 169When rendering elements with selection backgrounds, content inside the styled area gets the background applied. To prevent background from extending to decorative elements: 170 171**WRONG:** 172```go 173// Indicator is part of styled content - gets background 174line := fmt.Sprintf("%s %s", indicator, content) 175return mysisItemSelectedStyle.Render(line) 176``` 177 178**RIGHT:** 179```go 180// Indicator is outside styled content - no background 181line := content 182return " " + indicator + " " + mysisItemSelectedStyle.Render(line) 183``` 184 185**Pattern:** Render decorative elements (icons, indicators, spacing) OUTSIDE the styled area to prevent background color from applying to them. 186 187## Unicode Character Safety 188 189### East Asian Ambiguous Width 190Characters like `●`, `○`, `◆`, `◈`, `◇` are "East Asian Ambiguous Width": 191- Render as 1 cell in Western locales 192- Render as 2 cells in East Asian locales (Chinese, Japanese, Korean) 193 194This causes visual overlap when width calculations assume 1 cell but terminals render 2 cells. 195 196### Safe Replacements 197| Ambiguous | Safe | Unicode | Name | 198|-----------|------|---------|------| 199| `●` | `∙` | U+2219 | Bullet Operator | 200| `○` | `◦` | U+25E6 | White Bullet | 201| `◆` | `⬥` | U+2B25 | Black Medium Diamond | 202| `◈` | `⬧` | U+2B27 | Black Medium Lozenge | 203| `◇` | `⬦` | U+2B26 | White Medium Diamond | 204 205### Testing for Ambiguous Width 206Use `TestUnicodeAmbiguousWidthSafety` to verify all Unicode characters are non-ambiguous: 207 208```go 209func TestUnicodeAmbiguousWidthSafety(t *testing.T) { 210 chars := map[string]string{ 211 "filled_circle": "∙", 212 "empty_circle": "◦", 213 // ... 214 } 215 216 for name, char := range chars { 217 t.Run(name, func(t *testing.T) { 218 r := []rune(char)[0] 219 220 runewidth.DefaultCondition.EastAsianWidth = false 221 narrowWidth := runewidth.RuneWidth(r) 222 223 runewidth.DefaultCondition.EastAsianWidth = true 224 wideWidth := runewidth.RuneWidth(r) 225 226 if narrowWidth != wideWidth { 227 t.Errorf("Character %q is ambiguous width", char) 228 } 229 }) 230 } 231} 232``` 233 234## Edge Case Testing 235 236### Dashboard Edge Cases (`golden_edge_cases_test.go`) 237 238The `TestDashboardEdgeCases` test covers: 239- **Empty states** - No myses, no messages 240- **Full states** - 16 myses (max swarm), 10 broadcasts (max display) 241- **Error states** - All myses errored, stopped, idle 242- **Mixed states** - Combination of running, idle, stopped, errored 243- **Long content** - Very long broadcast messages (truncation) 244- **Unicode content** - Emoji, CJK characters, box-drawing 245- **Extreme dimensions** - 60 cols (narrow), 240 cols (wide), 100 lines (tall) 246- **Loading states** - All myses loading simultaneously 247- **Selection positions** - Top, middle, bottom of list 248 249### Focus View Edge Cases 250 251The `TestFocusViewEdgeCases` test covers: 252- **Empty states** - No logs, fresh mysis 253- **Long content** - Very long log entries, reasoning (wrapping) 254- **Unicode content** - Emoji in logs, CJK text 255- **Large JSON** - Huge tool results (truncation) 256- **Many logs** - 100+ log entries (scrolling) 257- **Narrow views** - 60 col focus view (wrapping) 258- **All role types** - System, user (direct), user (broadcast), assistant, tool 259 260### Net Indicator Edge Cases 261 262The `TestNetIndicatorEdgeCases` test covers: 263- **Activity states** - Idle, LLM, MCP 264- **Animation positions** - Start, middle, end of bar 265- **View modes** - Full bar, compact 266- **All combinations** - 8 test cases covering state × position × mode 267 268### Edge Case Coverage Summary 269 270| Component | Test Cases | Edge Cases Covered | 271|-----------|------------|-------------------| 272| Dashboard | 15 | Empty, full, errors, Unicode, dimensions, selection | 273| Focus View | 9 | Empty, long content, Unicode, JSON, many logs, narrow | 274| Net Indicator | 8 | Idle, LLM, MCP, positions, compact | 275| **Total** | **32** | **All major edge cases** | 276 277## Unicode Character Testing 278 279### Character Inventory Test 280 281The `TestUnicodeCharacterInventory` test documents all Unicode characters used in the TUI with their codepoints, names, and usage locations. This test serves as a comprehensive reference and ensures all characters are properly documented. 282 283**Verified characters:** 284- **⬥** (U+2B25 BLACK MEDIUM DIAMOND) - Header corners, status bar, message prompt, spinner 285- **⬧** (U+2B27 BLACK MEDIUM LOZENGE) - Section borders, broadcast prompt 286- **⬡** (U+2B21 WHITE HEXAGON) - Title decoration, new mysis prompt, spinner frame 0/2 287- **⬢** (U+2B22 BLACK HEXAGON) - Spinner frame 1/3 288- **⬦** (U+2B26 WHITE MEDIUM DIAMOND) - Spinner frame 4/6, idle indicator 289- **◦** (U+25E6 WHITE BULLET) - Idle state indicator 290- **◌** (U+25CC DOTTED CIRCLE) - Stopped state indicator 291- **✖** (U+2716 HEAVY MULTIPLICATION X) - Errored state indicator 292- **⚙** (U+2699 GEAR) - Config provider prompt 293 294### Spinner Animation Tests 295 296The `TestSpinnerFrameRendering` test verifies all 8 spinner frames: 297 2981. Frame 0: ⬡ (U+2B21) 2992. Frame 1: ⬢ (U+2B22) 3003. Frame 2: ⬡ (U+2B21) 3014. Frame 3: ⬢ (U+2B22) 3025. Frame 4: ⬦ (U+2B26) 3036. Frame 5: ⬥ (U+2B25) 3047. Frame 6: ⬦ (U+2B26) 3058. Frame 7: ⬥ (U+2B25) 306 307**Animation speed:** 125ms per frame (8 FPS) 308**Pattern:** Hexagonal theme alternating between filled/hollow shapes 309 310### Width Consistency Tests 311 312The `TestUnicodeWidthConsistency` test verifies that all characters: 313- Have width of 1 via `lipgloss.Width()` 314- Have width of 1 via `runewidth.RuneWidth()` 315- Are NOT ambiguous width (render consistently in East Asian locales) 316 317This prevents the Unicode overlap bug previously fixed in commit fb1d0b6. 318 319### Terminal Compatibility Testing 320 321**Manual testing checklist:** 322 3231. **Test in primary terminal** (Alacritty, Kitty, WezTerm recommended): 324 ```bash 325 ./bin/zoea --offline 326 ``` 327 3282. **Verify spinner animation:** 329 - Create a mysis (press `n`) 330 - Observe running state indicator animates smoothly 331 - All 8 frames should be visible and distinct 332 - No frame causes layout shift 333 3343. **Verify state indicators:** 335 - Idle: ◦ (white bullet) 336 - Stopped: ◌ (dotted circle) 337 - Errored: ✖ (heavy X) 338 - All indicators should align vertically 339 3404. **Verify section decorations:** 341 - Header corners: ⬥ 342 - Section borders: ⬧ 343 - Title decorations: ⬡ 344 - All decorations should render clearly 345 3465. **Verify input prompts:** 347 - Press `b` for broadcast: ⬧ 348 - Press `m` for message: ⬥ 349 - Press `n` for new mysis: ⬡ 350 - Press `c` for config: ⚙ 351 352**Terminal compatibility notes:** 353 354| Terminal | Status | Notes | 355|----------|--------|-------| 356| Alacritty | ✅ Excellent | Best rendering, all characters clear | 357| Kitty | ✅ Excellent | Full Unicode support | 358| WezTerm | ✅ Excellent | Native font fallback | 359| iTerm2 | ✅ Good | May vary with font | 360| Terminal.app | ⚠️ Fair | Font-dependent | 361| Windows Terminal | ✅ Good | Requires Nerd Font or Unicode font | 362| gnome-terminal | ✅ Good | Most fonts work well | 363| xterm | ⚠️ Limited | May not render all characters | 364 365**Font recommendations:** 366- **Nerd Fonts:** FiraCode Nerd Font, JetBrains Mono Nerd Font 367- **Unicode fonts:** Cascadia Code, Ubuntu Mono, Inconsolata 368- **Fallback:** DejaVu Sans Mono (decent Unicode coverage) 369 370### Character Replacement Strategy 371 372If a character renders poorly in a specific terminal: 373 3741. **Check font first:** Install a Nerd Font or Unicode-compatible font 3752. **Test with `go test`:** Run `TestCharacterRenderingMatrix` to see all characters 3763. **Report compatibility:** Document in KNOWN_ISSUES.md with terminal/font details 3774. **Consider fallback:** Add configuration option for ASCII-only mode (future enhancement) 378 379### Adding New Unicode Characters 380 381When adding new Unicode characters to the TUI: 382 3831. **Choose non-ambiguous width characters:** Use `runewidth` to verify 3842. **Update `TestUnicodeCharacterInventory`:** Add to inventory map with usage 3853. **Verify width:** Run `TestUnicodeWidthConsistency` with new character 3864. **Update golden files:** Run `go test ./internal/tui -update` 3875. **Test manually:** Verify in multiple terminals (see checklist above) 388 389## Spinner Testing Guidelines 390 391### Animation Testing 392 393The spinner animation is tested via `TestSpinnerFrameRendering` which verifies: 394- All 8 frames render correctly 395- Each frame uses the correct Unicode character 396- Frame sequence follows expected pattern (hexagonal theme) 397- Animation speed matches specification (8 FPS, 125ms per frame) 398 399**Test Pattern:** 400```go 401func TestSpinnerFrameRendering(t *testing.T) { 402 frames := []string{"⬡", "⬢", "⬡", "⬢", "⬦", "⬥", "⬦", "⬥"} 403 404 for i, expectedChar := range frames { 405 t.Run(fmt.Sprintf("frame_%d", i), func(t *testing.T) { 406 actual := getSpinnerFrame(i) 407 if actual != expectedChar { 408 t.Errorf("frame %d: expected %q, got %q", i, expectedChar, actual) 409 } 410 }) 411 } 412} 413``` 414 415**Manual Verification:** 4161. Run `./bin/zoea --offline` 4172. Create a mysis (press `n`) 4183. Observe running state indicator animates smoothly 4194. All frames should be visible and distinct 4205. No frame should cause layout shift 421 422**Spinner Specifications:** 423- Frames: 8 total 424- Pattern: Hexagonal theme alternating between filled/hollow shapes 425- Speed: 8 FPS (125ms per frame) 426- Unicode characters: All verified non-ambiguous width 427 428## Golden File Update Process 429 430### When to Update 431 432Update golden files when: 4331. **Intentionally changing UI** - Color changes, layout changes, new elements 4342. **After Phase 1 border color fix** - Border RGB codes changed 4353. **After Unicode character replacements** - Character codepoints changed 4364. **After adding new golden tests** - Initial generation 437 438### How to Update 439 440```bash 441# Update all golden files 442go test ./internal/tui -update 443 444# Update specific test golden files 445go test ./internal/tui -run TestDashboard -update 446go test ./internal/tui -run TestFocusView -update 447``` 448 449### Verification After Update 450 451```bash 452# 1. Verify all tests pass 453go test ./internal/tui 454 455# 2. Review changes to golden files 456git diff internal/tui/testdata/ 457 458# 3. Check for expected changes 459# - Phase 1: RGB color codes changed from 42,42,85 to 107,0,179 460# - Phase 3: Unicode codepoints changed for replaced characters 461# - Phase 4: Spinner frames use new characters 462 463# 4. Commit golden file updates with descriptive message 464git add internal/tui/testdata/ 465git commit -m "test: update golden files after [phase description]" 466``` 467 468### Golden File Structure 469 470Each test has two variants: 471- **ANSI.golden** - Full output with ANSI escape codes (RGB colors, styles) 472- **Stripped.golden** - Content only, ANSI codes removed 473 474**Example:** 475``` 476internal/tui/testdata/ 477├── TestDashboard/ 478│ ├── empty_swarm/ 479│ │ ├── ANSI.golden # Full ANSI with RGB codes 480│ │ └── Stripped.golden # Content only 481│ └── with_swarm_messages/ 482│ ├── ANSI.golden 483│ └── Stripped.golden 484``` 485 486**Why Two Variants:** 487- **ANSI** - Catches color and style regressions 488- **Stripped** - Catches content and layout regressions (easier to read diffs) 489 490## Layout Testing Guidelines 491 492### Dashboard Layout 493 494The dashboard layout calculation is tested via `TestDashboardLayoutCalculations` and `TestDashboardHeightCalculation`: 495 496**What to test:** 497- Terminal sizes from 80x20 to 200x100 498- Various mysis counts (0, 1, 5, 10, 20) 499- Various swarm message counts (0, 5, 10, 20) 500- No panics during rendering 501- Minimum height guards enforced 502 503**Test Pattern:** 504```go 505func TestDashboardLayoutCalculations(t *testing.T) { 506 testCases := []struct { 507 width, height int 508 mysisCount int 509 messageCount int 510 }{ 511 {80, 20, 0, 0}, 512 {120, 40, 5, 5}, 513 {200, 100, 20, 10}, 514 } 515 516 for _, tc := range testCases { 517 t.Run(fmt.Sprintf("%dx%d_m%d_msg%d", tc.width, tc.height, tc.mysisCount, tc.messageCount), func(t *testing.T) { 518 // Render and verify no panics 519 output := RenderDashboard(...) 520 if output == "" { 521 t.Error("empty output") 522 } 523 }) 524 } 525} 526``` 527 528### Focus View Layout 529 530The focus view layout calculation is tested via `TestFocusViewLayoutCalculations` and `TestViewportHeightCalculation`: 531 532**What to test:** 533- Terminal sizes from 80x10 to 200x100 534- Various log entry counts (0, 5, 20, 50, 100, 500, 1000) 535- Viewport height minimum enforcement (5 lines) 536- No negative heights 537- No panics during rendering 538 539**Test Pattern:** 540```go 541func TestFocusViewLayoutCalculations(t *testing.T) { 542 testCases := []struct { 543 width, height int 544 logCount int 545 }{ 546 {80, 10, 0}, 547 {120, 40, 50}, 548 {200, 100, 1000}, 549 } 550 551 for _, tc := range testCases { 552 t.Run(fmt.Sprintf("%dx%d_logs%d", tc.width, tc.height, tc.logCount), func(t *testing.T) { 553 // Render and verify no panics 554 output := RenderFocusViewWithViewport(...) 555 if output == "" { 556 t.Error("empty output") 557 } 558 }) 559 } 560} 561``` 562 563### Minimum Dimension Guards 564 565**Critical safety checks:** 566- Dashboard mysis list height: `if mysisListHeight < 3 { mysisListHeight = 3 }` 567- Focus view viewport height: `if vpHeight < 5 { vpHeight = 5 }` 568- Content width: `if contentWidth < 20 { contentWidth = 20 }` 569 570**Test Coverage:** 571- `TestLayoutNoNegativeHeights` verifies no negative heights at extreme small sizes 572- All guards tested with terminal heights from 5 to 100 lines 573- All guards tested with terminal widths from 10 to 200 columns 574 575## Width Calculation Testing Guidelines 576 577### Lipgloss Width vs len() 578 579**Critical Rule:** NEVER use `len()` for width calculations with Unicode or styled strings. 580 581**Test Pattern:** 582```go 583func TestWidthCalculations(t *testing.T) { 584 // Unicode character that is 3 bytes but displays as 1 column 585 unicodeStr := "⬥" 586 587 // WRONG: len() returns 3 (bytes) 588 bytesWidth := len(unicodeStr) 589 590 // RIGHT: lipgloss.Width() returns 1 (display width) 591 displayWidth := lipgloss.Width(unicodeStr) 592 593 if bytesWidth == displayWidth { 594 t.Error("len() should NOT equal lipgloss.Width() for Unicode") 595 } 596 597 if displayWidth != 1 { 598 t.Errorf("expected display width 1, got %d", displayWidth) 599 } 600} 601``` 602 603### Content Width with Borders 604 605When calculating content width with borders, account for border characters: 606 607**Pattern:** 608```go 609// Double-line border adds 4 chars total (2 on each side) 610contentWidth := terminalWidth - 4 611 612// Minimum guard 613if contentWidth < 20 { 614 contentWidth = 20 615} 616``` 617 618**Test:** 619```go 620func TestContentWidthCalculation(t *testing.T) { 621 widths := []int{10, 20, 40, 80, 120, 160, 200} 622 623 for _, w := range widths { 624 t.Run(fmt.Sprintf("width_%d", w), func(t *testing.T) { 625 contentWidth := w - 4 626 if contentWidth < 20 { 627 contentWidth = 20 628 } 629 630 if contentWidth < 0 { 631 t.Error("content width must never be negative") 632 } 633 }) 634 } 635} 636``` 637 638## Golden File Update Process 639 640### When to Update 641 642Update golden files when: 6431. **Intentionally changing UI** - Color changes, layout changes, new elements 6442. **After Phase 1 border color fix** - Border RGB codes changed 6453. **After Unicode character replacements** - Character codepoints changed 6464. **After adding new golden tests** - Initial generation 647 648### How to Update 649 650```bash 651# Update all golden files 652go test ./internal/tui -update 653 654# Update specific test golden files 655go test ./internal/tui -run TestDashboard -update 656go test ./internal/tui -run TestFocusView -update 657``` 658 659### Verification After Update 660 661```bash 662# 1. Verify all tests pass 663go test ./internal/tui 664 665# 2. Review changes to golden files 666git diff internal/tui/testdata/ 667 668# 3. Check for expected changes 669# - Phase 1: RGB color codes changed from 42,42,85 to 107,0,179 670# - Phase 3: Unicode codepoints changed for replaced characters 671# - Phase 4: Spinner frames use new characters 672 673# 4. Commit golden file updates with descriptive message 674git add internal/tui/testdata/ 675git commit -m "test: update golden files after [phase description]" 676``` 677 678### Golden File Structure 679 680Each test has two variants: 681- **ANSI.golden** - Full output with ANSI escape codes (RGB colors, styles) 682- **Stripped.golden** - Content only, ANSI codes removed 683 684**Example:** 685``` 686internal/tui/testdata/ 687├── TestDashboard/ 688│ ├── empty_swarm/ 689│ │ ├── ANSI.golden # Full ANSI with RGB codes 690│ │ └── Stripped.golden # Content only 691│ └── with_swarm_messages/ 692│ ├── ANSI.golden 693│ └── Stripped.golden 694``` 695 696**Why Two Variants:** 697- **ANSI** - Catches color and style regressions 698- **Stripped** - Catches content and layout regressions (easier to read diffs) 699 700## Test Execution 701 702### Run All Tests 703```bash 704go test ./internal/tui 705``` 706 707### Run Specific Test Types 708```bash 709# Unit tests only 710go test ./internal/tui -run TestModel 711 712# Golden file tests only 713go test ./internal/tui -run TestDashboard 714 715# Integration tests only 716go test ./internal/tui -run TestIntegration 717 718# Unicode safety tests 719go test ./internal/tui -run TestUnicodeAmbiguousWidthSafety 720``` 721 722### Update Golden Files 723```bash 724# Update all golden files 725go test ./internal/tui -update 726 727# Update specific test golden files 728go test ./internal/tui -run TestDashboard -update 729go test ./internal/tui -run TestFocusView -update 730 731# Verify changes after update 732git diff internal/tui/testdata/ 733``` 734 735### Verify Build 736```bash 737make build 738make test 739``` 740 741## Test Infrastructure 742 743### Files 744- `testhelpers_test.go` - Test utilities and constants 745- `golden_test.go` - Golden file tests (basic rendering) 746- `golden_edge_cases_test.go` - Edge case golden tests (empty states, full states, Unicode, etc.) 747- `integration_test.go` - Integration tests (18 tests) 748- `tui_test.go` - Unit tests (22 tests) 749- `focus_test.go` - Focus view tests (7 tests) 750- `json_tree_test.go` - JSON rendering tests (4 tests) 751- `scrollbar_test.go` - Scrollbar tests (4 tests) 752- `spinner_test.go` - Spinner animation tests 753- `statusbar_test.go` - Status bar tests 754- `input_test.go` - Input prompt tests 755- `unicode_test.go` - Unicode safety tests 756- `width_test.go` - Width calculation tests 757- `layout_test.go` - Layout calculation tests 758 759### Dependencies 760- `github.com/charmbracelet/x/exp/teatest` - Integration testing 761- `github.com/charmbracelet/x/exp/golden` - Golden file comparison 762- `github.com/mattn/go-runewidth` - Unicode width testing 763 764### Directory Structure 765``` 766internal/tui/ 767├── testdata/ # Golden files 768│ ├── TestDashboard/ 769│ │ ├── empty_swarm/ 770│ │ │ ├── ANSI.golden 771│ │ │ └── Stripped.golden 772│ │ └── with_swarm_messages/ 773│ │ ├── ANSI.golden 774│ │ └── Stripped.golden 775│ ├── TestDashboardEdgeCases/ # Edge case tests 776│ │ ├── full_swarm_16_myses/ 777│ │ ├── all_myses_errored/ 778│ │ ├── unicode_emoji_in_messages/ 779│ │ └── ... 780│ ├── TestFocusView/ 781│ ├── TestFocusViewEdgeCases/ # Edge case tests 782│ │ ├── no_logs_empty_state/ 783│ │ ├── very_long_log_entry/ 784│ │ ├── unicode_emoji_logs/ 785│ │ └── ... 786│ ├── TestNetIndicatorEdgeCases/ 787│ ├── TestHelp/ 788│ ├── TestLogEntry/ 789│ ├── TestJSONTree/ 790│ ├── TestScrollbar/ 791│ ├── TestMysisLine/ 792│ └── TestBroadcastLabels/ 793├── testhelpers_test.go # Test utilities 794├── golden_test.go # Golden file tests 795├── golden_edge_cases_test.go # Edge case golden tests 796├── integration_test.go # Integration tests 797├── tui_test.go # Unit tests 798├── focus_test.go # Focus view tests 799├── json_tree_test.go # JSON rendering tests 800└── scrollbar_test.go # Scrollbar tests 801``` 802 803## Metrics 804 805| Metric | Value | 806|--------|-------| 807| Total tests | 80+ | 808| Test files | 14 | 809| Unit tests | 22 | 810| Golden tests | 54 (basic + edge cases) | 811| Integration tests | 18 (1 passing, 17 need timeout fix) | 812| Golden files | 218 (ANSI + Stripped variants) | 813| Test coverage | 85.7% | 814 815## Key Lessons 816 817### 1. Golden Files Catch Visual Bugs 818Golden files caught the Unicode character overlap issue that unit tests couldn't detect because they don't render backgrounds. 819 820### 2. Background Styling Requires Careful Rendering 821Decorative elements (icons, indicators) must be rendered OUTSIDE styled areas to prevent background color from applying to them. 822 823### 3. Unicode Width Is Complex 824- Never use `len()` for width calculations 825- Always use `lipgloss.Width()` 826- Test for East Asian Ambiguous Width characters 827- Use `TestUnicodeAmbiguousWidthSafety` to prevent regressions 828 829### 4. Tests Don't Replace Manual Verification 830Always run the actual TUI application to verify visual changes. Tests validate logic and catch regressions, but human eyes catch visual issues tests miss. 831 832Use offline mode for safe UI testing without connecting to the live game server: 833```bash 834./bin/zoea -offline 835``` 836 837### 5. Integration Tests Need Quit Pattern 838Integration tests must send quit command before calling `FinalModel()` to avoid timeouts. See `TestIntegration_DashboardNavigation` for the correct pattern. 839 840## Future Improvements 841 8421. Fix remaining 17 integration test timeouts 8432. Add golden file tests for new UI components 8443. Increase test coverage to 90%+ 8454. Add performance benchmarks for rendering 8465. Document visual testing workflow for contributors 847 848## References 849 850- [Bubble Tea Testing Guide](https://github.com/charmbracelet/bubbletea/tree/master/tutorials/testing) 851- [Golden File Testing](https://github.com/charmbracelet/x/tree/main/exp/golden) 852- [Lipgloss Documentation](https://github.com/charmbracelet/lipgloss) 853- [Unicode Width Testing](https://github.com/mattn/go-runewidth)