Debian Codegraph @

huh_test.go

raw symbols SCIP
1 package huh
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "regexp"
10 "strings"
11 "testing"
12 "time"
13
14 tea "github.com/charmbracelet/bubbletea"
15 "github.com/charmbracelet/lipgloss"
16 "github.com/charmbracelet/x/ansi"
17 "github.com/charmbracelet/x/xpty"
18 )
19
20 var pretty = lipgloss.NewStyle().
21 Width(60).
22 Border(lipgloss.NormalBorder()).
23 MarginTop(1).
24 Padding(1, 3, 1, 2)
25
26 func TestForm(t *testing.T) {
27 type Taco struct {
28 Shell string
29 Base string
30 Toppings []string
31 }
32
33 type Order struct {
34 Taco Taco
35 Name string
36 Instructions string
37 Discount bool
38 }
39
40 var taco Taco
41 order := Order{Taco: taco}
42
43 f := NewForm(
44 NewGroup(
45 NewSelect[string]().
46 Options(NewOptions("Soft", "Hard")...).
47 Title("Shell?").
48 Description("Our tortillas are made fresh in-house every day.").
49 Validate(func(t string) error {
50 if t == "Hard" {
51 return fmt.Errorf("we're out of hard shells, sorry")
52 }
53 return nil
54 }).
55 Value(&order.Taco.Shell),
56
57 NewSelect[string]().
58 Options(NewOptions("Chicken", "Beef", "Fish", "Beans")...).
59 Value(&order.Taco.Base).
60 Title("Base"),
61 ),
62
63 // Prompt for toppings and special instructions.
64 // The customer can ask for up to 4 toppings.
65 NewGroup(
66 NewMultiSelect[string]().
67 Title("Toppings").
68 Description("Choose up to 4.").
69 Options(
70 NewOption("Lettuce", "lettuce").Selected(true),
71 NewOption("Tomatoes", "tomatoes").Selected(true),
72 NewOption("Corn", "corn"),
73 NewOption("Salsa", "salsa"),
74 NewOption("Sour Cream", "sour cream"),
75 NewOption("Cheese", "cheese"),
76 ).
77 Validate(func(t []string) error {
78 if len(t) <= 0 {
79 return fmt.Errorf("at least one topping is required")
80 }
81 return nil
82 }).
83 Value(&order.Taco.Toppings).
84 Filterable(true).
85 Limit(4),
86 ),
87
88 // Gather final details for the order.
89 NewGroup(
90 NewInput().
91 Value(&order.Name).
92 Title("What's your name?").
93 Placeholder("Margaret Thatcher").
94 Description("For when your order is ready."),
95
96 NewText().
97 Value(&order.Instructions).
98 Placeholder("Just put it in the mailbox please").
99 Title("Special Instructions").
100 Description("Anything we should know?").
101 CharLimit(400),
102
103 NewConfirm().
104 Title("Would you like 15% off?").
105 Value(&order.Discount).
106 Affirmative("Yes!").
107 Negative("No."),
108 ),
109 )
110
111 f.Update(f.Init())
112
113 view := ansi.Strip(f.View())
114
115 //
116 // ┃ Shell?
117 // ┃ Our tortillas are made fresh in-house every day.
118 // ┃ > Soft
119 // ┃ Hard
120 //
121 // Base
122 // > Chicken
123 // Beef
124 // Fish
125 // Beans
126 //
127 // ↑ up • ↓ down • / filter • enter select
128 //
129
130 if !strings.Contains(view, "┃ Shell?") {
131 t.Log(pretty.Render(view))
132 t.Error("Expected form to contain Shell? title")
133 }
134
135 if !strings.Contains(view, "Our tortillas are made fresh in-house every day.") {
136 t.Log(pretty.Render(view))
137 t.Error("Expected form to contain tortilla description")
138 }
139
140 if !strings.Contains(view, "Base") {
141 t.Log(pretty.Render(view))
142 t.Error("Expected form to contain Base title")
143 }
144
145 // Attempt to select hard shell and retrieve error.
146 m, _ := f.Update(keys('j'))
147 m, _ = m.Update(tea.KeyMsg{Type: tea.KeyTab})
148 view = ansi.Strip(m.View())
149
150 if !strings.Contains(view, "* we're out of hard shells, sorry") {
151 t.Log(pretty.Render(view))
152 t.Error("Expected form to show out of hard shells error")
153 }
154
155 m, _ = m.Update(keys('k'))
156
157 m, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
158 m = batchUpdate(m, cmd)
159
160 view = ansi.Strip(m.View())
161
162 if !strings.Contains(view, "┃ > Chicken") {
163 t.Log(pretty.Render(view))
164 t.Fatal("Expected form to continue to base group")
165 }
166
167 // batchMsg + nextGroup
168 m, cmd = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
169 m = batchUpdate(m, cmd)
170 view = ansi.Strip(m.View())
171
172 //
173 // ┃ Toppings
174 // ┃ Choose up to 4.
175 // ┃ > ✓ Lettuce
176 // ┃ ✓ Tomatoes
177 // ┃ • Corn
178 // ┃ • Salsa
179 // ┃ • Sour Cream
180 // ┃ • Cheese
181 //
182 // x toggle • ↑ up • ↓ down • enter confirm • shift+tab back
183 //
184 if !strings.Contains(view, "Toppings") {
185 t.Log(pretty.Render(view))
186 t.Fatal("Expected form to show toppings group")
187 }
188
189 if !strings.Contains(view, "Choose up to 4.") {
190 t.Log(pretty.Render(view))
191 t.Error("Expected form to show toppings description")
192 }
193
194 if !strings.Contains(view, "> ✓ Lettuce ") {
195 t.Log(pretty.Render(view))
196 t.Error("Expected form to preselect lettuce")
197 }
198
199 if !strings.Contains(view, " ✓ Tomatoes") {
200 t.Log(pretty.Render(view))
201 t.Error("Expected form to preselect tomatoes")
202 }
203
204 m, _ = m.Update(keys('j'))
205 m, _ = m.Update(keys('j'))
206 view = ansi.Strip(m.View())
207
208 if !strings.Contains(view, "> • Corn") {
209 t.Log(pretty.Render(view))
210 t.Error("Expected form to change selection to corn")
211 }
212
213 m, _ = m.Update(keys('x'))
214 view = ansi.Strip(m.View())
215
216 if !strings.Contains(view, "> ✓ Corn") {
217 t.Log(pretty.Render(view))
218 t.Error("Expected form to change selection to corn")
219 }
220
221 m = batchUpdate(m.Update(tea.KeyMsg{Type: tea.KeyEnter}))
222 view = ansi.Strip(m.View())
223
224 if !strings.Contains(view, "What's your name?") {
225 t.Log(pretty.Render(view))
226 t.Error("Expected form to prompt for name")
227 }
228
229 if !strings.Contains(view, "Special Instructions") {
230 t.Log(pretty.Render(view))
231 t.Error("Expected form to prompt for special instructions")
232 }
233
234 if !strings.Contains(view, "Would you like 15% off?") {
235 t.Log(pretty.Render(view))
236 t.Error("Expected form to prompt for discount")
237 }
238
239 //
240 // ┃ What's your name?
241 // ┃ For when your order is ready.
242 // ┃ > Margaret Thatcher
243 //
244 // Special Instructions
245 // Anything we should know?
246 // Just put it in the mailbox please
247 //
248 // Would you like 15% off?
249 //
250 // Yes! No.
251 //
252 // enter next • shift+tab back
253 //
254 m.Update(keys('G', 'l', 'e', 'n'))
255 view = ansi.Strip(m.View())
256 if !strings.Contains(view, "Glen") {
257 t.Log(pretty.Render(view))
258 t.Error("Expected form to accept user input")
259 }
260
261 if order.Taco.Shell != "Soft" {
262 t.Error("Expected order shell to be Soft")
263 }
264
265 if order.Taco.Base != "Chicken" {
266 t.Error("Expected order shell to be Chicken")
267 }
268
269 if len(order.Taco.Toppings) != 3 {
270 t.Error("Expected order to have 3 toppings")
271 }
272
273 if order.Name != "Glen" {
274 t.Error("Expected order name to be Glen")
275 }
276
277 // TODO: Finish and submit form.
278 }
279
280 func TestInput(t *testing.T) {
281 field := NewInput()
282 f := NewForm(NewGroup(field))
283 f.Update(f.Init())
284
285 view := ansi.Strip(f.View())
286
287 if !strings.Contains(view, ">") {
288 t.Log(pretty.Render(view))
289 t.Error("Expected field to contain prompt.")
290 }
291
292 // Type Huh in the form.
293 m, _ := f.Update(keys('H', 'u', 'h'))
294 f = m.(*Form)
295 view = ansi.Strip(f.View())
296
297 if !strings.Contains(view, "Huh") {
298 t.Log(pretty.Render(view))
299 t.Error("Expected field to contain Huh.")
300 }
301
302 if !strings.Contains(view, "enter submit") {
303 t.Log(pretty.Render(view))
304 t.Error("Expected field to contain help.")
305 }
306
307 if field.GetValue() != "Huh" {
308 t.Error("Expected field value to be Huh")
309 }
310 }
311
312 func TestInlineInput(t *testing.T) {
313 field := NewInput().
314 Title("Input ").
315 Prompt(": ").
316 Description("Description").
317 Inline(true)
318
319 f := NewForm(NewGroup(field)).WithWidth(40)
320 f.Update(f.Init())
321
322 view := ansi.Strip(f.View())
323
324 if !strings.Contains(view, "┃ Input Description:") {
325 t.Log(pretty.Render(view))
326 t.Error("Expected field to contain inline input.")
327 }
328
329 // Type Huh in the form.
330 m, _ := f.Update(keys('H', 'u', 'h'))
331 f = m.(*Form)
332 view = ansi.Strip(f.View())
333
334 if !strings.Contains(view, "Huh") {
335 t.Log(pretty.Render(view))
336 t.Error("Expected field to contain Huh.")
337 }
338
339 if !strings.Contains(view, "enter submit") {
340 t.Log(pretty.Render(view))
341 t.Error("Expected field to contain help.")
342 }
343
344 if !strings.Contains(view, "┃ Input Description: Huh") {
345 t.Log(pretty.Render(view))
346 t.Error("Expected field to contain help.")
347 }
348
349 if field.GetValue() != "Huh" {
350 t.Error("Expected field value to be Huh")
351 }
352 }
353
354 func TestText(t *testing.T) {
355 field := NewText()
356 f := NewForm(NewGroup(field))
357 f.Update(f.Init())
358
359 // Type Huh in the form.
360 m, _ := f.Update(keys('H', 'u', 'h'))
361 f = m.(*Form)
362 view := ansi.Strip(f.View())
363
364 if !strings.Contains(view, "Huh") {
365 t.Log(pretty.Render(view))
366 t.Error("Expected field to contain Huh.")
367 }
368
369 if !strings.Contains(view, "alt+enter / ctrl+j new line • ctrl+e open editor • enter submit") {
370 t.Log(pretty.Render(view))
371 t.Error("Expected field to contain help.")
372 }
373
374 if field.GetValue() != "Huh" {
375 t.Error("Expected field value to be Huh")
376 }
377 }
378
379 func TestTextExternalEditorHidden(t *testing.T) {
380 field := NewText().ExternalEditor(false)
381 f := NewForm(NewGroup(field))
382 f.Update(f.Init())
383
384 // Type Huh in the form.
385 m, _ := f.Update(keys('H', 'u', 'h'))
386 f = m.(*Form)
387 view := ansi.Strip(f.View())
388
389 if !strings.Contains(view, "Huh") {
390 t.Log(pretty.Render(view))
391 t.Error("Expected field to contain Huh.")
392 }
393
394 if strings.Contains(view, "ctrl+e open editor") {
395 t.Log(pretty.Render(view))
396 t.Error("Expected field to contain help without ctrl+e.")
397 }
398
399 if field.GetValue() != "Huh" {
400 t.Error("Expected field value to be Huh")
401 }
402 }
403
404 func TestConfirm(t *testing.T) {
405 field := NewConfirm().Title("Are you sure?")
406 f := NewForm(NewGroup(field))
407 f.Update(f.Init())
408
409 // Type Huh in the form.
410 m, _ := f.Update(keys('H'))
411 f = m.(*Form)
412 view := ansi.Strip(f.View())
413
414 if !strings.Contains(view, "Yes") {
415 t.Log(pretty.Render(view))
416 t.Error("Expected field to contain Yes.")
417 }
418
419 if !strings.Contains(view, "No") {
420 t.Log(pretty.Render(view))
421 t.Error("Expected field to contain No.")
422 }
423
424 if !strings.Contains(view, "Are you sure?") {
425 t.Log(pretty.Render(view))
426 t.Error("Expected field to contain Are you sure?.")
427 }
428
429 if !strings.Contains(view, "←/→ toggle • enter submit") {
430 t.Log(pretty.Render(view))
431 t.Error("Expected field to contain help.")
432 }
433
434 if field.GetValue() != false {
435 t.Error("Expected field value to be false")
436 }
437
438 // Toggle left
439 f.Update(tea.KeyMsg{Type: tea.KeyLeft})
440
441 if field.GetValue() != true {
442 t.Error("Expected field value to be true")
443 }
444
445 // Toggle right
446 f.Update(tea.KeyMsg{Type: tea.KeyRight})
447
448 if field.GetValue() != false {
449 t.Error("Expected field value to be false")
450 }
451 }
452
453 func TestSelect(t *testing.T) {
454 field := NewSelect[string]().
455 Options(NewOptions(
456 "Foo\nLine 2",
457 "Bar\nLine 2",
458 "Baz\nLine 2",
459 "Ban\nLine 2",
460 )...).
461 Title("Which one?")
462 f := NewForm(NewGroup(field)).WithHeight(5)
463 f.Update(f.Init())
464
465 view := ansi.Strip(f.View())
466
467 if !strings.Contains(view, "Foo") {
468 t.Log(pretty.Render(view))
469 t.Error("Expected field to contain Foo.")
470 }
471
472 if !strings.Contains(view, "Which one?") {
473 t.Log(pretty.Render(view))
474 t.Error("Expected field to contain Which one?.")
475 }
476
477 if !strings.Contains(view, "> Foo") {
478 t.Log(pretty.Render(view))
479 t.Error("Expected cursor to be on Foo.")
480 }
481
482 // Move selection cursor down
483 m, _ := f.Update(tea.KeyMsg{Type: tea.KeyDown})
484 f = m.(*Form)
485
486 view = ansi.Strip(f.View())
487
488 if got, ok := field.Hovered(); !ok || got != "Bar\nLine 2" {
489 t.Log(pretty.Render(view))
490 t.Error("Expected cursor to be on Bar.")
491 }
492
493 if strings.Contains(view, "> Foo") {
494 t.Log(pretty.Render(view))
495 t.Error("Expected cursor to be on Bar.")
496 }
497
498 if !strings.Contains(view, "> Bar") {
499 t.Log(pretty.Render(view))
500 t.Error("Expected cursor to be on Bar.")
501 }
502
503 if !strings.Contains(view, "↑ up • ↓ down • / filter • enter submit") {
504 t.Log(pretty.Render(view))
505 t.Error("Expected field to contain help.")
506 }
507
508 // Submit
509 f.Update(tea.KeyMsg{Type: tea.KeyEnter})
510
511 if field.GetValue() != "Bar\nLine 2" {
512 t.Error("Expected field value to be Bar")
513 }
514 }
515
516 // doAllUpdates updates the form with the given command, then continues updating it with any resultant commands from the update until no more are returned.
517 func doAllUpdates(f *Form, cmd tea.Cmd) {
518 if cmd == nil {
519 return
520 }
521 var cmds []tea.Cmd
522 switch msg := cmd().(type) {
523 case tea.BatchMsg:
524 for _, subcommand := range msg {
525 doAllUpdates(f, subcommand)
526 }
527 return
528 default:
529 _, result := f.Update(msg)
530 cmds = append(cmds, result)
531 }
532 doAllUpdates(f, tea.Batch(cmds...))
533 }
534
535 func TestSelectDynamic(t *testing.T) {
536 trigger := "initial"
537
538 field1 := NewSelect[string]().
539 TitleFunc(func() string {
540 return "field1 title " + trigger
541 }, &trigger).
542 DescriptionFunc(func() string {
543 return "field1 desc " + trigger
544 }, &trigger).
545 OptionsFunc(func() []Option[string] {
546 return []Option[string]{NewOption("field1 opt "+trigger, "field1 opt "+trigger)}
547 }, &trigger)
548 field2 := NewSelect[string]().
549 TitleFunc(func() string {
550 return "field2 title " + trigger
551 }, &trigger).
552 DescriptionFunc(func() string {
553 return "field2 desc " + trigger
554 }, &trigger).
555 OptionsFunc(func() []Option[string] {
556 return []Option[string]{NewOption("field2 opt "+trigger, "field2 opt "+trigger)}
557 }, &trigger)
558 field1.WithHeight(5)
559 field2.WithHeight(5)
560 f := NewForm(NewGroup(field1, field2)).WithHeight(10)
561
562 doAllUpdates(f, f.Init())
563
564 view := ansi.Strip(f.View())
565
566 expectedStrings := []string{
567 "field1 title initial",
568 "field1 desc initial",
569 "field1 opt initial",
570 "field2 title initial",
571 "field2 desc initial",
572 "field2 opt initial",
573 }
574 for _, expected := range expectedStrings {
575 if !strings.Contains(view, expected) {
576 t.Log(pretty.Render(view))
577 t.Error("Expected view to contain " + expected)
578 }
579 }
580
581 if field1.GetValue() != "field1 opt initial" {
582 t.Errorf("Expected field1 value to be field1 opt initial but was %s", field1.GetValue())
583 }
584 if field2.GetValue() != "field2 opt initial" {
585 t.Errorf("Expected field2 value to be field2 opt initial but was %s", field2.GetValue())
586 }
587
588 trigger = "updated"
589 _, cmd := f.Update(nil)
590 doAllUpdates(f, cmd)
591 view = ansi.Strip(f.View())
592
593 expectedStrings = []string{
594 "field1 title updated",
595 "field1 desc updated",
596 "field1 opt updated",
597 "field2 title updated",
598 "field2 desc updated",
599 "field2 opt updated",
600 }
601 for _, expected := range expectedStrings {
602 if !strings.Contains(view, expected) {
603 t.Log(pretty.Render(view))
604 t.Error("Expected view to contain " + expected)
605 }
606 }
607
608 if field1.GetValue() != "field1 opt updated" {
609 t.Errorf("Expected field1 value to be field1 opt updated but was %s", field1.GetValue())
610 }
611 if field2.GetValue() != "field2 opt updated" {
612 t.Errorf("Expected field2 value to be field2 opt updated but was %s", field1.GetValue())
613 }
614 }
615
616 func TestMultiSelect(t *testing.T) {
617 field := NewMultiSelect[string]().
618 Options(NewOptions(
619 "Foo\nLine2",
620 "Bar\nLine2",
621 "Baz\nLine2",
622 "Ban\nLine2",
623 )...).
624 Title("Which one?")
625 f := NewForm(NewGroup(field)).
626 WithHeight(5)
627 f.Update(f.Init())
628
629 view := ansi.Strip(f.View())
630
631 if !strings.Contains(view, "Foo") {
632 t.Log(pretty.Render(view))
633 t.Error("Expected field to contain Foo.")
634 }
635
636 if !strings.Contains(view, "Which one?") {
637 t.Log(pretty.Render(view))
638 t.Error("Expected field to contain Which one?.")
639 }
640
641 if !strings.Contains(view, "> • Foo") {
642 t.Log(pretty.Render(view))
643 t.Error("Expected cursor to be on Foo.")
644 }
645
646 // Move selection cursor down
647 m, _ := f.Update(keys('j'))
648 view = ansi.Strip(m.View())
649
650 if got, ok := field.Hovered(); !ok || got != "Bar\nLine2" {
651 t.Log(pretty.Render(view))
652 t.Error("Expected cursor to be on Bar.")
653 }
654
655 if strings.Contains(view, "> • Foo") {
656 t.Log(pretty.Render(view))
657 t.Error("Expected cursor to be on Bar.")
658 }
659
660 if !strings.Contains(view, "> • Bar") {
661 t.Log(pretty.Render(view))
662 t.Error("Expected cursor to be on Bar.")
663 }
664
665 // Toggle
666 m, _ = f.Update(keys('x'))
667 view = ansi.Strip(m.View())
668
669 if !strings.Contains(view, "> ✓ Bar") {
670 t.Log(pretty.Render(view))
671 t.Error("Expected cursor to be on Bar.")
672 }
673
674 if !strings.Contains(view, "x toggle • ↑ up • ↓ down • / filter • enter submit") {
675 t.Log(pretty.Render(view))
676 t.Error("Expected field to contain help.")
677 }
678
679 // Submit
680 f.Update(tea.KeyMsg{Type: tea.KeyEnter})
681
682 value := field.GetValue()
683 if value, ok := value.([]string); !ok {
684 t.Error("Expected field value to a slice of string")
685 } else {
686 if len(value) != 1 {
687 t.Error("Expected field value length to be 1")
688 } else {
689 if value[0] != "Bar\nLine2" {
690 t.Error("Expected first field value to be Bar")
691 }
692 }
693 }
694 }
695
696 func TestMultiSelectFiltering(t *testing.T) {
697 tests := []struct {
698 name string
699 filtering bool
700 }{
701 {"Filtering off", false},
702 {"Filtering on", true},
703 }
704
705 for _, tc := range tests {
706 t.Run(tc.name, func(t *testing.T) {
707 field := NewMultiSelect[string]().Options(NewOptions("Foo", "Bar", "Baz")...).Title("Which one?").Filterable(tc.filtering)
708 f := NewForm(NewGroup(field))
709 f.Update(f.Init())
710 // Filter for values starting with a 'B' only.
711 f.Update(keys('/'))
712 f.Update(keys('B'))
713
714 view := ansi.Strip(f.View())
715 // When we're filtering, the list should change.
716 if tc.filtering && strings.Contains(view, "Foo") {
717 t.Log(pretty.Render(view))
718 t.Error("Foo should not in filtered list.")
719 }
720 // When we're not filtering, the list shouldn't change.
721 if !tc.filtering && !strings.Contains(view, "Foo") {
722 t.Log(pretty.Render(view))
723 t.Error("Expected list to contain Foo.")
724 }
725 })
726 }
727 t.Run("Remove filter option from help menu.", func(t *testing.T) {
728 field := NewMultiSelect[string]().Options(NewOptions("Foo", "Bar", "Baz")...).Title("Which one?").Filterable(false)
729 f := NewForm(NewGroup(field))
730 f.Update(f.Init())
731 view := ansi.Strip(f.View())
732 if strings.Contains(view, "filter") {
733 t.Log(pretty.Render(view))
734 t.Error("Expected list to hide filtering in help menu.")
735 }
736 })
737 }
738
739 func TestSelectPageNavigation(t *testing.T) {
740 opts := NewOptions(
741 "Qux",
742 "Quux",
743 "Foo",
744 "Bar",
745 "Baz",
746 "Corge",
747 "Grault",
748 "Garply",
749 "Waldo",
750 "Fred",
751 "Plugh",
752 "Xyzzy",
753 "Thud",
754 "Norf",
755 "Blip",
756 "Flob",
757 "Zorp",
758 "Smurf",
759 "Bloop",
760 "Ping",
761 )
762
763 reFirst := regexp.MustCompile(`>( •)? Qux`)
764 reLast := regexp.MustCompile(`>( •)? Ping`)
765 reHalfDown := regexp.MustCompile(`>( •)? Baz`)
766
767 for name, field := range map[string]Field{
768 "multiselect": NewMultiSelect[string]().Options(opts...).Title("Choose"),
769 "select": NewSelect[string]().Options(opts...).Title("Choose"),
770 } {
771 t.Run(name, func(t *testing.T) {
772 f := NewForm(NewGroup(field)).WithHeight(10)
773 f.Update(f.Init())
774
775 view := ansi.Strip(f.View())
776 if !reFirst.MatchString(view) {
777 t.Log(pretty.Render(view))
778 t.Errorf("Wrong item selected, should have matched %q (first item)", reFirst.String())
779 }
780
781 m, _ := f.Update(keys('G'))
782 view = ansi.Strip(m.View())
783 if !reLast.MatchString(view) {
784 t.Log(pretty.Render(view))
785 t.Errorf("Wrong item selected, should have matched %q (last item)", reLast.String())
786 }
787
788 m, _ = f.Update(keys('g'))
789 view = ansi.Strip(m.View())
790 if !reFirst.MatchString(view) {
791 t.Log(pretty.Render(view))
792 t.Errorf("Wrong item selected, should have matched %q (first item)", reFirst.String())
793 }
794
795 m, _ = f.Update(tea.KeyMsg{Type: tea.KeyCtrlD})
796 view = ansi.Strip(m.View())
797 if !reHalfDown.MatchString(view) {
798 t.Log(pretty.Render(view))
799 t.Errorf("Wrong item selected, should have matched %q (half down item)", reHalfDown.String())
800 }
801
802 // sends multiple to verify it stays within boundaries
803 f.Update(tea.KeyMsg{Type: tea.KeyCtrlU})
804 f.Update(tea.KeyMsg{Type: tea.KeyCtrlU})
805 m, _ = f.Update(tea.KeyMsg{Type: tea.KeyCtrlU})
806 view = ansi.Strip(m.View())
807 if !reFirst.MatchString(view) {
808 t.Log(pretty.Render(view))
809 t.Errorf("Wrong item selected, should have matched %q (first item)", reFirst.String())
810 }
811
812 // verify it stays within boundaries
813 f.Update(tea.KeyMsg{Type: tea.KeyCtrlD})
814 f.Update(tea.KeyMsg{Type: tea.KeyCtrlD})
815 f.Update(tea.KeyMsg{Type: tea.KeyCtrlD})
816 f.Update(tea.KeyMsg{Type: tea.KeyCtrlD})
817 f.Update(tea.KeyMsg{Type: tea.KeyCtrlD})
818 m, _ = f.Update(tea.KeyMsg{Type: tea.KeyCtrlD})
819 view = ansi.Strip(m.View())
820 if !reLast.MatchString(view) {
821 t.Log(pretty.Render(view))
822 t.Errorf("Wrong item selected, should have matched %q (last item)", reLast.String())
823 }
824 })
825 }
826 }
827
828 func TestFile(t *testing.T) {
829 field := NewFilePicker().Title("Which file?")
830 cmd := field.Init()
831 field.Update(cmd())
832
833 view := ansi.Strip(field.View())
834
835 if !strings.Contains(view, "No file selected") {
836 t.Log(pretty.Render(view))
837 t.Error("Expected file picker to show no file selected.")
838 }
839
840 if !strings.Contains(view, "Which file?") {
841 t.Log(pretty.Render(view))
842 t.Error("Expected file picker to show title.")
843 }
844 }
845
846 func TestHideGroup(t *testing.T) {
847 f := NewForm(
848 NewGroup(NewNote().Description("Foo")).
849 WithHide(true),
850 NewGroup(NewNote().Description("Bar")),
851 NewGroup(NewNote().Description("Baz")),
852 NewGroup(NewNote().Description("Qux")).
853 WithHideFunc(func() bool { return false }).
854 WithHide(true),
855 )
856
857 f = batchUpdate(f, f.NextGroup()).(*Form)
858
859 if v := f.View(); !strings.Contains(v, "Bar") {
860 t.Log(pretty.Render(v))
861 t.Error("expected Bar to be visible")
862 }
863
864 // should have no effect as previous group is hidden
865 f.Update(prevGroup())
866
867 if v := f.View(); !strings.Contains(v, "Bar") {
868 t.Log(pretty.Render(v))
869 t.Error("expected Bar to be visible")
870 }
871
872 f.Update(nextGroup())
873
874 if v := f.View(); !strings.Contains(v, "Baz") {
875 t.Log(pretty.Render(v))
876 t.Error("expected Baz to be visible")
877 }
878
879 f.Update(nextGroup())
880
881 if v := f.View(); strings.Contains(v, "Qux") {
882 t.Log(pretty.Render(v))
883 t.Error("expected Qux to be hidden")
884 }
885
886 if v := f.State; v != StateCompleted {
887 t.Error("should have been completed")
888 }
889 }
890
891 func TestHideGroupLastAndFirstGroupsNotHidden(t *testing.T) {
892 f := NewForm(
893 NewGroup(NewNote().Description("Bar")),
894 NewGroup(NewNote().Description("Foo")).
895 WithHide(true),
896 NewGroup(NewNote().Description("Baz")),
897 )
898
899 f = batchUpdate(f, f.Init()).(*Form)
900
901 if v := ansi.Strip(f.View()); !strings.Contains(v, "Bar") {
902 t.Log(pretty.Render(v))
903 t.Error("expected Bar to not be hidden")
904 }
905
906 // should have no effect as there isn't any
907 f.Update(prevGroup())
908
909 if v := f.View(); !strings.Contains(v, "Bar") {
910 t.Log(pretty.Render(v))
911 t.Error("expected Bar to not be hidden")
912 }
913
914 f.Update(nextGroup())
915
916 if v := ansi.Strip(f.View()); !strings.Contains(v, "Baz") {
917 t.Log(pretty.Render(v))
918 t.Error("expected Baz to not be hidden")
919 }
920
921 // should submit the form
922 f.Update(nextGroup())
923 if v := f.State; v != StateCompleted {
924 t.Error("should have been completed")
925 }
926 }
927
928 func TestPrevGroup(t *testing.T) {
929 f := NewForm(
930 NewGroup(NewNote().Description("Bar")),
931 NewGroup(NewNote().Description("Foo")),
932 NewGroup(NewNote().Description("Baz")),
933 )
934
935 f = batchUpdate(f, f.Init()).(*Form)
936 f.Update(nextGroup())
937 f.Update(nextGroup())
938 f.Update(prevGroup())
939 f.Update(prevGroup())
940
941 if v := ansi.Strip(f.View()); !strings.Contains(v, "Bar") {
942 t.Log(pretty.Render(v))
943 t.Error("expected Bar to not be hidden")
944 }
945 }
946
947 func TestNote(t *testing.T) {
948 field := NewNote().
949 Title("Taco").
950 Description("How may we take your order?").
951 Next(true)
952 f := NewForm(NewGroup(field))
953 f.Update(f.Init())
954
955 view := ansi.Strip(f.View())
956
957 if !strings.Contains(view, "Taco") {
958 t.Log(view)
959 t.Error("Expected field to contain Taco title.")
960 }
961
962 if !strings.Contains(view, "order?") {
963 t.Log(view)
964 t.Error("Expected field to contain Taco description.")
965 }
966
967 if !strings.Contains(view, "Next") {
968 t.Log(view)
969 t.Error("Expected field to contain next button")
970 }
971
972 const expect = 7
973 if h := lipgloss.Height(ansi.Strip(view)); h != expect {
974 t.Log(view)
975 t.Errorf("Expected field to have height %d, got %d", expect, h)
976 }
977
978 if !strings.Contains(view, "enter submit") {
979 t.Log(view)
980 t.Error("Expected field to contain help.")
981 }
982 }
983
984 func TestDynamicHelp(t *testing.T) {
985 f := NewForm(
986 NewGroup(
987 NewInput().Title("Dynamic Help"),
988 NewInput().Title("Dynamic Help"),
989 NewInput().Title("Dynamic Help"),
990 ),
991 )
992 f.Update(f.Init())
993
994 view := ansi.Strip(f.View())
995
996 if !strings.Contains(view, "Dynamic Help") {
997 t.Log(pretty.Render(view))
998 t.Fatal("Expected help to contain title.")
999 }
1000
1001 if strings.Contains(view, "shift+tab") || strings.Contains(view, "submit") {
1002 t.Log(pretty.Render(view))
1003 t.Error("Expected help not to contain shift+tab or submit.")
1004 }
1005 }
1006
1007 func TestSkip(t *testing.T) {
1008 f := NewForm(
1009 NewGroup(
1010 NewInput().Title("First"),
1011 NewNote().Title("Skipped"),
1012 NewNote().Title("Skipped"),
1013 NewInput().Title("Second"),
1014 ),
1015 ).WithWidth(25)
1016
1017 f = batchUpdate(f, f.Init()).(*Form)
1018 view := ansi.Strip(f.View())
1019
1020 if !strings.Contains(view, "┃ First") {
1021 t.Log(pretty.Render(view))
1022 t.Error("Expected first field to be focused")
1023 }
1024
1025 // next field should skip both of the notes and proceed to the last input.
1026 f.Update(NextField())
1027 view = ansi.Strip(f.View())
1028
1029 if strings.Contains(view, "┃ First") {
1030 t.Log(pretty.Render(view))
1031 t.Error("Expected first field to be blurred")
1032 }
1033
1034 if !strings.Contains(view, "┃ Second") {
1035 t.Log(pretty.Render(view))
1036 t.Error("Expected second field to be focused")
1037 }
1038
1039 // previous field should skip both of the notes and focus the first input.
1040 f.Update(PrevField())
1041 view = ansi.Strip(f.View())
1042
1043 if strings.Contains(view, "┃ Second") {
1044 t.Log(pretty.Render(view))
1045 t.Error("Expected second field to be blurred")
1046 }
1047
1048 if !strings.Contains(view, "┃ First") {
1049 t.Log(pretty.Render(view))
1050 t.Error("Expected first field to be focused")
1051 }
1052 }
1053
1054 func TestTimeout(t *testing.T) {
1055 // This test requires a real program, so make sure it doesn't interfere with our test runner.
1056 f := formProgram()
1057
1058 // Test that the form times out after 1ms and returns a timeout error.
1059 err := f.WithTimeout(100 * time.Millisecond).Run()
1060 if err == nil || !errors.Is(err, ErrTimeout) {
1061 t.Errorf("expected timeout error, got %v", err)
1062 }
1063 }
1064
1065 func TestAbort(t *testing.T) {
1066 // This test requires a real program, so make sure it doesn't interfere with our test runner.
1067 f := formProgram()
1068
1069 // Test that the form aborts without throwing a timeout error when explicitly told to abort.
1070 ctx, cancel := context.WithCancel(context.Background())
1071 // Since the context is cancelled, the program should exit immediately.
1072 cancel()
1073 // Tell the form to abort.
1074 f.Update(tea.KeyMsg{Type: tea.KeyCtrlC})
1075 // Run the program.
1076 err := f.RunWithContext(ctx)
1077 if err == nil || !errors.Is(err, ErrUserAborted) {
1078 t.Errorf("expected user aborted error, got %v", err)
1079 }
1080 }
1081
1082 const (
1083 title = "A Title"
1084 description = "A Description"
1085 )
1086
1087 var titleAndDescTests = map[string]struct {
1088 Empty interface{ View() string }
1089 EmptyHeight int
1090 Title interface{ View() string }
1091 Description interface{ View() string }
1092 }{
1093 "Group": {
1094 NewGroup(NewInput()),
1095 1, // >
1096 NewGroup(NewInput()).Title(title),
1097 NewGroup(NewInput()).Description(description),
1098 },
1099 "Confirm": {
1100 NewConfirm(),
1101 1, // yes | no
1102 NewConfirm().Title(title),
1103 NewConfirm().Description(description),
1104 },
1105 "FilePicker": {
1106 NewFilePicker(),
1107 1, // "no file selected"
1108 NewFilePicker().Title(title),
1109 NewFilePicker().Description(description),
1110 },
1111 "Input": {
1112 NewInput(),
1113 1, // >
1114 NewInput().Title(title),
1115 NewInput().Description(description),
1116 },
1117 "Note": {
1118 NewNote(),
1119 1, // |
1120 NewNote().Title(title),
1121 NewNote().Description(description),
1122 },
1123 "Text": {
1124 NewText(),
1125 6, // textarea
1126 NewText().Title(title),
1127 NewText().Description(description),
1128 },
1129 "Select": {
1130 NewSelect[string](),
1131 1, // >
1132 NewSelect[string]().Title(title),
1133 NewSelect[string]().Description(description),
1134 },
1135 "MultiSelect": {
1136 NewMultiSelect[string](),
1137 1, // >
1138 NewMultiSelect[string]().Title(title),
1139 NewMultiSelect[string]().Description(description),
1140 },
1141 }
1142
1143 func TestNoTitleOrDescription(t *testing.T) {
1144 for name, tt := range titleAndDescTests {
1145 t.Run(name, func(t *testing.T) {
1146 view := tt.Empty.View()
1147 got := lipgloss.Height(ansi.Strip(view))
1148 want := tt.EmptyHeight
1149 if got != want {
1150 t.Log(pretty.Render(view))
1151 t.Fatalf("got != want; height should be %d, got %d", want, got)
1152 }
1153 })
1154 }
1155 }
1156
1157 func TestTitleRowRender(t *testing.T) {
1158 for name, tt := range titleAndDescTests {
1159 t.Run(name, func(t *testing.T) {
1160 view := tt.Title.View()
1161 if !strings.Contains(view, title) {
1162 t.Log(pretty.Render(view))
1163 t.Error("Expected title to be visible")
1164 }
1165 })
1166 }
1167 }
1168
1169 func TestDescriptionRowRender(t *testing.T) {
1170 for name, tt := range titleAndDescTests {
1171 t.Run(name, func(t *testing.T) {
1172 view := tt.Description.View()
1173 if !strings.Contains(view, description) {
1174 t.Log(pretty.Render(view))
1175 t.Error("Expected description to be visible")
1176 }
1177 })
1178 }
1179 }
1180
1181 func TestGetFocusedField(t *testing.T) {
1182 f := NewForm(
1183 NewGroup(
1184 NewInput().Title("First").Key("First"),
1185 NewInput().Title("Second").Key("Second"),
1186 NewInput().Title("Third").Key("Third"),
1187 ),
1188 ).WithWidth(25)
1189 f = batchUpdate(f, f.Init()).(*Form)
1190
1191 f.NextField()
1192 field := f.GetFocusedField()
1193
1194 if field.GetKey() != "Second" {
1195 t.Error("Expected Second field to be focused but was '" + field.GetKey() + "'")
1196 }
1197 }
1198
1199 // formProgram returns a new Form with a nil input and output, so it can be used as a test program.
1200 func formProgram() *Form {
1201 return NewForm(NewGroup(NewInput().Title("Foo"))).
1202 WithInput(nil).
1203 WithOutput(io.Discard).
1204 WithAccessible(false)
1205 }
1206
1207 func batchUpdate(m tea.Model, cmd tea.Cmd) tea.Model {
1208 if cmd == nil {
1209 return m
1210 }
1211 msg := cmd()
1212 m, cmd = m.Update(msg)
1213 if cmd == nil {
1214 return m
1215 }
1216 msg = cmd()
1217 m, _ = m.Update(msg)
1218 return m
1219 }
1220
1221 func keys(runes ...rune) tea.KeyMsg {
1222 return tea.KeyMsg{
1223 Type: tea.KeyRunes,
1224 Runes: runes,
1225 }
1226 }
1227
1228 func TestAccessibleForm(t *testing.T) {
1229 var out bytes.Buffer
1230
1231 f := NewForm(
1232 NewGroup(
1233 NewInput().Title("Hello:"),
1234 ),
1235 ).
1236 WithAccessible(true).
1237 WithOutput(&out).
1238 WithInput(strings.NewReader("carlos\n"))
1239
1240 if err := f.Run(); err != nil {
1241 t.Error(err)
1242 }
1243
1244 if !strings.Contains(out.String(), "Hello: ") {
1245 t.Error("invalid output:\n", out.String())
1246 }
1247 }
1248
1249 func TestAccessibleFields(t *testing.T) {
1250 for name, test := range map[string]struct {
1251 Field Field
1252 FieldFn func() Field
1253 Input string
1254 CheckOutput func(tb testing.TB, output string)
1255 CheckValue func(tb testing.TB, value any)
1256 }{
1257 "input": {
1258 Field: NewInput(),
1259 Input: "Hello",
1260 CheckOutput: func(tb testing.TB, output string) {
1261 tb.Helper()
1262 requireContains(tb, output, "Input: ")
1263 },
1264 CheckValue: func(tb testing.TB, value any) {
1265 tb.Helper()
1266 requireEqual(tb, "Hello", value.(string))
1267 },
1268 },
1269 "input with charlimit": {
1270 Field: NewInput().CharLimit(2),
1271 Input: "Hello",
1272 CheckOutput: func(tb testing.TB, output string) {
1273 tb.Helper()
1274 requireContains(tb, output, "Input cannot exceed 2 characters")
1275 },
1276 },
1277 "input with default": {
1278 FieldFn: func() Field {
1279 v := "hi"
1280 return NewInput().Value(&v)
1281 },
1282 Input: "\n",
1283 CheckOutput: func(tb testing.TB, output string) {
1284 tb.Helper()
1285 requireContains(tb, output, "Input: ")
1286 },
1287 CheckValue: func(tb testing.TB, value any) {
1288 tb.Helper()
1289 requireEqual(tb, "hi", value.(string))
1290 },
1291 },
1292 "confirm": {
1293 Field: NewConfirm(),
1294 Input: "Y",
1295 CheckOutput: func(tb testing.TB, output string) {
1296 tb.Helper()
1297 requireContains(tb, output, "Choose [y/N] ")
1298 },
1299 CheckValue: func(tb testing.TB, value any) {
1300 tb.Helper()
1301 requireEqual(tb, true, value.(bool))
1302 },
1303 },
1304 "confirm with default": {
1305 FieldFn: func() Field {
1306 v := true
1307 return NewConfirm().Value(&v)
1308 },
1309 CheckOutput: func(tb testing.TB, output string) {
1310 tb.Helper()
1311 requireContains(tb, output, "Choose [Y/n] ")
1312 },
1313 CheckValue: func(tb testing.TB, value any) {
1314 tb.Helper()
1315 requireEqual(tb, true, value.(bool))
1316 },
1317 },
1318 "confirm with default choose": {
1319 FieldFn: func() Field {
1320 v := true
1321 return NewConfirm().Value(&v)
1322 },
1323 Input: "n",
1324 CheckOutput: func(tb testing.TB, output string) {
1325 tb.Helper()
1326 requireContains(tb, output, "Y/n")
1327 },
1328 CheckValue: func(tb testing.TB, value any) {
1329 tb.Helper()
1330 requireEqual(tb, false, value.(bool))
1331 },
1332 },
1333 "filepicker": {
1334 Field: NewFilePicker(),
1335 Input: "huh_test.go",
1336 CheckOutput: func(tb testing.TB, output string) {
1337 tb.Helper()
1338 requireContains(tb, output, "Choose a file: ")
1339 },
1340 CheckValue: func(tb testing.TB, value any) {
1341 tb.Helper()
1342 requireEqual(tb, "huh_test.go", value.(string))
1343 },
1344 },
1345 "filepicker with default": {
1346 FieldFn: func() Field {
1347 v := "huh_test.go"
1348 return NewFilePicker().Value(&v)
1349 },
1350 Input: "\n",
1351 CheckOutput: func(tb testing.TB, output string) {
1352 tb.Helper()
1353 requireContains(tb, output, "Choose a file: ")
1354 },
1355 CheckValue: func(tb testing.TB, value any) {
1356 tb.Helper()
1357 requireEqual(tb, "huh_test.go", value.(string))
1358 },
1359 },
1360 "multiselect": {
1361 Field: NewMultiSelect[string]().Options(NewOptions("a", "b")...),
1362 Input: "2",
1363 CheckOutput: func(tb testing.TB, output string) {
1364 tb.Helper()
1365 requireContains(tb, output, "2. ✓ b")
1366 },
1367 CheckValue: func(tb testing.TB, value any) {
1368 tb.Helper()
1369 got := value.([]string)
1370 requireEqual(tb, 1, len(got))
1371 requireEqual(tb, "b", got[0])
1372 },
1373 },
1374 "multiselect default value": {
1375 FieldFn: func() Field {
1376 v := []string{"b", "c"}
1377 return NewMultiSelect[string]().Options(NewOptions("a", "b", "c", "d")...).Value(&v)
1378 },
1379 Input: "\n",
1380 CheckOutput: func(tb testing.TB, output string) {
1381 tb.Helper()
1382 requireContains(tb, output, "2. ✓ b")
1383 requireContains(tb, output, "3. ✓ c")
1384 },
1385 },
1386 "select": {
1387 Field: NewSelect[string]().Options(NewOptions("a", "b")...),
1388 Input: "2",
1389 CheckOutput: func(tb testing.TB, output string) {
1390 tb.Helper()
1391 requireContains(tb, output, "Select: ")
1392 },
1393 CheckValue: func(tb testing.TB, value any) {
1394 tb.Helper()
1395 requireEqual(tb, "b", value.(string))
1396 },
1397 },
1398 "select default value": {
1399 FieldFn: func() Field {
1400 v := "c"
1401 return NewSelect[string]().
1402 Options(NewOptions("a", "b", "c", "d")...).
1403 Value(&v)
1404 },
1405 Input: "\n",
1406 CheckOutput: func(tb testing.TB, output string) {
1407 tb.Helper()
1408 requireContains(tb, output, "Select: ")
1409 requireContains(tb, output, "Enter a number between 1 and 4")
1410 },
1411 CheckValue: func(tb testing.TB, value any) {
1412 tb.Helper()
1413 requireEqual(tb, "c", value.(string))
1414 },
1415 },
1416 "select no input": {
1417 Field: NewSelect[string]().Options(NewOptions("a", "b")...),
1418 Input: "\n2\n",
1419 CheckOutput: func(tb testing.TB, output string) {
1420 tb.Helper()
1421 requireContains(tb, output, "Select: ")
1422 requireContains(tb, output, "Enter a number between 1 and 2")
1423 requireContains(tb, output, "Invalid: must be a number between 1 and 2")
1424 },
1425 CheckValue: func(tb testing.TB, value any) {
1426 tb.Helper()
1427 requireEqual(tb, "b", value.(string))
1428 },
1429 },
1430 "select single option": {
1431 Field: NewSelect[string]().Options(NewOptions("a")...),
1432 Input: "\n1\n",
1433 CheckOutput: func(tb testing.TB, output string) {
1434 tb.Helper()
1435 requireContains(tb, output, "Select: ")
1436 requireContains(tb, output, "There is only one option available; enter the number 1:")
1437 requireContains(tb, output, "Invalid: must be 1")
1438 },
1439 CheckValue: func(tb testing.TB, value any) {
1440 tb.Helper()
1441 requireEqual(tb, "a", value.(string))
1442 },
1443 },
1444 "note": {
1445 Field: NewNote().Title("Hi").Description("there"),
1446 CheckOutput: func(tb testing.TB, output string) {
1447 tb.Helper()
1448 requireContains(tb, output, "Hi")
1449 requireContains(tb, output, "there")
1450 },
1451 },
1452 "text": {
1453 Field: NewText().Title("Text: "),
1454 Input: "hello world",
1455 CheckOutput: func(tb testing.TB, output string) {
1456 tb.Helper()
1457 requireContains(tb, output, "Text: ")
1458 },
1459 CheckValue: func(tb testing.TB, value any) {
1460 tb.Helper()
1461 requireEqual(tb, "hello world", value.(string))
1462 },
1463 },
1464 "text with limit": {
1465 Field: NewText().CharLimit(2).Title("Text"),
1466 Input: "hello world",
1467 CheckOutput: func(tb testing.TB, output string) {
1468 tb.Helper()
1469 requireContains(tb, output, "Input cannot exceed 2 characters")
1470 },
1471 },
1472 "text default value": {
1473 FieldFn: func() Field {
1474 v := "test"
1475 return NewText().Title("Text:").Value(&v)
1476 },
1477 Input: "\n",
1478 CheckOutput: func(tb testing.TB, output string) {
1479 tb.Helper()
1480 requireContains(tb, output, "Text: ")
1481 },
1482 CheckValue: func(tb testing.TB, value any) {
1483 tb.Helper()
1484 requireEqual(tb, "test", value.(string))
1485 },
1486 },
1487 } {
1488 t.Run(name, func(t *testing.T) {
1489 field := test.Field
1490 if test.FieldFn != nil {
1491 field = test.FieldFn()
1492 }
1493
1494 var out bytes.Buffer
1495 if err := field.RunAccessible(
1496 &out,
1497 strings.NewReader(test.Input),
1498 ); err != nil {
1499 t.Error(err)
1500 }
1501 if test.CheckOutput != nil {
1502 test.CheckOutput(t, out.String())
1503 }
1504 if test.CheckValue != nil {
1505 test.CheckValue(t, field.GetValue())
1506 }
1507 })
1508 }
1509 }
1510
1511 func TestInputPasswordAccessible(t *testing.T) {
1512 t.Run("not a tty", func(t *testing.T) {
1513 var out bytes.Buffer
1514 if err := NewInput().
1515 EchoMode(EchoModeNone).
1516 RunAccessible(&out, bytes.NewReader(nil)); err == nil {
1517 t.Error("expected it to error")
1518 }
1519 if err := NewInput().
1520 EchoMode(EchoModePassword).
1521 RunAccessible(&out, bytes.NewReader(nil)); err == nil {
1522 t.Error("expected it to error")
1523 }
1524 })
1525
1526 t.Run("is a tty", func(t *testing.T) {
1527 var out bytes.Buffer
1528 pty, err := xpty.NewPty(50, 30)
1529 if err != nil {
1530 t.Skipf("could not open pty: %v", err)
1531 }
1532 upty, ok := pty.(*xpty.UnixPty)
1533 if !ok {
1534 t.Skipf("test only works on unix")
1535 }
1536
1537 input := NewInput().EchoMode(EchoModePassword)
1538
1539 errs := make(chan error, 1)
1540 go func() {
1541 errs <- input.RunAccessible(&out, upty.Slave())
1542 }()
1543
1544 upty.Master().Write([]byte("a password\n"))
1545
1546 if err := <-errs; err != nil {
1547 t.Errorf("expected no error, got %v", err)
1548 }
1549
1550 requireContains(t, out.String(), "Password: ")
1551 requireEqual(t, "a password", input.GetValue().(string))
1552 })
1553 }
1554
1555 func requireEqual[T comparable](tb testing.TB, a, b T) {
1556 tb.Helper()
1557 if a != b {
1558 tb.Fatalf("expected %v to be equal to %v", a, b)
1559 }
1560 }
1561
1562 func requireContains(tb testing.TB, s, subtr string) {
1563 tb.Helper()
1564 if !strings.Contains(s, subtr) {
1565 tb.Fatalf("%q does not contain %q", s, subtr)
1566 }
1567 }