]> git.giacomolli.uk - onechat/blob - terminal_client_helper_test.go
Record the subagent name in the usage records
[onechat] / terminal_client_helper_test.go
1 package main
2
3 import (
4 "io"
5 "net"
6 "strings"
7 "testing"
8 "time"
9
10 "github.com/stretchr/testify/require"
11 )
12
13 // TerminalTestClient is a terminal client of a test daemon, with a pipe as its
14 // input.
15 type TerminalTestClient struct {
16 input *io.PipeWriter
17 done chan error
18 out *SyncBuffer
19 }
20
21 // Type writes one line to the input of the client.
22 func (c *TerminalTestClient) Type(line string) {
23 _, err := io.WriteString(c.input, line+"\n")
24 if err != nil {
25 panic(err)
26 }
27 }
28
29 // Output returns what the client showed.
30 func (c *TerminalTestClient) Output() string {
31 return c.out.String()
32 }
33
34 // WaitFor waits until the client showed text.
35 func (c *TerminalTestClient) WaitFor(t *testing.T, text string) {
36 t.Helper()
37
38 require.Eventually(t, func() bool {
39 return strings.Contains(c.Output(), text)
40 }, 10*time.Second, time.Millisecond, "output so far: %q", c.Output())
41 }
42
43 // Close ends the input and waits for the client.
44 func (c *TerminalTestClient) Close() error {
45 err := c.input.Close()
46 if err != nil {
47 return err
48 }
49
50 return <-c.done
51 }
52
53 // terminalStartTestClient connects a client to the daemon at socket.
54 func terminalStartTestClient(t *testing.T, socket string) *TerminalTestClient {
55 t.Helper()
56
57 conn, err := net.Dial("unix", socket)
58 require.NoError(t, err)
59
60 reader, writer := io.Pipe()
61 client := &TerminalTestClient{
62 input: writer,
63 done: make(chan error, 1),
64 out: &SyncBuffer{},
65 }
66
67 go func() {
68 client.done <- terminalSession(t.Context(), conn, reader, client.out)
69 }()
70
71 t.Cleanup(func() {
72 _ = writer.Close()
73 })
74
75 return client
76 }