Skip to content

Commit ee0d696

Browse files
committed
add monitor test
1 parent 28da34d commit ee0d696

File tree

2 files changed

+81
-3
lines changed

2 files changed

+81
-3
lines changed

internal/monitor/monitor.go

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,22 @@ import (
2121
"log/slog"
2222
"net"
2323
"time"
24+
25+
"go.bug.st/f"
2426
)
2527

26-
const monitorAddr = "127.0.0.1:7500"
28+
const defaultArduinoRouterMonitorAddress = "127.0.0.1:7500"
29+
30+
func NewMonitorHandler(rw io.ReadWriteCloser, address ...string) (func(), error) {
31+
f.Assert(len(address) <= 1, "NewMonitorHandler accepts at most one address argument")
32+
33+
addr := defaultArduinoRouterMonitorAddress
34+
if len(address) == 1 {
35+
addr = address[0]
36+
}
2737

28-
func NewMonitorHandler(rw io.ReadWriteCloser) (func(), error) {
2938
// Connect to monitor
30-
monitor, err := net.DialTimeout("tcp", monitorAddr, time.Second)
39+
monitor, err := net.DialTimeout("tcp", addr, time.Second)
3140
if err != nil {
3241
return nil, err
3342
}

internal/monitor/monitor_test.go

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package monitor
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"net"
7+
"testing"
8+
9+
"github.com/arduino/arduino-app-cli/pkg/x/ports"
10+
"github.com/stretchr/testify/assert"
11+
)
12+
13+
func TestMonitorHandler(t *testing.T) {
14+
addr := startEcoMonitor(t)
15+
16+
t.Logf("Started echo monitor at %s", addr.String())
17+
18+
// Use pipes to simulate ReadWriteCloser
19+
rOut, wIn := io.Pipe()
20+
rIn, wOut := io.Pipe()
21+
type pipeReadWriteCloser struct {
22+
io.Reader
23+
io.Writer
24+
io.Closer
25+
}
26+
pr := &pipeReadWriteCloser{
27+
Reader: rOut,
28+
Writer: wOut,
29+
Closer: io.NopCloser(nil),
30+
}
31+
32+
handler, err := NewMonitorHandler(pr, addr.String())
33+
assert.NoError(t, err)
34+
go handler()
35+
36+
// Write data to the pipe writer
37+
message := "Hello, Monitor!"
38+
n, err := wIn.Write([]byte(message))
39+
assert.NoError(t, err)
40+
assert.Equal(t, len(message), n)
41+
42+
// Read data from the pipe reader
43+
buf := [128]byte{}
44+
n, err = rIn.Read(buf[:])
45+
assert.NoError(t, err)
46+
assert.Equal(t, len(message), n)
47+
assert.Equal(t, message, string(buf[:n]))
48+
}
49+
50+
func startEcoMonitor(t *testing.T) net.Addr {
51+
t.Helper()
52+
53+
port, err := ports.GetAvailable()
54+
assert.NoError(t, err)
55+
56+
ln, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
57+
assert.NoError(t, err)
58+
t.Cleanup(func() { _ = ln.Close() })
59+
60+
go func() {
61+
for {
62+
conn, err := ln.Accept()
63+
assert.NoError(t, err)
64+
go io.Copy(conn, conn) // Echo server
65+
}
66+
}()
67+
68+
return ln.Addr()
69+
}

0 commit comments

Comments
 (0)