|
| 1 | +package components |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/stretchr/testify/assert" |
| 9 | +) |
| 10 | + |
| 11 | +// Mock function that returns a component without error |
| 12 | +func mockInitFuncSuccess(instance GPUdInstance) (Component, error) { |
| 13 | + return newMockComponent("test-component"), nil |
| 14 | +} |
| 15 | + |
| 16 | +// Mock function that returns an error |
| 17 | +func mockInitFuncError(instance GPUdInstance) (Component, error) { |
| 18 | + return nil, fmt.Errorf("mock init error") |
| 19 | +} |
| 20 | + |
| 21 | +func TestHasRegistered(t *testing.T) { |
| 22 | + // Create a new registry |
| 23 | + reg := NewRegistry(GPUdInstance{ |
| 24 | + RootCtx: context.Background(), |
| 25 | + }) |
| 26 | + |
| 27 | + // When registry is empty, should return false |
| 28 | + assert.False(t, reg.hasRegistered("test-component")) |
| 29 | + |
| 30 | + // Register a component |
| 31 | + comp := newMockComponent("test-component") |
| 32 | + reg.mu.Lock() |
| 33 | + reg.components["test-component"] = comp |
| 34 | + reg.mu.Unlock() |
| 35 | + |
| 36 | + // Should now return true for the registered component |
| 37 | + assert.True(t, reg.hasRegistered("test-component")) |
| 38 | + |
| 39 | + // Should still return false for unregistered components |
| 40 | + assert.False(t, reg.hasRegistered("unknown-component")) |
| 41 | +} |
| 42 | + |
| 43 | +func TestRegisterInitFunc(t *testing.T) { |
| 44 | + // Create a new registry |
| 45 | + reg := NewRegistry(GPUdInstance{ |
| 46 | + RootCtx: context.Background(), |
| 47 | + }) |
| 48 | + |
| 49 | + // Test registering a component successfully |
| 50 | + err := reg.registerInit("test-component", mockInitFuncSuccess) |
| 51 | + assert.NoError(t, err) |
| 52 | + assert.True(t, reg.hasRegistered("test-component")) |
| 53 | + |
| 54 | + // Test registering a component that already exists |
| 55 | + err = reg.registerInit("test-component", mockInitFuncSuccess) |
| 56 | + assert.Error(t, err) |
| 57 | + assert.Contains(t, err.Error(), "already registered") |
| 58 | + |
| 59 | + // Test registering a component with an initialization function that returns an error |
| 60 | + err = reg.registerInit("error-component", mockInitFuncError) |
| 61 | + assert.Error(t, err) |
| 62 | + assert.Contains(t, err.Error(), "mock init error") |
| 63 | + |
| 64 | + // The component should not be registered if the init function fails |
| 65 | + assert.False(t, reg.hasRegistered("error-component")) |
| 66 | +} |
0 commit comments