|
| 1 | +package deviceplugin |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "net" |
| 6 | + "os" |
| 7 | + "path/filepath" |
| 8 | + "testing" |
| 9 | + "time" |
| 10 | + |
| 11 | + "go.uber.org/zap" |
| 12 | +) |
| 13 | + |
| 14 | +type mockDeviceCounter struct { |
| 15 | + count int |
| 16 | +} |
| 17 | + |
| 18 | +func (m *mockDeviceCounter) getDeviceCount() int { |
| 19 | + return m.count |
| 20 | +} |
| 21 | + |
| 22 | +func TestServer_Run_CleansUpExistingSocket(t *testing.T) { |
| 23 | + // Create a temporary directory for the socket |
| 24 | + tmpDir := t.TempDir() |
| 25 | + socketPath := filepath.Join(tmpDir, "test.sock") |
| 26 | + |
| 27 | + // Create a dummy file at the socket path to simulate a stale socket |
| 28 | + if err := os.WriteFile(socketPath, []byte("stale socket"), 0644); err != nil { |
| 29 | + t.Fatalf("failed to create dummy socket file: %v", err) |
| 30 | + } |
| 31 | + |
| 32 | + logger := zap.NewNop() |
| 33 | + counter := &mockDeviceCounter{count: 1} |
| 34 | + server := NewServer(logger, socketPath, counter, time.Second) |
| 35 | + |
| 36 | + // Create a context that we can cancel to stop the server |
| 37 | + ctx, cancel := context.WithCancel(context.Background()) |
| 38 | + |
| 39 | + // Run the server in a goroutine |
| 40 | + errChan := make(chan error) |
| 41 | + go func() { |
| 42 | + errChan <- server.Run(ctx) |
| 43 | + }() |
| 44 | + |
| 45 | + // Wait for the server to start up, delete the pre-existing file and recreate it as a socket |
| 46 | + // We verify this by trying to connect to the socket repeatedly until success or timeout |
| 47 | + var conn net.Conn |
| 48 | + var err error |
| 49 | + // Retry for up to 2 seconds |
| 50 | + for start := time.Now(); time.Since(start) < 2*time.Second; time.Sleep(200 * time.Millisecond) { |
| 51 | + conn, err = net.Dial("unix", socketPath) |
| 52 | + if err == nil { |
| 53 | + conn.Close() |
| 54 | + break |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + if err != nil { |
| 59 | + t.Errorf("failed to connect to socket: %v", err) |
| 60 | + } |
| 61 | + |
| 62 | + // Stop the server |
| 63 | + cancel() |
| 64 | + |
| 65 | + // Wait for Run to return |
| 66 | + if err := <-errChan; err != nil { |
| 67 | + t.Errorf("server.Run returned error: %v", err) |
| 68 | + } |
| 69 | +} |
0 commit comments