sharedcomponent_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package sharedcomponent
  4. import (
  5. "context"
  6. "errors"
  7. "testing"
  8. "github.com/stretchr/testify/assert"
  9. "go.opentelemetry.io/collector/component"
  10. "go.opentelemetry.io/collector/component/componenttest"
  11. )
  12. var id = component.NewID("test")
  13. func TestNewSharedComponents(t *testing.T) {
  14. comps := NewSharedComponents()
  15. assert.Len(t, comps.comps, 0)
  16. }
  17. type mockComponent struct {
  18. component.StartFunc
  19. component.ShutdownFunc
  20. }
  21. func TestSharedComponents_GetOrAdd(t *testing.T) {
  22. nop := &mockComponent{}
  23. createNop := func() component.Component { return nop }
  24. comps := NewSharedComponents()
  25. got := comps.GetOrAdd(id, createNop)
  26. assert.Len(t, comps.comps, 1)
  27. assert.Same(t, nop, got.Unwrap())
  28. assert.Same(t, got, comps.GetOrAdd(id, createNop))
  29. // Shutdown nop will remove
  30. assert.NoError(t, got.Shutdown(context.Background()))
  31. assert.Len(t, comps.comps, 0)
  32. assert.NotSame(t, got, comps.GetOrAdd(id, createNop))
  33. }
  34. func TestSharedComponent(t *testing.T) {
  35. wantErr := errors.New("my error")
  36. calledStart := 0
  37. calledStop := 0
  38. comp := &mockComponent{
  39. StartFunc: func(ctx context.Context, host component.Host) error {
  40. calledStart++
  41. return wantErr
  42. },
  43. ShutdownFunc: func(ctx context.Context) error {
  44. calledStop++
  45. return wantErr
  46. },
  47. }
  48. createComp := func() component.Component { return comp }
  49. comps := NewSharedComponents()
  50. got := comps.GetOrAdd(id, createComp)
  51. assert.Equal(t, wantErr, got.Start(context.Background(), componenttest.NewNopHost()))
  52. assert.Equal(t, 1, calledStart)
  53. // Second time is not called anymore.
  54. assert.NoError(t, got.Start(context.Background(), componenttest.NewNopHost()))
  55. assert.Equal(t, 1, calledStart)
  56. assert.Equal(t, wantErr, got.Shutdown(context.Background()))
  57. assert.Equal(t, 1, calledStop)
  58. // Second time is not called anymore.
  59. assert.NoError(t, got.Shutdown(context.Background()))
  60. assert.Equal(t, 1, calledStop)
  61. }