| 1 | package notification |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "net" |
| 7 | "path/filepath" |
| 8 | "testing" |
| 9 | "time" |
| 10 | |
| 11 | "github.com/containers/gvisor-tap-vsock/pkg/types" |
| 12 | "github.com/stretchr/testify/assert" |
| 13 | ) |
| 14 | |
| 15 | func TestNewNotificationSender_EmptySocket(t *testing.T) { |
| 16 | sender := NewNotificationSender("") |
| 17 | assert.Nil(t, sender.notificationCh) |
| 18 | assert.Empty(t, sender.socket) |
| 19 | } |
| 20 | |
| 21 | func TestNewNotificationSender_NonEmptySocket(t *testing.T) { |
| 22 | sender := NewNotificationSender("test.sock") |
| 23 | assert.NotNil(t, sender) |
| 24 | assert.Equal(t, "test.sock", sender.socket) |
| 25 | assert.NotNil(t, sender.notificationCh) |
| 26 | } |
| 27 | |
| 28 | func TestNotificationSender_NilChannel(t *testing.T) { |
| 29 | sender := NewNotificationSender("") |
| 30 | assert.Nil(t, sender.notificationCh) |
| 31 | |
| 32 | |
| 33 | sender.Send(types.NotificationMessage{ |
| 34 | NotificationType: types.ConnectionEstablished, |
| 35 | MacAddress: "5a:94:ef:e4:0c:ee", |
| 36 | }) |
| 37 | } |
| 38 | |
| 39 | func TestNotificationSender_Success(t *testing.T) { |
| 40 | tmpDir := t.TempDir() |
| 41 | socketPath := filepath.Join(tmpDir, "test.sock") |
| 42 | listener, err := net.Listen("unix", socketPath) |
| 43 | assert.NoError(t, err) |
| 44 | defer listener.Close() |
| 45 | |
| 46 | expectedNotifications := []types.NotificationMessage{ |
| 47 | { |
| 48 | NotificationType: types.Ready, |
| 49 | }, |
| 50 | { |
| 51 | NotificationType: types.ConnectionEstablished, |
| 52 | MacAddress: "5a:94:ef:e4:0c:ee", |
| 53 | }, |
| 54 | { |
| 55 | NotificationType: types.HypervisorError, |
| 56 | }, |
| 57 | { |
| 58 | NotificationType: types.ConnectionClosed, |
| 59 | MacAddress: "5a:94:ef:e4:0c:ee", |
| 60 | }, |
| 61 | } |
| 62 | |
| 63 | for _, expectedNotification := range expectedNotifications { |
| 64 | t.Run(string(expectedNotification.NotificationType), func(t *testing.T) { |
| 65 | done := make(chan struct{}) |
| 66 | go func() { |
| 67 | defer close(done) |
| 68 | conn, err := listener.Accept() |
| 69 | assert.NoError(t, err) |
| 70 | assert.NotNil(t, conn) |
| 71 | defer conn.Close() |
| 72 | |
| 73 | dec := json.NewDecoder(conn) |
| 74 | var notification types.NotificationMessage |
| 75 | assert.NoError(t, dec.Decode(¬ification)) |
| 76 | assert.Equal(t, expectedNotification.NotificationType, notification.NotificationType) |
| 77 | assert.Equal(t, expectedNotification.MacAddress, notification.MacAddress) |
| 78 | }() |
| 79 | |
| 80 | sender := NewNotificationSender(socketPath) |
| 81 | go sender.Start(context.Background()) |
| 82 | |
| 83 | sender.Send(expectedNotification) |
| 84 | select { |
| 85 | case <-done: |
| 86 | case <-time.After(2 * time.Second): |
| 87 | t.Fatal("timeout waiting for notification") |
| 88 | } |
| 89 | }) |
| 90 | } |
| 91 | } |