Skip to content

Commit

Permalink
added unit test for clients
Browse files Browse the repository at this point in the history
  • Loading branch information
Paramadon committed Dec 12, 2024
1 parent dbb6bb5 commit 87208dd
Show file tree
Hide file tree
Showing 10 changed files with 168 additions and 9 deletions.
2 changes: 2 additions & 0 deletions processor/resourcedetectionprocessor/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ type Config struct {
// Deprecated: Please use detector's resource_attributes config instead
Attributes []string `mapstructure:"attributes"`

// MiddlewareID is an ID for an extension that can be used to configure the
// AWS client.
MiddlewareID *component.ID `mapstructure:"middleware,omitempty"`
}

Expand Down
1 change: 0 additions & 1 deletion processor/resourcedetectionprocessor/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,6 @@ func (f *factory) getResourceDetectionProcessor(
}

return &resourceDetectionProcessor{
config: oCfg,
provider: provider,
override: oCfg.Override,
httpClientSettings: oCfg.ClientConfig,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,3 +212,4 @@ func MergeResource(to, from pcommon.Resource, overrideTo bool) {
func IsEmptyResource(res pcommon.Resource) bool {
return res.Attributes().Len() == 0
}

Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go/aws/request"
"go.opentelemetry.io/collector/component"
"net/http"
"sync"
"testing"
Expand Down Expand Up @@ -317,3 +319,100 @@ func TestFilterAttributes_NoAttributes(t *testing.T) {

assert.Equal(t, len(droppedAttributes), 0)
}

// mockDetectorWithHandler is a mock detector that implements ExposeHandlerDetector
type mockDetectorWithHandler struct {
handlersCalled bool
}

func (m *mockDetectorWithHandler) Detect(ctx context.Context) (resource pcommon.Resource, schemaURL string, err error) {
return pcommon.NewResource(), "", nil
}

func (m *mockDetectorWithHandler) ExposeHandlers(ctx context.Context) *request.Handlers {
m.handlersCalled = true
return &request.Handlers{}
}

// mockExtension implements component.Component
type mockExtension struct {
configured bool
}

func (m *mockExtension) Start(context.Context, component.Host) error {
return nil
}

func (m *mockExtension) Shutdown(context.Context) error {
return nil
}

// mockHost implements component.Host
type mockHost struct {
extensions map[component.ID]component.Component
}

// mockDetector is a basic detector that doesn't implement ExposeHandlerDetector
type mockDetector struct{}

func (m *mockDetector) Detect(ctx context.Context) (resource pcommon.Resource, schemaURL string, err error) {
return pcommon.NewResource(), "", nil
}

func newMockHost() component.Host {
return &mockHost{
extensions: make(map[component.ID]component.Component),
}
}

func (m *mockHost) GetExtension(id component.ID) (component.Component, error) {
if ext, ok := m.extensions[id]; ok {
return ext, nil
}
return nil, nil
}

func (m *mockHost) ReportFatalError(err error) {}

func (m *mockHost) GetFactory(kind component.Kind, componentType component.Type) component.Factory {
return nil
}

func (m *mockHost) GetExtensions() map[component.ID]component.Component {
return m.extensions
}

func (m *mockHost) GetExporters() map[component.DataType]map[component.ID]component.Component {
return nil
}

func TestConfigureHandlers(t *testing.T) {
testType, _ := component.NewType("awsmiddleware")
mockDetector := &mockDetectorWithHandler{}
logger := zap.NewNop()
provider := NewResourceProvider(logger, 0, nil, mockDetector)
mockExt := &mockExtension{}
host := newMockHost()
host.(*mockHost).extensions[component.NewID(testType)] = mockExt

middlewareID := component.NewID(testType)
ctx := context.Background()
provider.ConfigureHandlers(ctx, host, middlewareID)

assert.True(t, mockDetector.handlersCalled, "ExposeHandlers should have been called")
}

func TestConfigureHandlersWithNonHandlerDetector(t *testing.T) {
testType, _ := component.NewType("awsmiddleware")
basicDetector := &mockDetector{}
logger := zap.NewNop()
provider := NewResourceProvider(logger, 0, nil, basicDetector)

mockExt := &mockExtension{}
host := newMockHost()
host.(*mockHost).extensions[component.NewID(testType)] = mockExt
middlewareID := component.NewID(testType)

ctx := context.Background()
provider.ConfigureHandlers(ctx, host, middlewareID)
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
)

type resourceDetectionProcessor struct {
config *Config
middlewareID *component.ID
provider *internal.ResourceProvider
resource pcommon.Resource
schemaURL string
Expand All @@ -31,7 +31,9 @@ func (rdp *resourceDetectionProcessor) Start(ctx context.Context, host component
client, _ := rdp.httpClientSettings.ToClient(ctx, host, rdp.telemetrySettings)
ctx = internal.ContextWithClient(ctx, client)
var err error
rdp.provider.ConfigureHandlers(ctx, host, *rdp.config.MiddlewareID) //configuring middleware in all clients of detectors
if host != nil && rdp.middlewareID != nil{
rdp.provider.ConfigureHandlers(ctx, host, *rdp.middlewareID) //configuring middleware in all clients of detectors
}
rdp.resource, rdp.schemaURL, err = rdp.provider.Get(ctx, client)
return err
}
Expand Down
2 changes: 2 additions & 0 deletions receiver/awscontainerinsightreceiver/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,5 +75,7 @@ type Config struct {
// RunOnSystemd is an optional attribute to run the receiver in an EC2 environment
RunOnSystemd bool `mapstructure:"run_on_systemd,omitempty"`

// MiddlewareID is an ID for an extension that can be used to configure the
// AWS client.
MiddlewareID *component.ID `mapstructure:"middleware,omitempty"`
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,6 @@ func newEBSVolume(ctx context.Context, session *session.Session, instanceID stri
err := configurer.Configure(awsmiddleware.SDKv1(&e.client.(*ec2.EC2).Handlers))
if err != nil {
log.Println("There was a problem configuring middleware on ec2 client")
} else {
log.Println("Successfully configured sdk with middleware handlers")
}
}
for _, opt := range options {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,6 @@ func newEC2Metadata(ctx context.Context, session *session.Session, refreshInterv
err := configurer.Configure(awsmiddleware.SDKv1(&emd.client.(*awsec2metadata.EC2Metadata).Handlers))
if err != nil {
log.Println("There was a problem configuring middleware on ec2 client")
} else {
log.Println("Successfully configured sdk with middleware handlers")
}
}

Expand Down
2 changes: 0 additions & 2 deletions receiver/awscontainerinsightreceiver/internal/host/ec2tags.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,6 @@ func newEC2Tags(ctx context.Context, session *session.Session, instanceID string
err := configurer.Configure(awsmiddleware.SDKv1(&et.client.(*ec2.EC2).Handlers))
if err != nil {
log.Println("There was a problem configuring middleware on ec2 client")
} else {
log.Println("Successfully configured sdk with middleware handlers")
}
}

Expand Down
60 changes: 60 additions & 0 deletions receiver/awscontainerinsightreceiver/receiver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ package awscontainerinsightreceiver
import (
"context"
"errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"go.opentelemetry.io/collector/component"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -158,3 +161,60 @@ func TestCollectDataWithSystemd(t *testing.T) {
err = r.collectData(ctx)
require.Nil(t, err)
}

// MockHost is a mock implementation of component.Host
type MockHost struct {
mock.Mock
}

func (m *MockHost) GetExtensions() map[component.ID]component.Component {
args := m.Called()
return args.Get(0).(map[component.ID]component.Component)
}

// MockConfigurer is a mock implementation of awsmiddleware.Configurer
type MockConfigurer struct {
mock.Mock
}

func (m *MockConfigurer) Start(context.Context, component.Host) error {
return nil
}

func (m *MockConfigurer) Shutdown(context.Context) error {
return nil
}

func (m *MockHost) GetFactory(kind component.Kind, componentType component.Type) component.Factory {
return nil
}

func TestAWSContainerInsightReceiverStart(t *testing.T) {
// Create a mock host
mockHost := new(MockHost)
testType, _ := component.NewType("awsmiddleware")

// Create a mock configurer
mockConfigurer := new(MockConfigurer)
agenthealth, _ := component.NewType("agenthealth")
// Set up the mock host to return a map with the mock configurer
mockHost.On("GetExtensions").Return(map[component.ID]component.Component{
component.NewID(testType): mockConfigurer,
})

statusCodeID := component.NewIDWithName(agenthealth, "statuscode")

// Create a receiver instance
config := &Config{
CollectionInterval: 60,
ContainerOrchestrator: "eks",
MiddlewareID: &statusCodeID,
}
consumer := consumertest.NewNop()
receiver, err := newAWSContainerInsightReceiver(component.TelemetrySettings{}, config, consumer)
assert.NoError(t, err)
err = receiver.Start(context.Background(), mockHost)
assert.Error(t, err)

mockHost.AssertCalled(t, "GetExtensions")
}

0 comments on commit 87208dd

Please sign in to comment.