vcom/internal/tui/app_test.go
vrubelroman 1bdff32a84
Some checks failed
CI / test (push) Failing after 6m3s
feat(tui): full preview, text viewer and image overlays (6.3)
2026-11-01 22:06:24 +03:00

536 lines
16 KiB
Go

package tui
import (
"context"
"fmt"
"math/rand"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/config"
"vcom/internal/testutil/fstree"
"vcom/internal/testutil/teadriver"
"vcom/internal/tui/keys"
"vcom/internal/tui/viewer"
"vcom/internal/vfs"
"vcom/internal/vfs/localfs"
"vcom/internal/vfs/vfstest"
)
const settle = 3 * time.Second
type harness struct {
t *testing.T
d *teadriver.Driver
app *App
dir string
}
type opt func(*Deps)
func newHarness(t *testing.T, fsys vfs.FS, dir string, opts ...opt) *harness {
t.Helper()
cfg := config.Default()
cfg.Behavior.ConfirmQuit = true
d := Deps{
Config: cfg,
LocalFS: fsys,
StartDirs: [2]string{dir, dir},
SetConfigKey: func(string, string, string, any) (string, error) { return "test.toml", nil },
Opener: []string{"true"},
Clipboard: func(string) error { return nil },
}
for _, o := range opts {
o(&d)
}
app := New(d)
h := &harness{t: t, app: app, dir: dir}
h.d = teadriver.New(t, app, 100, 30, teadriver.WithLongCmd(150*time.Millisecond))
h.d.Settle(settle)
h.check()
return h
}
func (h *harness) check() {
h.t.Helper()
if err := h.app.Invariants(); err != nil {
h.t.Fatalf("invariants: %v\n%s", err, h.d.Screen())
}
}
// press sends keys, settling and checking invariants after each.
func (h *harness) press(ks ...string) {
h.t.Helper()
for _, k := range ks {
h.d.Press(k)
h.d.Settle(settle)
h.check()
}
}
func (h *harness) typ(s string) {
h.t.Helper()
h.d.Type(s)
h.d.Settle(settle)
h.check()
}
func (h *harness) selected() string {
e, _ := h.app.Active().Selected()
return e.Name
}
// cursorTo moves the active panel's cursor onto name.
func (h *harness) cursorTo(name string) {
h.t.Helper()
p := h.app.Active()
for i := 0; i < p.VisibleLen(); i++ {
if e, _ := p.Visible(i); e.Name == name {
p.SetCursor(i)
return
}
}
h.t.Fatalf("%s not in panel: %s", name, h.d.Screen())
}
func tree(t *testing.T, spec fstree.Spec) string {
t.Helper()
dir := t.TempDir()
fstree.Build(t, dir, spec)
return dir
}
// gate blocks hooks until released.
type gate struct {
once sync.Once
ch chan struct{}
}
func newGate(t *testing.T) *gate {
g := &gate{ch: make(chan struct{})}
t.Cleanup(g.open)
return g
}
func (g *gate) open() { g.once.Do(func() { close(g.ch) }) }
// N-P1-1, U-P1-9: a hung ReadDir must not block Update; Esc and q work.
func TestUpdateNeverBlocks(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("f", "x")})
g := newGate(t)
fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, p string) error {
if op == vfstest.OpReadDir {
<-g.ch
}
return nil
}}
cfg := config.Default()
cfg.Behavior.ConfirmQuit = true
app := New(Deps{Config: cfg, LocalFS: fsys, StartDirs: [2]string{dir, dir}})
d := teadriver.New(t, app, 100, 30, teadriver.WithLongCmd(50*time.Millisecond))
d.Settle(time.Second) // the listings hang
for _, k := range []string{"esc", "j", "tab", "o", "o", "q"} {
start := time.Now()
d.Press(k)
if el := time.Since(start); el > 10*time.Millisecond {
t.Errorf("Update(%s) took %v", k, el)
}
}
if !strings.Contains(d.Screen(), "Quit vcom?") {
t.Fatalf("quit dialog not shown while a listing hangs:\n%s", d.Screen())
}
d.Press("q")
d.Settle(time.Second)
if !d.Quit() {
t.Fatal("q q did not quit while a listing hangs")
}
g.open()
}
// U-P1-13: a listing that arrives after a newer navigation is dropped.
func TestStaleListingIgnored(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("a"), fstree.File("a/in-a", ""), fstree.Dir("b"), fstree.File("b/in-b", "")})
g := newGate(t)
fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, p string) error {
if op == vfstest.OpReadDir && filepath.Base(p) == "a" {
<-g.ch
}
return nil
}}
h := newHarness(t, fsys, dir)
h.cursorTo("a")
h.press("enter") // hangs
if h.app.Active().Path() != dir {
t.Fatal("panel changed before its listing arrived")
}
h.cursorTo("b")
h.press("enter")
if got := h.app.Active().Path(); got != filepath.Join(dir, "b") {
t.Fatalf("path = %s", got)
}
g.open()
h.d.Settle(settle)
if got := h.app.Active().Path(); got != filepath.Join(dir, "b") {
t.Fatalf("stale listing of a applied: path = %s", got)
}
if h.selected() != "in-b" && !h.d.ScreenContains("in-b") {
t.Fatalf("b's content not shown:\n%s", h.d.Screen())
}
}
// U-P1-13: a stale preview (Image) must not knock the viewer out of Caret.
func TestStalePreviewDoesNotExitCaret(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("a.txt", "line1\nline2"), fstree.File("b.png", "img")})
g := newGate(t)
prev := func(ctx context.Context, loc vfs.Location, fi vfs.FileInfo, _ int64) (viewer.Content, error) {
if fi.Name == "b.png" {
<-g.ch // ignores ctx on purpose: the result arrives late
return viewer.Content{Kind: viewer.Image, Title: "b.png"}, nil
}
return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: []string{"line1", "line2"}}, nil
}
h := newHarness(t, localfs.New(), dir, func(d *Deps) { d.Preview = prev })
h.cursorTo("a.txt")
h.press("o")
if h.app.Viewer().Kind != viewer.Text {
t.Fatalf("preview of a.txt not loaded: %v", h.app.Viewer().Kind)
}
h.press("j") // b.png: its preview hangs
h.press("k") // back to a.txt
h.press("i")
if h.app.InputOwner() != keys.CtxCaret {
t.Fatalf("not in caret: %s", h.app.InputOwner())
}
g.open()
h.d.Settle(settle)
h.check()
if h.app.InputOwner() != keys.CtxCaret || h.app.Viewer().Kind != viewer.Text {
t.Fatalf("stale preview changed the viewer: owner %s kind %v", h.app.InputOwner(), h.app.Viewer().Kind)
}
}
func lockedFS(dir string) vfs.FS {
return &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, p string) error {
if op == vfstest.OpReadDir && filepath.Base(p) == "locked" {
return &os.PathError{Op: "open", Path: p, Err: vfs.ErrPermission}
}
return nil
}}
}
// U-P1-8: a failed navigation leaves the panel as it was.
func TestNavErrorKeepsPanel(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("locked"), fstree.File("other", "")})
h := newHarness(t, lockedFS(dir), dir)
h.cursorTo("locked")
before := h.app.Active().VisibleLen()
h.press("enter")
p := h.app.Active()
if p.Path() != dir || p.VisibleLen() != before || h.selected() != "locked" || p.Loading {
t.Fatalf("panel changed: path %s, %d entries, on %q", p.Path(), p.VisibleLen(), h.selected())
}
}
// U-P1-1: errors are visible in the status line.
func TestStatusLineShowsError(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("locked")})
h := newHarness(t, lockedFS(dir), dir)
h.cursorTo("locked")
h.press("enter")
scr := h.d.Screen()
last := strings.Split(scr, "\n")
status := last[len(last)-2]
if !strings.Contains(status, "Cannot open") || !strings.Contains(status, "permission") {
t.Fatalf("status line = %q", status)
}
// It stays at least until a key is pressed.
h.d.Settle(settle)
if !h.d.ScreenContains("Cannot open") {
t.Fatal("error vanished without a key press")
}
}
// U-P1-8: if the current directory vanishes, a refresh climbs to the
// nearest existing parent.
func TestVanishedDirClimbsUp(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("x/y/z"), fstree.File("x/keep", "")})
deep := filepath.Join(dir, "x", "y", "z")
h := newHarness(t, localfs.New(), deep)
if err := os.RemoveAll(filepath.Join(dir, "x", "y")); err != nil {
t.Fatal(err)
}
h.press("ctrl+r")
if got := h.app.Active().Path(); got != filepath.Join(dir, "x") {
t.Fatalf("path = %s, want %s", got, filepath.Join(dir, "x"))
}
if got := h.app.Passive().Path(); got != filepath.Join(dir, "x") {
t.Fatalf("passive path = %s", got)
}
if !h.d.ScreenContains("vanished") {
t.Fatalf("no notice:\n%s", h.d.Screen())
}
}
// U-P1-16: q closes layers first; quitting needs confirmation; q q is fast.
func TestQClosesLayersThenConfirmsQuit(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("apple", ""), fstree.File("banana", "")})
h := newHarness(t, localfs.New(), dir)
h.press("o")
if h.app.Screen() != ScreenInfo {
t.Fatal("o did not open Info")
}
h.press("q")
if h.app.Screen() != ScreenBrowse || h.d.Quit() {
t.Fatal("q in Info did not just close Info")
}
h.press("/")
h.typ("an")
h.press("enter")
if h.app.Active().Filter() != "an" {
t.Fatalf("filter = %q", h.app.Active().Filter())
}
h.press("q")
if h.d.Quit() || !h.d.ScreenContains("Quit vcom?") {
t.Fatal("q in Browse quit without asking")
}
h.press("esc")
if h.d.Quit() || h.d.ScreenContains("Quit vcom?") {
t.Fatal("Esc in the quit dialog did not just close it")
}
h.press("esc") // drops the filter, never quits
if h.app.Active().Filter() != "" || h.d.Quit() {
t.Fatal("Esc did not drop the filter")
}
h.press("q", "q")
if !h.d.Quit() || !h.app.Quitting() {
t.Fatal("q q did not quit")
}
}
// U-P1-6: PgDn moves a page.
func TestPgDn(t *testing.T) {
var spec fstree.Spec
for i := 0; i < 200; i++ {
spec = append(spec, fstree.File(fmt.Sprintf("f%03d", i), ""))
}
h := newHarness(t, localfs.New(), tree(t, spec))
rows := h.app.Active().Rows()
if rows < 10 {
t.Fatalf("rows = %d", rows)
}
h.press("pgdown")
if c := h.app.Active().Cursor(); c != rows-1 {
t.Fatalf("cursor after PgDn = %d, want %d", c, rows-1)
}
h.press("pgdown", "pgup")
if c := h.app.Active().Cursor(); c != rows-1 {
t.Fatalf("cursor after PgDn PgUp = %d", c)
}
h.press("G")
if c := h.app.Active().Cursor(); c != 200 { // ".." + 200 files
t.Fatalf("G: cursor %d", c)
}
}
func TestInvariantsAfterEachStep(t *testing.T) {
dir := tree(t, fstree.Spec{
fstree.File("a.txt", "hello\nworld"), fstree.File("b.bin", "\x00\x01"), fstree.Dir("sub"),
fstree.File("sub/c.txt", "c"), fstree.Symlink("link", "sub"),
})
seed := time.Now().UnixNano()
t.Logf("seed %d", seed)
rng := rand.New(rand.NewSource(seed))
pool := []string{"j", "k", "o", "i", "v", "esc", "q", "/", "a", "enter", "tab", "ctrl+t", "f3",
"pgdown", "g", "G", "?", "t", "h", "l", "n", "y", "insert", "ctrl+c", "backspace", "W", "й", "п"}
cfg := config.Default()
cfg.Behavior.ConfirmQuit = true
app := New(Deps{Config: cfg, LocalFS: localfs.New(), StartDirs: [2]string{dir, dir},
SetConfigKey: func(string, string, string, any) (string, error) { return "x", nil },
Opener: []string{"true"}, Clipboard: func(string) error { return nil }})
d := teadriver.New(t, app, 80, 24, teadriver.WithLongCmd(20*time.Millisecond))
d.Settle(settle)
for i := 0; i < 400; i++ {
k := pool[rng.Intn(len(pool))]
d.Press(k)
d.Settle(settle)
if err := app.Invariants(); err != nil {
t.Fatalf("step %d (%q): %v", i, k, err)
}
_ = d.Screen()
}
}
// Design §9.2: the theme is saved with config.SetKey (comments kept).
func TestThemeSelectPreservesConfigComments(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("f", "")})
cfgPath := filepath.Join(t.TempDir(), "vcom.toml")
orig := "# my settings\n[ui]\n# the look\ntheme = \"nord\"\nshow_footer = true\n"
if err := os.WriteFile(cfgPath, []byte(orig), 0o600); err != nil {
t.Fatal(err)
}
h := newHarness(t, localfs.New(), dir, func(d *Deps) {
d.Config.UI.Theme = "nord"
d.ConfigPath = cfgPath
d.SetConfigKey = config.SetKey
})
h.press("t", "down")
next := h.app.ThemeName()
if next == "nord" {
t.Fatal("no live preview")
}
h.press("enter")
data, _ := os.ReadFile(cfgPath)
got := string(data)
if !strings.Contains(got, "theme = \""+next+"\"") || !strings.Contains(got, "# my settings") ||
!strings.Contains(got, "# the look") || !strings.Contains(got, "show_footer = true") {
t.Fatalf("config after save:\n%s", got)
}
// Esc reverts the live preview and writes nothing.
h.press("t", "down", "esc")
if h.app.ThemeName() != next {
t.Fatalf("Esc kept %s", h.app.ThemeName())
}
if data2, _ := os.ReadFile(cfgPath); string(data2) != got {
t.Fatal("Esc wrote the config")
}
}
// Crutch #10/#14: under a modal, the mouse does nothing to the panels.
func TestMouseUnderModalIgnored(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("a", ""), fstree.File("b", ""), fstree.File("c", "")})
h := newHarness(t, localfs.New(), dir)
h.press("q")
cur := h.app.Active().Cursor()
lr := h.app.listRect(0)
h.d.Mouse(lr.X+1, lr.Y+2, tea.MouseButtonLeft)
h.d.Mouse(lr.X+1, lr.Y+2, tea.MouseButtonWheelDown)
h.d.Settle(settle)
if h.app.Active().Cursor() != cur || h.app.active != 0 || !h.d.ScreenContains("Quit vcom?") {
t.Fatal("click under the modal acted")
}
}
func TestMarksKeptOnTab(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("a", ""), fstree.File("b", "")})
h := newHarness(t, localfs.New(), dir)
h.cursorTo("a")
h.press("insert")
h.press("tab", "tab")
if h.app.Active().MarkCount() != 1 || !h.app.Active().Marked("a") {
t.Fatal("marks lost on Tab")
}
h.press("esc")
if h.app.Active().MarkCount() != 0 {
t.Fatal("Esc did not clear marks")
}
}
// U-P1-4 through the App: a click picks the visible row under the mouse.
func TestFilterVisibleIndexAndMouseApp(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("abc", ""), fstree.File("bcd", ""), fstree.File("xyz", ""), fstree.File("xbz", "")})
h := newHarness(t, localfs.New(), dir)
h.press("/")
h.typ("b")
h.press("enter")
lr := h.app.listRect(0)
h.d.Mouse(lr.X+2, lr.Y+2, tea.MouseButtonLeft) // third row: "..", abc, bcd
h.d.Settle(settle)
if got := h.selected(); got != "bcd" {
t.Fatalf("clicked %q, want bcd\n%s", got, h.d.Screen())
}
// A double click opens like Enter (here: a file → not available yet, no crash).
h.d.Mouse(lr.X+2, lr.Y+2, tea.MouseButtonLeft)
h.d.Settle(settle)
h.check()
}
// U-P1-5 through the App: Cyrillic goes into the filter as typed.
func TestTextContextPassesRunesApp(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("папка"), fstree.File("quit", "")})
h := newHarness(t, localfs.New(), dir)
h.press("/")
h.typ("папка")
if got := h.app.Active().Filter(); got != "папка" {
t.Fatalf("filter = %q", got)
}
h.press("enter")
h.press("/")
h.typ("q") // a letter here, not quit
if h.d.Quit() || h.d.ScreenContains("Quit vcom?") {
t.Fatal("q in the filter line acted as a command")
}
}
func TestNavigationHistoryAndParent(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("sub/deeper"), fstree.File("top", "")})
h := newHarness(t, localfs.New(), dir)
h.cursorTo("sub")
h.press("l")
h.cursorTo("deeper")
h.press("enter")
if h.app.Active().Path() != filepath.Join(dir, "sub", "deeper") {
t.Fatal("enter failed")
}
h.press("h")
if h.app.Active().Path() != filepath.Join(dir, "sub") || h.selected() != "deeper" {
t.Fatalf("parent: %s on %q", h.app.Active().Path(), h.selected())
}
h.press("[")
if h.app.Active().Path() != filepath.Join(dir, "sub", "deeper") {
t.Fatalf("back: %s", h.app.Active().Path())
}
h.press("]")
if h.app.Active().Path() != filepath.Join(dir, "sub") {
t.Fatalf("forward: %s", h.app.Active().Path())
}
h.press("?")
if !h.d.ScreenContains("Help") || !h.d.ScreenContains("history back") {
t.Fatalf("help:\n%s", h.d.Screen())
}
h.press("esc")
_ = h.app.dispatch(keys.ActionID("test.unbound")) // an action without a handler: a note, no crash
if !h.d.ScreenContains("not available yet") {
t.Fatalf("no note for an unimplemented action:\n%s", h.d.Screen())
}
}
func TestViewScreenAndBack(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("a.txt", "one\ntwo\nthree"), fstree.Dir("d")})
h := newHarness(t, localfs.New(), dir)
h.cursorTo("d")
h.press("f3")
if h.app.Screen() != ScreenBrowse {
t.Fatal("F3 on a directory opened View")
}
h.cursorTo("a.txt")
h.press("f3")
if h.app.Screen() != ScreenView || !h.d.ScreenContains("three") {
t.Fatalf("View:\n%s", h.d.Screen())
}
h.press("i", "v")
if h.app.InputOwner() != keys.CtxVisual {
t.Fatalf("owner %s", h.app.InputOwner())
}
h.press("esc", "esc")
if h.app.InputOwner() != keys.CtxViewScroll {
t.Fatalf("owner %s", h.app.InputOwner())
}
h.press("ctrl+t")
if !h.app.nativeSelect {
t.Fatal("ctrl+t")
}
h.press("esc")
if h.app.nativeSelect || h.app.Screen() != ScreenView {
t.Fatal("Esc must end native selection first")
}
h.press("q")
if h.app.Screen() != ScreenBrowse {
t.Fatal("q did not close View")
}
}