diff --git a/internal/testutil/teadriver/driver.go b/internal/testutil/teadriver/driver.go new file mode 100644 index 0000000..baf05b9 --- /dev/null +++ b/internal/testutil/teadriver/driver.go @@ -0,0 +1,350 @@ +// Package teadriver drives a Bubble Tea model in tests without a terminal: +// it feeds key/mouse messages to Update, executes returned commands in +// goroutines (unwrapping Batch and Sequence) and feeds their results back +// until the model is quiet, and renders View without ANSI escapes. +// +// The lipgloss color profile is process-global, so tests using a Driver must +// not run in parallel with each other. +package teadriver + +import ( + "fmt" + "reflect" + "strings" + "sync" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + "github.com/muesli/termenv" +) + +// DefaultLongCmd is how long Settle waits for a single command before +// treating it as a timer or long wait (e.g. tea.Tick with a long delay) and +// returning without it. Its result is still delivered on a later Settle. +const DefaultLongCmd = time.Second + +// Option configures New. +type Option func(*Driver) + +// WithProfile renders with the given color profile instead of Ascii. +func WithProfile(p termenv.Profile) Option { return func(d *Driver) { d.profile = p } } + +// WithLongCmd overrides DefaultLongCmd. +func WithLongCmd(dur time.Duration) Option { return func(d *Driver) { d.LongCmd = dur } } + +// WithoutInit skips running the model's Init command. +func WithoutInit() Option { return func(d *Driver) { d.skipInit = true } } + +// Driver runs a model. It is not safe for concurrent use. +type Driver struct { + // LongCmd: see DefaultLongCmd. + LongCmd time.Duration + + t testing.TB + m tea.Model + w, h int + profile termenv.Profile + skipInit bool + + pending []tea.Cmd + nextID int + inflight map[int]time.Time + results chan result + + quit bool + execs []tea.Msg + msgs int +} + +type result struct { + id int + msg tea.Msg + final bool // the command (or whole sequence) is done + panic any +} + +// New creates a driver, sets the color profile (Ascii by default), sends a +// WindowSizeMsg of w×h and queues the model's Init command (run by the +// next Settle). +func New(t testing.TB, m tea.Model, w, h int, opts ...Option) *Driver { + t.Helper() + d := &Driver{ + LongCmd: DefaultLongCmd, + t: t, + m: m, + w: w, + h: h, + profile: termenv.Ascii, + inflight: map[int]time.Time{}, + results: make(chan result, 1024), + } + for _, o := range opts { + o(d) + } + prev := lipgloss.ColorProfile() + lipgloss.SetColorProfile(d.profile) + t.Cleanup(func() { lipgloss.SetColorProfile(prev) }) + if !d.skipInit { + d.enqueue(m.Init()) + } + d.Send(tea.WindowSizeMsg{Width: w, Height: h}) + return d +} + +// Model returns the current model. +func (d *Driver) Model() tea.Model { return d.m } + +// Quit reports whether a command returned tea.QuitMsg. +func (d *Driver) Quit() bool { return d.quit } + +// Execs returns the tea.ExecProcess requests the model made. They are +// recorded, never run. +func (d *Driver) Execs() []tea.Msg { return d.execs } + +// Send passes msg to Update synchronously and queues the returned command. +func (d *Driver) Send(msg tea.Msg) { + d.t.Helper() + m, cmd := d.m.Update(msg) + if m == nil { + d.t.Fatalf("teadriver: Update(%T) returned nil model", msg) + } + d.m = m + d.msgs++ + d.enqueue(cmd) +} + +// Press sends one key message per argument, using tea key names: "enter", +// "esc", "tab", "f5", "pgdown", "ctrl+r", "alt+left", "shift+up", " " or +// "space", or literal text ("j", "п") sent as runes. +func (d *Driver) Press(keys ...string) { + d.t.Helper() + for _, k := range keys { + d.Send(Key(d.t, k)) + } +} + +// Type sends one rune key message per rune of text. +func (d *Driver) Type(text string) { + d.t.Helper() + for _, r := range text { + if r == ' ' { + d.Send(tea.KeyMsg{Type: tea.KeySpace, Runes: []rune{' '}}) + continue + } + d.Send(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}}) + } +} + +// Mouse sends a press of button at cell (x, y) followed by a release. +func (d *Driver) Mouse(x, y int, button tea.MouseButton) { + d.t.Helper() + d.Send(tea.MouseMsg{X: x, Y: y, Button: button, Action: tea.MouseActionPress}) + if button != tea.MouseButtonWheelUp && button != tea.MouseButtonWheelDown { + d.Send(tea.MouseMsg{X: x, Y: y, Button: button, Action: tea.MouseActionRelease}) + } +} + +// Screen renders View with ANSI escapes stripped. +func (d *Driver) Screen() string { return ansi.Strip(d.m.View()) } + +// ScreenContains reports whether the rendered screen contains s. +func (d *Driver) ScreenContains(s string) bool { return strings.Contains(d.Screen(), s) } + +// Settle runs queued commands concurrently and feeds their messages back to +// Update until nothing is left, except commands that have been running +// longer than LongCmd (timers); their results arrive on a later Settle. It +// also returns at timeout, logging what is still running. +func (d *Driver) Settle(timeout time.Duration) { + d.t.Helper() + deadline := time.Now().Add(timeout) + for { + d.launchPending() + // Deliver whatever is already done without blocking. + if d.drainReady() { + continue + } + if len(d.inflight) == 0 { + return + } + now := time.Now() + var wake time.Time + for _, started := range d.inflight { + if old := started.Add(d.LongCmd); old.After(now) && (wake.IsZero() || old.Before(wake)) { + wake = old + } + } + if wake.IsZero() { + return // only long-running commands remain + } + if now.After(deadline) { + d.t.Logf("teadriver: Settle timed out after %v with %d command(s) running", timeout, len(d.inflight)) + return + } + if deadline.Before(wake) { + wake = deadline + } + timer := time.NewTimer(time.Until(wake)) + select { + case r := <-d.results: + timer.Stop() + d.handle(r) + case <-timer.C: + } + } +} + +func (d *Driver) drainReady() bool { + got := false + for { + select { + case r := <-d.results: + d.handle(r) + got = true + default: + return got + } + } +} + +func (d *Driver) enqueue(cmd tea.Cmd) { + if cmd != nil { + d.pending = append(d.pending, cmd) + } +} + +func (d *Driver) launchPending() { + cmds := d.pending + d.pending = nil + for _, c := range cmds { + d.launch([]tea.Cmd{c}) + } +} + +// launch runs cmds one after another in a goroutine (one cmd for a plain +// command, several for a Sequence). +func (d *Driver) launch(cmds []tea.Cmd) { + id := d.nextID + d.nextID++ + d.inflight[id] = time.Now() + results := d.results + go func() { + var once sync.Once + defer func() { + if p := recover(); p != nil { + once.Do(func() { results <- result{id: id, final: true, panic: p} }) + } + }() + for _, c := range cmds { + if c != nil { + results <- result{id: id, msg: c()} + } + } + once.Do(func() { results <- result{id: id, final: true} }) + }() +} + +func (d *Driver) handle(r result) { + d.t.Helper() + if r.final { + delete(d.inflight, r.id) + } + if r.panic != nil { + d.t.Fatalf("teadriver: command panicked: %v", r.panic) + } + d.deliver(r.msg) +} + +func (d *Driver) deliver(msg tea.Msg) { + d.t.Helper() + switch msg := msg.(type) { + case nil: + return + case tea.BatchMsg: + for _, c := range msg { + d.enqueue(c) + } + return + case tea.QuitMsg: + d.quit = true + return + } + if cmds, ok := asSequence(msg); ok { + d.launch(cmds) + return + } + if isExec(msg) { + d.execs = append(d.execs, msg) + return + } + d.Send(msg) +} + +const teaPkg = "github.com/charmbracelet/bubbletea" + +func asSequence(msg tea.Msg) ([]tea.Cmd, bool) { + v := reflect.ValueOf(msg) + t := v.Type() + if t.PkgPath() != teaPkg || t.Name() != "sequenceMsg" || t.Kind() != reflect.Slice { + return nil, false + } + cmds := make([]tea.Cmd, v.Len()) + for i := range cmds { + cmds[i], _ = v.Index(i).Interface().(tea.Cmd) + } + return cmds, true +} + +func isExec(msg tea.Msg) bool { + t := reflect.TypeOf(msg) + return t.PkgPath() == teaPkg && t.Name() == "execMsg" +} + +var keyTypes = func() map[string]tea.KeyType { + m := map[string]tea.KeyType{} + for kt := tea.KeyType(-200); kt <= 200; kt++ { + if kt == tea.KeyRunes { + continue + } + name := tea.Key{Type: kt}.String() + if name == "" { + continue + } + if _, dup := m[name]; !dup { + m[name] = kt + } + } + m["space"] = tea.KeySpace + return m +}() + +// Key converts a key name (see Press) to a tea.KeyMsg. +func Key(t testing.TB, s string) tea.KeyMsg { + t.Helper() + if kt, ok := keyTypes[s]; ok { + k := tea.KeyMsg{Type: kt} + if kt == tea.KeySpace { + k.Runes = []rune{' '} + } + return k + } + if rest, ok := strings.CutPrefix(s, "alt+"); ok && rest != "" { + k := Key(t, rest) + k.Alt = true + return k + } + if s == "" { + t.Fatalf("teadriver: empty key") + } + if strings.Contains(s, "+") && len([]rune(s)) > 1 { + t.Fatalf("teadriver: unknown key %q", s) + } + return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)} +} + +// String describes the driver state for failure messages. +func (d *Driver) String() string { + return fmt.Sprintf("teadriver{msgs=%d inflight=%d pending=%d quit=%v}", d.msgs, len(d.inflight), len(d.pending), d.quit) +} diff --git a/internal/testutil/teadriver/driver_test.go b/internal/testutil/teadriver/driver_test.go new file mode 100644 index 0000000..78594de --- /dev/null +++ b/internal/testutil/teadriver/driver_test.go @@ -0,0 +1,107 @@ +package teadriver + +import ( + "strings" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" +) + +type note string + +type toy struct { + got []string + keys []string +} + +func (m toy) Init() tea.Cmd { return func() tea.Msg { return note("init") } } + +func emit(s string) tea.Cmd { return func() tea.Msg { return note(s) } } + +func (m toy) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case note: + m.got = append(m.got, string(msg)) + if msg == "a" { + return m, emit("a-followup") + } + case tea.KeyMsg: + m.keys = append(m.keys, msg.String()) + switch msg.String() { + case "x": + return m, tea.Batch( + emit("a"), + tea.Batch(emit("b"), nil, emit("c")), + tea.Sequence(emit("s1"), emit("s2")), + tea.Tick(time.Hour, func(time.Time) tea.Msg { return note("never") }), + ) + case "q": + return m, tea.Quit + } + } + return m, nil +} + +func (m toy) View() string { return "\x1b[1mgot:\x1b[0m " + strings.Join(m.got, ",") } + +func TestDriverSettleBatch(t *testing.T) { + d := New(t, toy{}, 80, 24, WithLongCmd(100*time.Millisecond)) + d.Settle(time.Second) + d.Press("x") + t0 := time.Now() + d.Settle(5 * time.Second) + if el := time.Since(t0); el > 2*time.Second { + t.Fatalf("Settle waited for the long tick: %v", el) + } + m := d.Model().(toy) + have := map[string]bool{} + for _, g := range m.got { + have[g] = true + } + for _, want := range []string{"init", "a", "a-followup", "b", "c", "s1", "s2"} { + if !have[want] { + t.Errorf("missing %q in %v", want, m.got) + } + } + if have["never"] { + t.Error("hour-long tick must not be awaited") + } + idx := func(s string) int { + for i, g := range m.got { + if g == s { + return i + } + } + return -1 + } + if idx("s1") > idx("s2") { + t.Errorf("sequence out of order: %v", m.got) + } + if s := d.Screen(); strings.Contains(s, "\x1b") || !strings.HasPrefix(s, "got: init") { + t.Errorf("screen not stripped: %q", s) + } + d.Press("q") + d.Settle(time.Second) + if !d.Quit() { + t.Error("tea.Quit not detected") + } +} + +func TestDriverKeys(t *testing.T) { + for _, k := range []string{"enter", "esc", "tab", "f5", "f12", "pgdown", "ctrl+r", "shift+up", "alt+left", "backspace", "delete", " ", "j", "п"} { + got := Key(t, k).String() + want := k + if k == "alt+left" { + want = "alt+left" + } + if got != want { + t.Errorf("Key(%q).String() = %q", k, got) + } + } + d := New(t, toy{}, 80, 24, WithoutInit()) + d.Type("ab п") + if got := strings.Join(d.Model().(toy).keys, "|"); got != "a|b| |п" { + t.Errorf("typed keys %q", got) + } +} diff --git a/internal/ui/helpers_test.go b/internal/ui/helpers_test.go new file mode 100644 index 0000000..94fc134 --- /dev/null +++ b/internal/ui/helpers_test.go @@ -0,0 +1,138 @@ +package ui + +import ( + "io" + "log" + "os" + "path/filepath" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/config" + "vcom/internal/testutil/teadriver" +) + +func TestMain(m *testing.M) { + log.SetOutput(io.Discard) + os.Exit(m.Run()) +} + +// isolateEnv points HOME/XDG dirs at a temp dir so session, trash and SSH +// state never touch the real user's files. +func isolateEnv(t *testing.T) string { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share")) + t.Setenv("SSH_AUTH_SOCK", "") + t.Setenv("VISUAL", "") + t.Setenv("EDITOR", "") + if err := os.MkdirAll(filepath.Join(home, ".ssh"), 0o700); err != nil { + t.Fatal(err) + } + return home +} + +// newTestModel builds the old UI model with both panes at the given paths. +func newTestModel(t *testing.T, left, right string, mutate ...func(*config.Config)) Model { + t.Helper() + isolateEnv(t) + cfg := config.Default() + cfg.UI.IconMode = "ascii" + cfg.Startup.LeftPath = left + cfg.Startup.RightPath = right + for _, f := range mutate { + f(&cfg) + } + m, err := NewModel(cfg, "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + m.cleanupArchiveMounts() + m.cleanupRemoteImageTemp() + }) + return m +} + +const settle = 5 * time.Second + +func newDriver(t *testing.T, left, right string, mutate ...func(*config.Config)) *teadriver.Driver { + t.Helper() + m := newTestModel(t, left, right, mutate...) + d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond)) + d.Settle(settle) + return d +} + +// asModel unwraps the driver's model (Update returns Model or *Model). +func asModel(t *testing.T, tm tea.Model) Model { + t.Helper() + switch v := tm.(type) { + case Model: + return v + case *Model: + return *v + } + t.Fatalf("unexpected model type %T", tm) + return Model{} +} + +func cur(t *testing.T, d *teadriver.Driver) Model { return asModel(t, d.Model()) } + +func writeFile(t *testing.T, p, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +// selectName moves the active pane's cursor to the entry called name using +// j/k presses (as a user would). +func selectName(t *testing.T, d *teadriver.Driver, name string) { + t.Helper() + m := cur(t, d) + p := m.activePane() + idx := -1 + for i, e := range p.Entries { + if e.Name == name { + idx = i + } + } + if idx < 0 { + t.Fatalf("entry %q not in active pane %s", name, p.Path) + } + for p.Cursor != idx { + if p.Cursor < idx { + d.Press("j") + } else { + d.Press("k") + } + m = cur(t, d) + p = m.activePane() + } + d.Settle(settle) +} + +func selectedEntryName(t *testing.T, d *teadriver.Driver) string { + t.Helper() + m := cur(t, d) + e, ok := m.activePane().Selected() + if !ok { + return "" + } + return e.Name +} + +// activeOf returns a copy of the active pane. +func activeOf(t *testing.T, d *teadriver.Driver) BrowserPane { + t.Helper() + m := cur(t, d) + return *m.activePane() +} diff --git a/internal/ui/smoke_test.go b/internal/ui/smoke_test.go new file mode 100644 index 0000000..0626150 --- /dev/null +++ b/internal/ui/smoke_test.go @@ -0,0 +1,180 @@ +package ui + +// Behavioural smoke tests for the old UI: keys in, effect on disk and on the +// screen out. They avoid model internals where possible so they can be +// re-pointed at the new UI later. + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" +) + +func exists(p string) bool { _, err := os.Lstat(p); return err == nil } + +func TestSmokeNavigateIntoDirAndBack(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "a.txt"), "hello") + writeFile(t, filepath.Join(dir, "sub", "inner.txt"), "b") + d := newDriver(t, dir, t.TempDir()) + + selectName(t, d, "sub") + d.Press("enter") + d.Settle(settle) + if got := activeOf(t, d).Path; got != filepath.Join(dir, "sub") { + t.Fatalf("after Enter path=%q", got) + } + if !d.ScreenContains("inner.txt") { + t.Fatalf("inner.txt not on screen:\n%s", d.Screen()) + } + + d.Press("backspace") + d.Settle(settle) + if got := activeOf(t, d).Path; got != dir { + t.Fatalf("after Backspace path=%q", got) + } + if got := selectedEntryName(t, d); got != "sub" { + t.Fatalf("cursor should return to sub, got %q", got) + } + if !d.ScreenContains("a.txt") { + t.Fatalf("a.txt not on screen:\n%s", d.Screen()) + } +} + +func TestSmokeMkdir(t *testing.T) { + dir := t.TempDir() + d := newDriver(t, dir, t.TempDir()) + d.Press("f7") + d.Type("newdir") + d.Press("enter") + d.Settle(settle) + if st, err := os.Stat(filepath.Join(dir, "newdir")); err != nil || !st.IsDir() { + t.Fatalf("newdir not created: %v", err) + } + if !d.ScreenContains("newdir/") { + t.Fatalf("newdir not on screen:\n%s", d.Screen()) + } + if got := selectedEntryName(t, d); got != "newdir" { + t.Fatalf("cursor on %q, want newdir", got) + } +} + +func TestSmokeMkdirCyrillic(t *testing.T) { + t.Skip("U-P1-5: fixed in 1.6") + dir := t.TempDir() + d := newDriver(t, dir, t.TempDir()) + d.Press("f7") + d.Type("папка") + d.Press("enter") + d.Settle(settle) + if !exists(filepath.Join(dir, "папка")) { + entries, _ := os.ReadDir(dir) + t.Fatalf("папка not created; dir has %v", entries) + } +} + +func TestSmokeCopyFile(t *testing.T) { + src, dst := t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(src, "a.txt"), "payload") + d := newDriver(t, src, dst) + selectName(t, d, "a.txt") + d.Press("f5") + d.Settle(settle) + d.Press("enter") + d.Settle(settle) + b, err := os.ReadFile(filepath.Join(dst, "a.txt")) + if err != nil || string(b) != "payload" { + t.Fatalf("copy result: %q %v", b, err) + } + if !exists(filepath.Join(src, "a.txt")) { + t.Fatal("source disappeared after copy") + } + if n := strings.Count(d.Screen(), "a.txt"); n < 2 { + t.Fatalf("a.txt should be visible in both panes (%d):\n%s", n, d.Screen()) + } +} + +func TestSmokeRename(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "old.txt"), "x") + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, "old.txt") + d.Press("f2", "ctrl+u") + d.Type("new.txt") + d.Press("enter") + d.Settle(settle) + if exists(filepath.Join(dir, "old.txt")) || !exists(filepath.Join(dir, "new.txt")) { + t.Fatal("rename did not happen on disk") + } + if !d.ScreenContains("new.txt") || d.ScreenContains("old.txt") { + t.Fatalf("screen not updated:\n%s", d.Screen()) + } +} + +func TestSmokeFilterNarrowsList(t *testing.T) { + dir := t.TempDir() + for _, n := range []string{"a1", "b1", "b2", "c1", "zz-target"} { + writeFile(t, filepath.Join(dir, n), "x") + } + d := newDriver(t, dir, t.TempDir()) + if !d.ScreenContains("b2") { + t.Fatalf("b2 should be visible before filtering:\n%s", d.Screen()) + } + d.Press("/") + d.Type("zz") + d.Settle(settle) + s := d.Screen() + if !strings.Contains(s, "zz-target") { + t.Fatalf("zz-target hidden by filter:\n%s", s) + } + for _, n := range []string{"a1", "b1", "b2", "c1"} { + if strings.Contains(s, " "+n+" ") || strings.Contains(s, "] "+n) { + t.Fatalf("%s still visible with filter zz:\n%s", n, s) + } + } +} + +func TestSmokeDeleteWithConfirm(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "victim.txt"), "x") + writeFile(t, filepath.Join(dir, "keep.txt"), "y") + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, "victim.txt") + d.Press("f8") + d.Settle(settle) + if !exists(filepath.Join(dir, "victim.txt")) { + t.Fatal("deleted before confirmation") + } + d.Press("enter") + d.Settle(settle) + if exists(filepath.Join(dir, "victim.txt")) { + t.Fatal("victim.txt still on disk after confirmed delete") + } + if !exists(filepath.Join(dir, "keep.txt")) { + t.Fatal("keep.txt removed") + } + if d.ScreenContains("victim.txt") { + t.Fatalf("victim.txt still on screen:\n%s", d.Screen()) + } +} + +func TestSmokePageDown(t *testing.T) { + t.Skip("U-P1-6: fixed in 1.6") + dir := t.TempDir() + for i := 0; i < 200; i++ { + writeFile(t, filepath.Join(dir, fmt.Sprintf("f%03d", i)), "x") + } + d := newDriver(t, dir, t.TempDir()) + before := activeOf(t, d).Cursor + d.Press("pgdown") + d.Settle(settle) + after := activeOf(t, d).Cursor + if after <= before+5 { + t.Fatalf("PgDn moved cursor %d -> %d", before, after) + } + if !d.ScreenContains(fmt.Sprintf("f%03d", after-1)) { + t.Fatalf("list did not scroll to the cursor:\n%s", d.Screen()) + } +}