Debian Codegraph @

exp/teatest/v2/teatest.go

raw
1 // Package teatest provides helper functions to test tea.Model's.
2 package teatest
3
4 import (
5 "bytes"
6 "fmt"
7 "io"
8 "os"
9 "os/signal"
10 "sync"
11 "syscall"
12 "testing"
13 "time"
14
15 tea "github.com/charmbracelet/bubbletea/v2"
16 "github.com/charmbracelet/x/exp/golden"
17 )
18
19 // Program defines the subset of the tea.Program API we need for testing.
20 type Program interface {
21 Send(tea.Msg)
22 }
23
24 // TestModelOptions defines all options available to the test function.
25 type TestModelOptions struct {
26 size tea.WindowSizeMsg
27 programOpts []tea.ProgramOption
28 }
29
30 // TestOption is a functional option.
31 type TestOption func(opts *TestModelOptions)
32
33 // WithInitialTermSize ...
34 func WithInitialTermSize(x, y int) TestOption {
35 return func(opts *TestModelOptions) {
36 opts.size = tea.WindowSizeMsg{
37 Width: x,
38 Height: y,
39 }
40 }
41 }
42
43 // WithProgramOptions adds tea.ProgramOptions to the test model during initialization
44 // of the program.
45 func WithProgramOptions(options ...tea.ProgramOption) TestOption {
46 return func(opts *TestModelOptions) {
47 opts.programOpts = options
48 }
49 }
50
51 // WaitingForContext is the context for a WaitFor.
52 type WaitingForContext struct {
53 Duration time.Duration
54 CheckInterval time.Duration
55 }
56
57 // WaitForOption changes how a WaitFor will behave.
58 type WaitForOption func(*WaitingForContext)
59
60 // WithCheckInterval sets how much time a WaitFor should sleep between every
61 // check.
62 func WithCheckInterval(d time.Duration) WaitForOption {
63 return func(wf *WaitingForContext) {
64 wf.CheckInterval = d
65 }
66 }
67
68 // WithDuration sets how much time a WaitFor will wait for the condition.
69 func WithDuration(d time.Duration) WaitForOption {
70 return func(wf *WaitingForContext) {
71 wf.Duration = d
72 }
73 }
74
75 // WaitFor keeps reading from r until the condition matches.
76 // Default duration is 1s, default check interval is 50ms.
77 // These defaults can be changed with WithDuration and WithCheckInterval.
78 func WaitFor(
79 tb testing.TB,
80 r io.Reader,
81 condition func(bts []byte) bool,
82 options ...WaitForOption,
83 ) {
84 tb.Helper()
85 if err := doWaitFor(r, condition, options...); err != nil {
86 tb.Fatal(err)
87 }
88 }
89
90 func doWaitFor(r io.Reader, condition func(bts []byte) bool, options ...WaitForOption) error {
91 wf := WaitingForContext{
92 Duration: time.Second,
93 CheckInterval: 50 * time.Millisecond, //nolint: gomnd
94 }
95
96 for _, opt := range options {
97 opt(&wf)
98 }
99
100 var b bytes.Buffer
101 start := time.Now()
102 for time.Since(start) <= wf.Duration {
103 if _, err := io.ReadAll(io.TeeReader(r, &b)); err != nil {
104 return fmt.Errorf("WaitFor: %w", err)
105 }
106 if condition(b.Bytes()) {
107 return nil
108 }
109 time.Sleep(wf.CheckInterval)
110 }
111 return fmt.Errorf("WaitFor: condition not met after %s. Last output:\n%s", wf.Duration, b.String())
112 }
113
114 // TestModel is a model that is being tested.
115 type TestModel struct {
116 program *tea.Program
117
118 in *bytes.Buffer
119 out io.ReadWriter
120
121 modelCh chan tea.Model
122 model tea.Model
123
124 done sync.Once
125 doneCh chan bool
126 }
127
128 // NewTestModel makes a new TestModel which can be used for tests.
129 func NewTestModel(tb testing.TB, m tea.Model, options ...TestOption) *TestModel {
130 tm := &TestModel{
131 in: bytes.NewBuffer(nil),
132 out: safe(bytes.NewBuffer(nil)),
133 modelCh: make(chan tea.Model, 1),
134 doneCh: make(chan bool, 1),
135 }
136
137 // We always have an initial size.
138 options = append([]TestOption{
139 WithInitialTermSize(80, 24),
140 }, options...)
141
142 var opts TestModelOptions
143 for _, opt := range options {
144 opt(&opts)
145 }
146 programOpts := append(
147 opts.programOpts,
148 // Append our options to ensure they always override.
149 tea.WithInput(tm.in),
150 tea.WithOutput(tm.out),
151 tea.WithoutSignals(),
152 tea.WithWindowSize(opts.size.Width, opts.size.Height),
153 )
154
155 tm.program = tea.NewProgram(m, programOpts...)
156
157 interruptions := make(chan os.Signal, 1)
158 signal.Notify(interruptions, syscall.SIGINT)
159 go func() {
160 m, err := tm.program.Run()
161 if err != nil {
162 tb.Fatalf("app failed: %s", err)
163 }
164 tm.modelCh <- m
165 tm.doneCh <- true
166 }()
167 go func() {
168 <-interruptions
169 signal.Stop(interruptions)
170 tb.Log("interrupted")
171 tm.program.Kill()
172 }()
173
174 if opts.size.Width != 0 {
175 tm.program.Send(opts.size)
176 }
177 return tm
178 }
179
180 func (tm *TestModel) waitDone(tb testing.TB, opts []FinalOpt) {
181 tm.done.Do(func() {
182 fopts := FinalOpts{}
183 for _, opt := range opts {
184 opt(&fopts)
185 }
186 if fopts.timeout > 0 {
187 select {
188 case <-time.After(fopts.timeout):
189 if fopts.onTimeout == nil {
190 tb.Fatalf("timeout after %s", fopts.timeout)
191 }
192 fopts.onTimeout(tb)
193 case <-tm.doneCh:
194 }
195 } else {
196 <-tm.doneCh
197 }
198 })
199 }
200
201 // FinalOpts represents the options for FinalModel and FinalOutput.
202 type FinalOpts struct {
203 timeout time.Duration
204 onTimeout func(tb testing.TB)
205 }
206
207 // FinalOpt changes FinalOpts.
208 type FinalOpt func(opts *FinalOpts)
209
210 // WithTimeoutFn allows to define what happens when WaitFinished times out.
211 func WithTimeoutFn(fn func(tb testing.TB)) FinalOpt {
212 return func(opts *FinalOpts) {
213 opts.onTimeout = fn
214 }
215 }
216
217 // WithFinalTimeout allows to set a timeout for how long FinalModel and
218 // FinalOuput should wait for the program to complete.
219 func WithFinalTimeout(d time.Duration) FinalOpt {
220 return func(opts *FinalOpts) {
221 opts.timeout = d
222 }
223 }
224
225 // WaitFinished waits for the app to finish.
226 // This method only returns once the program has finished running or when it
227 // times out.
228 func (tm *TestModel) WaitFinished(tb testing.TB, opts ...FinalOpt) {
229 tm.waitDone(tb, opts)
230 }
231
232 // FinalModel returns the resulting model, resulting from program.Run().
233 // This method only returns once the program has finished running or when it
234 // times out.
235 func (tm *TestModel) FinalModel(tb testing.TB, opts ...FinalOpt) tea.Model {
236 tm.waitDone(tb, opts)
237 select {
238 case m := <-tm.modelCh:
239 tm.model = m
240 return tm.model
241 default:
242 return tm.model
243 }
244 }
245
246 // FinalOutput returns the program's final output io.Reader.
247 // This method only returns once the program has finished running or when it
248 // times out.
249 func (tm *TestModel) FinalOutput(tb testing.TB, opts ...FinalOpt) io.Reader {
250 tm.waitDone(tb, opts)
251 return tm.Output()
252 }
253
254 // Output returns the program's current output io.Reader.
255 func (tm *TestModel) Output() io.Reader {
256 return tm.out
257 }
258
259 // Send sends messages to the underlying program.
260 func (tm *TestModel) Send(m tea.Msg) {
261 tm.program.Send(m)
262 }
263
264 // Quit quits the program and releases the terminal.
265 func (tm *TestModel) Quit() error {
266 tm.program.Quit()
267 return nil
268 }
269
270 // Type types the given text into the given program.
271 func (tm *TestModel) Type(s string) {
272 for _, c := range s {
273 tm.Send(tea.KeyPressMsg{
274 Code: c,
275 Text: string(c),
276 })
277 }
278 }
279
280 // GetProgram gets the TestModel's program.
281 func (tm *TestModel) GetProgram() *tea.Program {
282 return tm.program
283 }
284
285 // RequireEqualOutput is a helper function to assert the given output is
286 // the expected from the golden files, printing its diff in case it is not.
287 //
288 // Important: this uses the system `diff` tool.
289 //
290 // You can update the golden files by running your tests with the -update flag.
291 func RequireEqualOutput(tb testing.TB, out []byte) {
292 tb.Helper()
293 golden.RequireEqualEscape(tb, out, true) //nolint:staticcheck
294 }
295
296 func safe(rw io.ReadWriter) io.ReadWriter {
297 return &safeReadWriter{rw: rw}
298 }
299
300 // safeReadWriter implements io.ReadWriter, but locks reads and writes.
301 type safeReadWriter struct {
302 rw io.ReadWriter
303 m sync.RWMutex
304 }
305
306 // Read implements io.ReadWriter.
307 func (s *safeReadWriter) Read(p []byte) (n int, err error) {
308 s.m.RLock()
309 defer s.m.RUnlock()
310 return s.rw.Read(p) //nolint: wrapcheck
311 }
312
313 // Write implements io.ReadWriter.
314 func (s *safeReadWriter) Write(p []byte) (int, error) {
315 s.m.Lock()
316 defer s.m.Unlock()
317 return s.rw.Write(p) //nolint: wrapcheck
318 }