Skip to content
Myr

tea_test.go

This file

Path

tea_test.go

846 lines · 17.0 KiB · Go

Last changed by

fix: skip capability queries when input is disabled (#1801)draw me an elephantbefore adoption8b10e22

History of this file

Take it

1package tea23import (4	"bytes"5	"context"6	"errors"7	"fmt"8	"io"9	"strings"10	"sync"11	"sync/atomic"12	"testing"13	"time"1415	"github.com/charmbracelet/x/ansi"16)1718type ctxImplodeMsg struct {19	cancel context.CancelFunc20}2122type incrementMsg struct{}2324type panicMsg struct{}2526func panicCmd() Msg {27	panic("testing goroutine panic behavior")28}2930type testModel struct {31	executed atomic.Value32	counter  atomic.Value33}3435func (m *testModel) Init() Cmd {36	return nil37}3839func (m *testModel) Update(msg Msg) (Model, Cmd) {40	switch msg := msg.(type) {41	case ctxImplodeMsg:42		msg.cancel()43		time.Sleep(100 * time.Millisecond)4445	case incrementMsg:46		i := m.counter.Load()47		if i == nil {48			m.counter.Store(1)49		} else {50			m.counter.Store(i.(int) + 1)51		}5253	case KeyPressMsg:54		switch msg.String() {55		case "q", "ctrl+c":56			return m, Quit57		}5859	case panicMsg:60		panic("testing panic behavior")61	}6263	return m, nil64}6566func (m *testModel) View() View {67	m.executed.Store(true)68	return NewView("success")69}7071func TestTeaModel(t *testing.T) {72	t.Parallel()73	var buf bytes.Buffer74	var in bytes.Buffer75	in.Write([]byte("q"))7677	ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)78	defer cancel()7980	p := NewProgram(&testModel{},81		WithContext(ctx),82		WithInput(&in),83		WithOutput(&buf),84	)85	if _, err := p.Run(); err != nil {86		t.Fatal(err)87	}8889	if buf.Len() == 0 {90		t.Fatal("no output")91	}92}9394func TestTeaQuit(t *testing.T) {95	t.Parallel()96	var buf bytes.Buffer97	var in bytes.Buffer9899	m := &testModel{}100	p := NewProgram(m,101		WithInput(&in),102		WithOutput(&buf),103	)104	go func() {105		for {106			time.Sleep(time.Millisecond)107			if m.executed.Load() != nil {108				p.Quit()109				return110			}111		}112	}()113114	if _, err := p.Run(); err != nil {115		t.Fatal(err)116	}117}118119func TestTeaWaitQuit(t *testing.T) {120	t.Parallel()121	var buf bytes.Buffer122	var in bytes.Buffer123124	progStarted := make(chan struct{})125	waitStarted := make(chan struct{})126	errChan := make(chan error, 1)127128	m := &testModel{}129	p := NewProgram(m,130		WithInput(&in),131		WithOutput(&buf),132	)133134	go func() {135		_, err := p.Run()136		errChan <- err137	}()138139	go func() {140		for {141			time.Sleep(time.Millisecond)142			if m.executed.Load() != nil {143				close(progStarted)144145				<-waitStarted146				time.Sleep(50 * time.Millisecond)147				p.Quit()148149				return150			}151		}152	}()153154	<-progStarted155156	var wg sync.WaitGroup157	for range 5 {158		wg.Add(1)159		go func() {160			p.Wait()161			wg.Done()162		}()163	}164	close(waitStarted)165	wg.Wait()166167	err := <-errChan168	if err != nil {169		t.Fatalf("Expected nil, got %v", err)170	}171}172173func TestTeaWaitKill(t *testing.T) {174	t.Parallel()175	var buf bytes.Buffer176	var in bytes.Buffer177178	progStarted := make(chan struct{})179	waitStarted := make(chan struct{})180	errChan := make(chan error, 1)181182	m := &testModel{}183	p := NewProgram(m,184		WithInput(&in),185		WithOutput(&buf),186	)187188	go func() {189		_, err := p.Run()190		errChan <- err191	}()192193	go func() {194		for {195			time.Sleep(time.Millisecond)196			if m.executed.Load() != nil {197				close(progStarted)198199				<-waitStarted200				time.Sleep(50 * time.Millisecond)201				p.Kill()202203				return204			}205		}206	}()207208	<-progStarted209210	var wg sync.WaitGroup211	for range 5 {212		wg.Add(1)213		go func() {214			p.Wait()215			wg.Done()216		}()217	}218	close(waitStarted)219	wg.Wait()220221	err := <-errChan222	if !errors.Is(err, ErrProgramKilled) {223		t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)224	}225}226227func TestTeaWithFilter(t *testing.T) {228	for _, preventCount := range []uint32{0, 1, 2} {229		t.Run(fmt.Sprintf("prevent_%d", preventCount), func(t *testing.T) {230			t.Parallel()231			testTeaWithFilter(t, preventCount)232		})233	}234}235236func testTeaWithFilter(t *testing.T, preventCount uint32) {237	var buf bytes.Buffer238	var in bytes.Buffer239240	m := &testModel{}241	shutdowns := uint32(0)242	p := NewProgram(m,243		WithInput(&in),244		WithOutput(&buf),245	)246	p.filter = func(_ Model, msg Msg) Msg {247		if _, ok := msg.(QuitMsg); !ok {248			return msg249		}250		if shutdowns < preventCount {251			atomic.AddUint32(&shutdowns, 1)252			return nil253		}254		return msg255	}256257	go func() {258		for atomic.LoadUint32(&shutdowns) <= preventCount {259			time.Sleep(time.Millisecond)260			p.Quit()261		}262	}()263264	if _, err := p.Run(); err != nil {265		t.Fatal(err)266	}267	if shutdowns != preventCount {268		t.Errorf("Expected %d prevented shutdowns, got %d", preventCount, shutdowns)269	}270}271272func TestTeaKill(t *testing.T) {273	t.Parallel()274	var buf bytes.Buffer275	var in bytes.Buffer276277	m := &testModel{}278	p := NewProgram(m,279		WithInput(&in),280		WithOutput(&buf),281	)282	go func() {283		for {284			time.Sleep(time.Millisecond)285			if m.executed.Load() != nil {286				p.Kill()287				return288			}289		}290	}()291292	_, err := p.Run()293294	if !errors.Is(err, ErrProgramKilled) {295		t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)296	}297298	if errors.Is(err, context.Canceled) {299		// The end user should not know about the program's internal context state.300		// The program should only report external context cancellation as a context error.301		t.Fatalf("Internal context cancellation was reported as context error!")302	}303}304305func TestTeaContext(t *testing.T) {306	t.Parallel()307	ctx, cancel := context.WithCancel(t.Context())308	var buf bytes.Buffer309	var in bytes.Buffer310311	m := &testModel{}312	p := NewProgram(m,313		WithContext(ctx),314		WithInput(&in),315		WithOutput(&buf),316	)317	go func() {318		for {319			time.Sleep(time.Millisecond)320			if m.executed.Load() != nil {321				cancel()322				return323			}324		}325	}()326327	_, err := p.Run()328329	if !errors.Is(err, ErrProgramKilled) {330		t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)331	}332333	if !errors.Is(err, context.Canceled) {334		// The end user should know that their passed in context caused the kill.335		t.Fatalf("Expected %v, got %v", context.Canceled, err)336	}337}338339func TestTeaContextImplodeDeadlock(t *testing.T) {340	t.Parallel()341	ctx, cancel := context.WithCancel(t.Context())342	var buf bytes.Buffer343	var in bytes.Buffer344345	m := &testModel{}346	p := NewProgram(m,347		WithContext(ctx),348		WithInput(&in),349		WithOutput(&buf),350	)351	go func() {352		for {353			time.Sleep(time.Millisecond)354			if m.executed.Load() != nil {355				p.Send(ctxImplodeMsg{cancel: cancel})356				return357			}358		}359	}()360361	if _, err := p.Run(); !errors.Is(err, ErrProgramKilled) {362		t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)363	}364}365366func TestTeaContextBatchDeadlock(t *testing.T) {367	t.Parallel()368	ctx, cancel := context.WithCancel(t.Context())369	var buf bytes.Buffer370	var in bytes.Buffer371372	inc := func() Msg {373		cancel()374		return incrementMsg{}375	}376377	m := &testModel{}378	p := NewProgram(m,379		WithContext(ctx),380		WithInput(&in),381		WithOutput(&buf),382	)383	go func() {384		for {385			time.Sleep(time.Millisecond)386			if m.executed.Load() != nil {387				batch := make(BatchMsg, 100)388				for i := range batch {389					batch[i] = inc390				}391				p.Send(batch)392				return393			}394		}395	}()396397	if _, err := p.Run(); !errors.Is(err, ErrProgramKilled) {398		t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)399	}400}401402func TestTeaBatchMsg(t *testing.T) {403	t.Parallel()404	var buf bytes.Buffer405	var in bytes.Buffer406407	inc := func() Msg {408		return incrementMsg{}409	}410411	m := &testModel{}412	p := NewProgram(m,413		WithInput(&in),414		WithOutput(&buf),415	)416	go func() {417		p.Send(BatchMsg{inc, inc})418419		for {420			time.Sleep(time.Millisecond)421			i := m.counter.Load()422			if i != nil && i.(int) >= 2 {423				p.Quit()424				return425			}426		}427	}()428429	if _, err := p.Run(); err != nil {430		t.Fatal(err)431	}432433	if m.counter.Load() != 2 {434		t.Fatalf("counter should be 2, got %d", m.counter.Load())435	}436}437438func TestTeaSequenceMsg(t *testing.T) {439	t.Parallel()440	var buf bytes.Buffer441	var in bytes.Buffer442443	inc := func() Msg {444		return incrementMsg{}445	}446447	m := &testModel{}448	p := NewProgram(m,449		WithInput(&in),450		WithOutput(&buf),451	)452	go p.Send(sequenceMsg{inc, inc, Quit})453454	if _, err := p.Run(); err != nil {455		t.Fatal(err)456	}457458	if m.counter.Load() != 2 {459		t.Fatalf("counter should be 2, got %d", m.counter.Load())460	}461}462463func TestTeaSequenceMsgWithBatchMsg(t *testing.T) {464	t.Parallel()465	var buf bytes.Buffer466	var in bytes.Buffer467468	inc := func() Msg {469		return incrementMsg{}470	}471	batch := func() Msg {472		return BatchMsg{inc, inc}473	}474475	m := &testModel{}476	p := NewProgram(m,477		WithInput(&in),478		WithOutput(&buf),479	)480	go p.Send(sequenceMsg{batch, inc, Quit})481482	if _, err := p.Run(); err != nil {483		t.Fatal(err)484	}485486	if m.counter.Load() != 3 {487		t.Fatalf("counter should be 3, got %d", m.counter.Load())488	}489}490491func TestTeaNestedSequenceMsg(t *testing.T) {492	t.Parallel()493	var buf bytes.Buffer494	var in bytes.Buffer495496	inc := func() Msg {497		return incrementMsg{}498	}499500	m := &testModel{}501	p := NewProgram(m,502		WithInput(&in),503		WithOutput(&buf),504	)505	go p.Send(sequenceMsg{inc, Sequence(inc, inc, Batch(inc, inc)), Quit})506507	if _, err := p.Run(); err != nil {508		t.Fatal(err)509	}510511	if m.counter.Load() != 5 {512		t.Fatalf("counter should be 5, got %d", m.counter.Load())513	}514}515516func TestTeaSend(t *testing.T) {517	t.Parallel()518	var buf bytes.Buffer519	var in bytes.Buffer520521	m := &testModel{}522	p := NewProgram(m,523		WithInput(&in),524		WithOutput(&buf),525	)526527	// sending before the program is started is a blocking operation528	go p.Send(Quit())529530	if _, err := p.Run(); err != nil {531		t.Fatal(err)532	}533534	// sending a message after program has quit is a no-op535	p.Send(Quit())536}537538func TestTeaNoRun(t *testing.T) {539	t.Parallel()540	var buf bytes.Buffer541	var in bytes.Buffer542543	m := &testModel{}544	NewProgram(m,545		WithInput(&in),546		WithOutput(&buf),547	)548}549550func TestTeaPanic(t *testing.T) {551	t.Parallel()552	var buf bytes.Buffer553	var in bytes.Buffer554555	m := &testModel{}556	p := NewProgram(m,557		WithInput(&in),558		WithOutput(&buf),559	)560	go func() {561		for {562			time.Sleep(time.Millisecond)563			if m.executed.Load() != nil {564				p.Send(panicMsg{})565				return566			}567		}568	}()569570	_, err := p.Run()571572	if !errors.Is(err, ErrProgramPanic) {573		t.Fatalf("Expected %v, got %v", ErrProgramPanic, err)574	}575576	if !errors.Is(err, ErrProgramKilled) {577		t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)578	}579}580581func TestTeaGoroutinePanic(t *testing.T) {582	t.Parallel()583	var buf bytes.Buffer584	var in bytes.Buffer585586	m := &testModel{}587	p := NewProgram(m,588		WithInput(&in),589		WithOutput(&buf),590	)591	go func() {592		for {593			time.Sleep(time.Millisecond)594			if m.executed.Load() != nil {595				batch := make(BatchMsg, 10)596				for i := 0; i < len(batch); i += 2 {597					batch[i] = Sequence(panicCmd)598					batch[i+1] = Batch(panicCmd)599				}600				p.Send(batch)601				return602			}603		}604	}()605606	_, err := p.Run()607608	if !errors.Is(err, ErrProgramPanic) {609		t.Fatalf("Expected %v, got %v", ErrProgramPanic, err)610	}611612	if !errors.Is(err, ErrProgramKilled) {613		t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)614	}615}616617type benchModel struct {618	t testing.TB619}620621func (m benchModel) Init() Cmd {622	return nil623}624625func (m benchModel) Update(msg Msg) (Model, Cmd) {626	switch msg := msg.(type) {627	case KeyPressMsg:628		switch msg.String() {629		case "q", "ctrl+c":630			return m, Quit631		}632	}633634	return m, nil635}636637func (m benchModel) View() View {638	view := strings.Join([]string{639		" \x1b[38;5;63m╭─────────────────────────╮\x1b[m",640		" \x1b[38;5;63m│\x1b[m\x1b[25X\x1b[28G\x1b[38;5;63m│\x1b[m",641		" \x1b[38;5;63m│\x1b[m    \x1b[38;5;231mHello There!\x1b[m    \x1b[38;5;63m│\x1b[m",642		" \x1b[38;5;63m│\x1b[m\x1b[25X\x1b[28G\x1b[38;5;63m│\x1b[m",643		" \x1b[38;5;63m╰─────────────────────────╯\x1b[m",644	}, "\n")645646	return NewView(view)647}648649func BenchmarkTeaRun(b *testing.B) {650	for i := 0; i < b.N; i++ {651		var buf bytes.Buffer652653		m := benchModel{b}654		r, w := io.Pipe()655		p := NewProgram(m,656			WithInput(r),657			WithOutput(&buf),658		)659660		go func() {661			for _, input := range "abcdefghijklmnopq" {662				time.Sleep(10 * time.Millisecond)663				w.Write([]byte(string(input)))664			}665		}()666667		if _, err := p.Run(); err != nil {668			b.Fatalf("Run failed: %v", err)669		}670671		_ = r.CloseWithError(io.EOF)672	}673}674675// quitModel quits as soon as it starts.676type quitModel struct{}677678func (quitModel) Init() Cmd               { return Quit }679func (quitModel) Update(Msg) (Model, Cmd) { return quitModel{}, nil }680func (quitModel) View() View              { return NewView("") }681682// TestTeaNoCapabilityQueryWithoutInput is a regression test for683// https://github.com/charmbracelet/gum/issues/1118: programs without input684// can't read the terminal's responses to capability queries, so the replies685// leak into the shell after the program exits. Don't send the queries when686// input is disabled.687func TestTeaNoCapabilityQueryWithoutInput(t *testing.T) {688	t.Parallel()689690	query := ansi.RequestModeSynchronizedOutput + ansi.RequestModeUnicodeCore691	env := []string{"TERM=xterm-256color", "TERM_PROGRAM=ghostty"}692693	for _, tt := range []struct {694		name  string695		input io.Reader696		want  bool697	}{698		{name: "input disabled", input: nil, want: false},699		{name: "input enabled", input: bytes.NewReader(nil), want: true},700	} {701		t.Run(tt.name, func(t *testing.T) {702			t.Parallel()703704			var buf bytes.Buffer705			p := NewProgram(quitModel{},706				WithInput(tt.input),707				WithOutput(&buf),708				WithEnvironment(env),709			)710			if _, err := p.Run(); err != nil {711				t.Fatal(err)712			}713714			// The queued output may not have been flushed if the program715			// exited before the first tick, so inspect it too. Reading716			// p.outputBuf here is deliberate: it checks the buffered bytes717			// that would have been flushed, without depending on flush718			// timing (and it ties the test to the renderer's buffer, which719			// is an intentional trade-off).720			got := buf.String() + p.outputBuf.String()721			if strings.Contains(got, query) != tt.want {722				t.Fatalf("capability query present = %v, want %v; output: %q", !tt.want, tt.want, got)723			}724		})725	}726}727728// terminalQueryCmds lists every command that sends a terminal query whose729// reply must be read from the input reader.730var terminalQueryCmds = []Cmd{731	RequestBackgroundColor,732	RequestForegroundColor,733	RequestCursorColor,734	ReadClipboard,735	ReadPrimaryClipboard,736	RequestTerminalVersion,737	RequestCapability("TN"),738	RequestCursorPosition,739}740741// queryModel issues every terminal query that needs a reply on the input742// reader, then quits once each one has been handled.743type queryModel struct {744	handled int745}746747func (queryModel) Init() Cmd {748	return Batch(terminalQueryCmds...)749}750751func (m queryModel) Update(msg Msg) (Model, Cmd) {752	switch msg.(type) {753	case backgroundColorMsg, foregroundColorMsg, cursorColorMsg,754		readClipboardMsg, readPrimaryClipboardMsg, terminalVersion,755		requestCapabilityMsg, requestCursorPosMsg:756		// Each query is handled by an intermediate reader that turns the757		// terminal's reply into a message, so Update only sees the request758		// messages because the event loop passes them through after the759		// intermediate reads. If that pass-through ever changes, this test760		// will hang instead of quitting.761		m.handled++762		if m.handled == len(terminalQueryCmds) {763			return m, Quit764		}765	}766	return m, nil767}768769func (queryModel) View() View { return NewView("") }770771// TestTeaNoTerminalQueriesWithoutInput is a regression test for772// https://github.com/charmbracelet/gum/issues/1118: programs without input773// can't read the terminal's responses, so query replies leak into the shell774// after the program exits. No input-dependent query should be sent when input775// is disabled.776func TestTeaNoTerminalQueriesWithoutInput(t *testing.T) {777	t.Parallel()778779	queries := []string{780		ansi.RequestSystemClipboard,781		ansi.RequestPrimaryClipboard,782		ansi.RequestBackgroundColor,783		ansi.RequestForegroundColor,784		ansi.RequestCursorColor,785		ansi.RequestNameVersion,786		ansi.RequestTermcap("TN"),787		ansi.RequestCursorPositionReport,788	}789	env := []string{"TERM=xterm-256color", "TERM_PROGRAM=ghostty"}790791	for _, tt := range []struct {792		name  string793		input io.Reader794		want  bool795	}{796		{name: "input disabled", input: nil, want: false},797		{name: "input enabled", input: bytes.NewReader(nil), want: true},798	} {799		t.Run(tt.name, func(t *testing.T) {800			t.Parallel()801802			var buf bytes.Buffer803			p := NewProgram(queryModel{},804				WithInput(tt.input),805				WithOutput(&buf),806				WithEnvironment(env),807			)808			if _, err := p.Run(); err != nil {809				t.Fatal(err)810			}811812			// The queued output may not have been flushed if the program813			// exited before the first tick, so inspect it too. Reading814			// p.outputBuf here is deliberate: it checks the buffered bytes815			// that would have been flushed, without depending on flush816			// timing (and it ties the test to the renderer's buffer, which817			// is an intentional trade-off).818			got := buf.String() + p.outputBuf.String()819			for _, query := range queries {820				if strings.Contains(got, query) != tt.want {821					t.Errorf("query %q present = %v, want %v; output: %q", query, !tt.want, tt.want, got)822				}823			}824		})825	}826}827828// TestProgressBarStateStringOutOfRange is a regression test for829// https://github.com/charmbracelet/bubbletea/issues/1711: String panicked830// with an index-out-of-range error for any ProgressBarState outside the831// [ProgressBarNone, ProgressBarWarning] range. Since State is an exported832// field on ProgressBar, callers can assign such a value without going833// through NewProgressBar.834func TestProgressBarStateStringOutOfRange(t *testing.T) {835	for _, s := range []ProgressBarState{-1, 5, 100} {836		if got, want := s.String(), "Unknown"; got != want {837			t.Errorf("ProgressBarState(%d).String() = %q, want %q", int(s), got, want)838		}839	}840841	for s := ProgressBarNone; s <= ProgressBarWarning; s++ {842		if got := s.String(); got == "Unknown" {843			t.Errorf("ProgressBarState(%d).String() = %q, want a known name", int(s), got)844		}845	}846}