@@ -0,0 +1,346 @@
1+# TUI Testing Guide
2+
3+## Overview
4+
5+Zoea Nova's TUI test suite uses three complementary testing approaches:
6+1. **Unit tests** - Model state and business logic
7+2. **Golden file tests** - Visual regression testing
8+3. **Integration tests** - End-to-end user flows with teatest
9+
10+This 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+
16+Test 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
28+func 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+
46+Visual 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
58+func 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
76+go test ./internal/tui -update
77+```
78+
79+**Golden files location:** `internal/tui/testdata/`
80+
81+### 3. Integration Tests (`integration_test.go`)
82+
83+End-to-end tests using teatest to simulate full user interactions.
84+
85+**What to test:**
86+- Complete user flows (create mysis, send broadcast, etc.)
87+- Async event handling
88+- Window resize behavior
89+- Viewport scrolling
90+- Multi-step interactions
91+
92+**Pattern:**
93+```go
94+func TestIntegration_Example(t *testing.T) {
95+ m, cleanup := setupTestModel(t)
96+ defer cleanup()
97+
98+ tm := teatest.NewTestModel(t, m,
99+ teatest.WithInitialTermSize(120, 40))
100+ defer tm.Quit()
101+
102+ // Wait for initial render
103+ teatest.WaitFor(t, tm.Output(), func(bts []byte) bool {
104+ return bytes.Contains(bts, []byte("expected"))
105+ }, teatest.WithDuration(2*time.Second))
106+
107+ // Send input
108+ tm.Send(tea.KeyMsg{Type: tea.KeyDown})
109+
110+ // Wait briefly
111+ time.Sleep(100 * time.Millisecond)
112+
113+ // Send quit to allow FinalModel to complete
114+ tm.Send(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("q")})
115+
116+ // Verify final state
117+ fm := tm.FinalModel(t, teatest.WithFinalTimeout(time.Second))
118+ finalModel := fm.(Model)
119+ // ... assertions
120+}
121+```
122+
123+**Known Issue:** Integration tests must send quit command before calling `FinalModel()` to avoid timeouts.
124+
125+## Testing Guidelines
126+
127+### DO
128+- Test model state and logic with unit tests
129+- Test visual output with golden files
130+- Test user flows with integration tests
131+- Use `lipgloss.Width()` for display width calculations
132+- Use `setupGoldenTest(t)` for consistent ANSI output
133+- Update golden files when intentionally changing UI
134+
135+### DO NOT
136+- Test width arithmetic (false positives, environment-dependent)
137+- Test ANSI codes directly (use golden files)
138+- Use `len()` on styled strings (use `lipgloss.Width()`)
139+- Test implementation details (padding calculations, internal spacing)
140+- Skip golden file updates after UI changes
141+
142+## Lipgloss Testing Notes
143+
144+### Width Calculations
145+Multi-byte Unicode characters cause width bugs:
146+
147+- **`len()` returns BYTES, not display width**: Characters like `◈`, `◆`, `╭`, `─` are 3 bytes each but display as 1 column
148+- **ALWAYS use `lipgloss.Width()`**: Correctly calculates display width for Unicode and ANSI-styled strings
149+- **Test with Unicode-heavy content**: Section titles and borders use Unicode box-drawing characters
150+
151+### Style Padding and Alignment
152+- `lipgloss.Style.Padding(0, 1)` adds 1 space on each side
153+- If one element has padding and another doesn't, decorations won't align
154+- `lipgloss.Width()` sets CONTENT width - borders and padding are added on top
155+- Example: `style.Width(98)` with border produces total width 100
156+
157+### Background Color Rendering
158+**Critical lesson from Unicode character overlap fix:**
159+
160+When rendering elements with selection backgrounds, content inside the styled area gets the background applied. To prevent background from extending to decorative elements:
161+
162+**WRONG:**
163+```go
164+// Indicator is part of styled content - gets background
165+line := fmt.Sprintf("%s %s", indicator, content)
166+return mysisItemSelectedStyle.Render(line)
167+```
168+
169+**RIGHT:**
170+```go
171+// Indicator is outside styled content - no background
172+line := content
173+return " " + indicator + " " + mysisItemSelectedStyle.Render(line)
174+```
175+
176+**Pattern:** Render decorative elements (icons, indicators, spacing) OUTSIDE the styled area to prevent background color from applying to them.
177+
178+## Unicode Character Safety
179+
180+### East Asian Ambiguous Width
181+Characters like `●`, `○`, `◆`, `◈`, `◇` are "East Asian Ambiguous Width":
182+- Render as 1 cell in Western locales
183+- Render as 2 cells in East Asian locales (Chinese, Japanese, Korean)
184+
185+This causes visual overlap when width calculations assume 1 cell but terminals render 2 cells.
186+
187+### Safe Replacements
188+| Ambiguous | Safe | Unicode | Name |
189+|-----------|------|---------|------|
190+| `●` | `∙` | U+2219 | Bullet Operator |
191+| `○` | `◦` | U+25E6 | White Bullet |
192+| `◆` | `⬥` | U+2B25 | Black Medium Diamond |
193+| `◈` | `⬧` | U+2B27 | Black Medium Lozenge |
194+| `◇` | `⬦` | U+2B26 | White Medium Diamond |
195+
196+### Testing for Ambiguous Width
197+Use `TestUnicodeAmbiguousWidthSafety` to verify all Unicode characters are non-ambiguous:
198+
199+```go
200+func TestUnicodeAmbiguousWidthSafety(t *testing.T) {
201+ chars := map[string]string{
202+ "filled_circle": "∙",
203+ "empty_circle": "◦",
204+ // ...
205+ }
206+
207+ for name, char := range chars {
208+ t.Run(name, func(t *testing.T) {
209+ r := []rune(char)[0]
210+
211+ runewidth.DefaultCondition.EastAsianWidth = false
212+ narrowWidth := runewidth.RuneWidth(r)
213+
214+ runewidth.DefaultCondition.EastAsianWidth = true
215+ wideWidth := runewidth.RuneWidth(r)
216+
217+ if narrowWidth != wideWidth {
218+ t.Errorf("Character %q is ambiguous width", char)
219+ }
220+ })
221+ }
222+}
223+```
224+
225+## Test Execution
226+
227+### Run All Tests
228+```bash
229+go test ./internal/tui
230+```
231+
232+### Run Specific Test Types
233+```bash
234+# Unit tests only
235+go test ./internal/tui -run TestModel
236+
237+# Golden file tests only
238+go test ./internal/tui -run TestDashboard
239+
240+# Integration tests only
241+go test ./internal/tui -run TestIntegration
242+
243+# Unicode safety tests
244+go test ./internal/tui -run TestUnicodeAmbiguousWidthSafety
245+```
246+
247+### Update Golden Files
248+```bash
249+go test ./internal/tui -update
250+```
251+
252+### Verify Build
253+```bash
254+make build
255+make test
256+```
257+
258+## Test Infrastructure
259+
260+### Files
261+- `testhelpers_test.go` - Test utilities and constants
262+- `golden_test.go` - Golden file tests (22 tests, 44 golden files)
263+- `integration_test.go` - Integration tests (18 tests)
264+- `tui_test.go` - Unit tests (22 tests)
265+- `focus_test.go` - Focus view tests (7 tests)
266+- `json_tree_test.go` - JSON rendering tests (4 tests)
267+- `scrollbar_test.go` - Scrollbar tests (4 tests)
268+
269+### Dependencies
270+- `github.com/charmbracelet/x/exp/teatest` - Integration testing
271+- `github.com/charmbracelet/x/exp/golden` - Golden file comparison
272+- `github.com/mattn/go-runewidth` - Unicode width testing
273+
274+### Directory Structure
275+```
276+internal/tui/
277+├── testdata/ # Golden files
278+│ ├── TestDashboard/
279+│ │ ├── empty_swarm/
280+│ │ │ ├── ANSI.golden
281+│ │ │ └── Stripped.golden
282+│ │ └── with_swarm_messages/
283+│ │ ├── ANSI.golden
284+│ │ └── Stripped.golden
285+│ ├── TestFocusView/
286+│ ├── TestHelp/
287+│ ├── TestLogEntry/
288+│ ├── TestJSONTree/
289+│ ├── TestScrollbar/
290+│ ├── TestMysisLine/
291+│ └── TestBroadcastLabels/
292+├── testhelpers_test.go # Test utilities
293+├── golden_test.go # Golden file tests
294+├── integration_test.go # Integration tests
295+├── tui_test.go # Unit tests
296+├── focus_test.go # Focus view tests
297+├── json_tree_test.go # JSON rendering tests
298+└── scrollbar_test.go # Scrollbar tests
299+```
300+
301+## Metrics
302+
303+| Metric | Value |
304+|--------|-------|
305+| Total tests | 48 |
306+| Test files | 7 |
307+| Unit tests | 22 |
308+| Golden tests | 22 |
309+| Integration tests | 18 (1 passing, 17 need timeout fix) |
310+| Golden files | 44 (ANSI + Stripped variants) |
311+| Test coverage | 83% |
312+
313+## Key Lessons
314+
315+### 1. Golden Files Catch Visual Bugs
316+Golden files caught the Unicode character overlap issue that unit tests couldn't detect because they don't render backgrounds.
317+
318+### 2. Background Styling Requires Careful Rendering
319+Decorative elements (icons, indicators) must be rendered OUTSIDE styled areas to prevent background color from applying to them.
320+
321+### 3. Unicode Width Is Complex
322+- Never use `len()` for width calculations
323+- Always use `lipgloss.Width()`
324+- Test for East Asian Ambiguous Width characters
325+- Use `TestUnicodeAmbiguousWidthSafety` to prevent regressions
326+
327+### 4. Tests Don't Replace Manual Verification
328+Always run the actual TUI application to verify visual changes. Tests validate logic and catch regressions, but human eyes catch visual issues tests miss.
329+
330+### 5. Integration Tests Need Quit Pattern
331+Integration tests must send quit command before calling `FinalModel()` to avoid timeouts. See `TestIntegration_DashboardNavigation` for the correct pattern.
332+
333+## Future Improvements
334+
335+1. Fix remaining 17 integration test timeouts
336+2. Add golden file tests for new UI components
337+3. Increase test coverage to 90%+
338+4. Add performance benchmarks for rendering
339+5. Document visual testing workflow for contributors
340+
341+## References
342+
343+- [Bubble Tea Testing Guide](https://github.com/charmbracelet/bubbletea/tree/master/tutorials/testing)
344+- [Golden File Testing](https://github.com/charmbracelet/x/tree/main/exp/golden)
345+- [Lipgloss Documentation](https://github.com/charmbracelet/lipgloss)
346+- [Unicode Width Testing](https://github.com/mattn/go-runewidth)