Debian Codegraph @

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