cat / 012
clone

a spreadsheet for the terminal: lotus 1-2-3 looks, google sheets keys and formulas, one go binary

main
012 / internal / ui / choicebar / choicebar_test.go
choicebar_test.go 2.7K
1package choicebar23import (4 "strings"5 "testing"67 tea "charm.land/bubbletea/v2"8 "github.com/charmbracelet/x/ansi"910 "src.rest/cat/012/internal/ui/overlay"11 "src.rest/cat/012/internal/ui/theme"12)1314// fakeHost records what the bar did.15type fakeHost struct {16 th theme.Theme17 closed int18 answers []string19}2021func (f *fakeHost) Theme() *theme.Theme { return &f.th }22func (f *fakeHost) Close() { f.closed++ }2324func (f *fakeHost) RecordAnswer(answer string, cancelled bool) {25 if cancelled {26 answer = "(cancelled)"27 }28 f.answers = append(f.answers, answer)29}3031// newBar asks about unsaved changes, noting the choice made in *ran.32func newBar(ran *string) (*Bar, *fakeHost) {33 h := &fakeHost{th: theme.New(true)}34 run := func(what string) func() tea.Cmd { return func() tea.Cmd { *ran = what; return nil } }35 return New(h, "You have unsaved changes.", true, "More", []Choice{36 {Key: "enter", Label: "Save and quit", Run: run("save")},37 {Key: "d", Label: "Discard", Run: run("discard")},38 {Key: "esc", Label: "Cancel", Run: run("cancel")},39 }), h40}4142func TestKeysChoose(t *testing.T) {43 var ran string44 b, h := newBar(&ran)45 b.Key(tea.KeyPressMsg{Code: 'x', Text: "x"})46 if ran != "" || h.closed != 0 {47 t.Fatalf("a key of no choice acted: %q, closed %d", ran, h.closed)48 }49 b.Key(tea.KeyPressMsg{Code: 'D', Text: "D", Mod: tea.ModShift})50 if ran != "discard" || h.closed != 1 || strings.Join(h.answers, ",") != "d" {51 t.Fatalf("D: ran %q, closed %d, answers %v", ran, h.closed, h.answers)52 }53 b.Key(tea.KeyPressMsg{Code: tea.KeyEscape})54 if ran != "cancel" || h.answers[1] != "(cancelled)" {55 t.Fatalf("Esc: ran %q, answers %v", ran, h.answers)56 }57}5859func TestFindByKeyOrLabel(t *testing.T) {60 var ran string61 b, _ := newBar(&ran)62 for answer, want := range map[string]int{"enter": 0, "DISCARD": 1, "Esc": 2, "nope": -1} {63 if got := b.Find(answer); got != want {64 t.Errorf("Find(%q) = %d, want %d", answer, got, want)65 }66 }67}6869func TestClickChoosesOrCancels(t *testing.T) {70 var ran string71 b, h := newBar(&ran)72 line, _ := b.ContextLine()73 plain := ansi.Strip(line)74 if !strings.HasPrefix(plain, "You have unsaved changes. ") || !strings.Contains(plain, "Discard ") {75 t.Fatalf("context line %q", plain)76 }77 x := strings.Index(plain, "Discard")78 b.Mouse(overlay.MouseEvent{Kind: overlay.MousePress, X: x, Y: overlay.ContextLine})79 if ran != "discard" {80 t.Fatalf("clicking Discard ran %q", ran)81 }82 ran = ""83 b.Mouse(overlay.MouseEvent{Kind: overlay.MousePress, X: 0, Y: overlay.ContextLine + 3})84 if ran != "" || h.closed != 2 {85 t.Fatalf("a click elsewhere should only close: ran %q, closed %d", ran, h.closed)86 }87 if desc, _ := b.Status(); desc != "More" {88 t.Fatalf("status %q", desc)89 }90}