File: send_test.go

package info (click to toggle)
golang-github-charmbracelet-x 0.0~git20240809.9ab0ca0%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,004 kB
  • sloc: sh: 55; makefile: 5
file content (87 lines) | stat: -rw-r--r-- 1,850 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package teatest_test

import (
	"fmt"
	"strings"
	"testing"
	"time"

	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/x/exp/teatest"
)

func TestAppSendToOtherProgram(t *testing.T) {
	m1 := &connectedModel{
		name: "m1",
	}
	m2 := &connectedModel{
		name: "m2",
	}

	tm1 := teatest.NewTestModel(t, m1, teatest.WithInitialTermSize(70, 30))
	t.Cleanup(func() {
		if err := tm1.Quit(); err != nil {
			t.Fatal(err)
		}
	})
	tm2 := teatest.NewTestModel(t, m2, teatest.WithInitialTermSize(70, 30))
	t.Cleanup(func() {
		if err := tm2.Quit(); err != nil {
			t.Fatal(err)
		}
	})
	m1.programs = append(m1.programs, tm2)
	m2.programs = append(m2.programs, tm1)

	tm1.Type("pp")
	tm2.Type("pppp")

	tm1.Type("q")
	tm2.Type("q")

	out1 := readBts(t, tm1.FinalOutput(t, teatest.WithFinalTimeout(time.Second)))
	out2 := readBts(t, tm2.FinalOutput(t, teatest.WithFinalTimeout(time.Second)))

	if string(out1) != string(out2) {
		t.Errorf("output of both models should be the same, got:\n%v\nand:\n%v\n", string(out1), string(out2))
	}

	teatest.RequireEqualOutput(t, out1)
}

type connectedModel struct {
	name     string
	programs []interface{ Send(tea.Msg) }
	msgs     []string
}

type ping string

func (m *connectedModel) Init() tea.Cmd {
	return nil
}

func (m *connectedModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case tea.KeyMsg:
		switch msg.String() {
		case "p":
			send := ping("from " + m.name)
			m.msgs = append(m.msgs, string(send))
			for _, p := range m.programs {
				p.Send(send)
			}
			fmt.Printf("sent ping %q to others\n", send)
		case "q":
			return m, tea.Quit
		}
	case ping:
		fmt.Printf("rcvd ping %q on %s\n", msg, m.name)
		m.msgs = append(m.msgs, string(msg))
	}
	return m, nil
}

func (m *connectedModel) View() string {
	return "All pings:\n" + strings.Join(m.msgs, "\n")
}