Debian Codegraph @

exp/teatest/v2/send_test.go

raw
1 package teatest_test
2
3 import (
4 "fmt"
5 "strings"
6 "testing"
7 "time"
8
9 tea "github.com/charmbracelet/bubbletea/v2"
10 "github.com/charmbracelet/x/exp/teatest/v2"
11 )
12
13 func TestAppSendToOtherProgram(t *testing.T) {
14 m1 := &connectedModel{
15 name: "m1",
16 }
17 m2 := &connectedModel{
18 name: "m2",
19 }
20
21 tm1 := teatest.NewTestModel(t, m1, teatest.WithInitialTermSize(70, 30))
22 t.Cleanup(func() {
23 if err := tm1.Quit(); err != nil {
24 t.Fatal(err)
25 }
26 })
27 tm2 := teatest.NewTestModel(t, m2, teatest.WithInitialTermSize(70, 30))
28 t.Cleanup(func() {
29 if err := tm2.Quit(); err != nil {
30 t.Fatal(err)
31 }
32 })
33 m1.programs = append(m1.programs, tm2)
34 m2.programs = append(m2.programs, tm1)
35
36 tm1.Type("pp")
37 tm2.Type("pppp")
38
39 tm1.Type("q")
40 tm2.Type("q")
41
42 out1 := readBts(t, tm1.FinalOutput(t, teatest.WithFinalTimeout(time.Second)))
43 out2 := readBts(t, tm2.FinalOutput(t, teatest.WithFinalTimeout(time.Second)))
44
45 if string(out1) != string(out2) {
46 t.Errorf("output of both models should be the same, got:\n%v\nand:\n%v\n", string(out1), string(out2))
47 }
48
49 teatest.RequireEqualOutput(t, out1)
50 }
51
52 type connectedModel struct {
53 name string
54 programs []interface{ Send(tea.Msg) }
55 msgs []string
56 }
57
58 type ping string
59
60 func (m *connectedModel) Init() tea.Cmd {
61 return nil
62 }
63
64 func (m *connectedModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
65 switch msg := msg.(type) {
66 case tea.KeyMsg:
67 switch msg.String() {
68 case "p":
69 send := ping("from " + m.name)
70 m.msgs = append(m.msgs, string(send))
71 for _, p := range m.programs {
72 p.Send(send)
73 }
74 fmt.Printf("sent ping %q to others\n", send)
75 case "q":
76 return m, tea.Quit
77 }
78 case ping:
79 fmt.Printf("rcvd ping %q on %s\n", msg, m.name)
80 m.msgs = append(m.msgs, string(msg))
81 }
82 return m, nil
83 }
84
85 func (m *connectedModel) View() string {
86 return "All pings:\n" + strings.Join(m.msgs, "\n")
87 }