forked from Code-Hex/vz
-
Notifications
You must be signed in to change notification settings - Fork 1
/
socket_test.go
74 lines (60 loc) · 1.5 KB
/
socket_test.go
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
package vz_test
import (
"bytes"
"fmt"
"io"
"testing"
"time"
"github.com/Code-Hex/vz/v3"
)
func TestVirtioSocketListener(t *testing.T) {
container := newVirtualizationMachine(t)
defer container.Close()
vm := container.VirtualMachine
socketDevice := vm.SocketDevices()[0] // already tested in newVirtualizationMachine
port := 43218
wantData := "hello"
done := make(chan struct{})
listener, err := socketDevice.Listen(uint32(port))
if err != nil {
t.Fatal(err)
}
defer listener.Close()
go func() {
defer close(done)
conn, err := listener.Accept()
if err != nil {
t.Errorf("failed to accept connection: %v", err)
return
}
defer conn.Close()
destPort := conn.(*vz.VirtioSocketConnection).DestinationPort()
if port != int(destPort) {
t.Errorf("want destination port %d but got %d", destPort, port)
return
}
buf := make([]byte, len(wantData))
n, err := conn.Read(buf)
if err != nil && err != io.EOF {
t.Errorf("failed to read data: %v", err)
return
}
got := string(buf[:n])
if wantData != got {
t.Errorf("want %q but got %q", wantData, got)
}
}()
session := container.NewSession(t)
var buf bytes.Buffer
session.Stderr = &buf
cmd := fmt.Sprintf("echo %s | socat - VSOCK-CONNECT:2:%d", wantData, port)
if err := session.Run(cmd); err != nil {
t.Fatalf("failed to write data to vsock: %v\nstderr: %q", err, buf)
}
session.Close()
select {
case <-done:
case <-time.After(3 * time.Second):
t.Fatalf("timeout connection handling after accepted")
}
}