vcom/internal/testutil/teadriver/driver.go

351 lines
8.5 KiB
Go
Raw Normal View History

// 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)
}