Skip to content

Commit

Permalink
with test cases
Browse files Browse the repository at this point in the history
Signed-off-by: SudhanshuBawane <[email protected]>
  • Loading branch information
SudhanshuBawane committed Mar 7, 2024
1 parent ca45c3f commit 76f7b3c
Show file tree
Hide file tree
Showing 3 changed files with 130 additions and 58 deletions.
9 changes: 4 additions & 5 deletions backend/agentd/agentd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,6 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"

corev2 "github.com/sensu/core/v2"
corev3 "github.com/sensu/core/v3"
"github.com/sensu/sensu-go/backend/apid/middlewares"
Expand All @@ -22,6 +17,10 @@ import (
"github.com/sensu/sensu-go/transport"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)

func TestAgentdMiddlewares(t *testing.T) {
Expand Down
52 changes: 1 addition & 51 deletions backend/agentd/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ type SessionConfig struct {
// with the session has been buried. Necessary when running parallel keepalived
// workers.
BurialReceiver *BurialReceiver
userConfig *userConfig
}

type BurialReceiver struct {
Expand Down Expand Up @@ -356,8 +357,6 @@ func (s *Session) sender() {
}
// Handle the delete/disable event
switch watchEvent.Action {
case store.WatchCreate:
logger.Println("New user has been created")
case store.WatchUpdate:
if watchEvent.Disabled {
logger.Warn("The user associated with the agent is now disabled")
Expand Down Expand Up @@ -580,55 +579,6 @@ func (s *Session) Start() (err error) {
lager.WithError(err).Error("error publishing user config")
return err
}
//if err != nil {
// // Just exit but don't send error about absence of user config
// var errNotFound *store.ErrNotFound
// if !errors.As(err, &errNotFound) {
// lager.WithError(err).Error("error querying the user config")
// return err
// }
// lager.Debug("no user config found")
//
// // Indicate to the agent that this user does not exist
// //meta := corev2.NewObjectMeta(UserNotFound, s.cfg.Namespace)
// watchEvent := &store.WatchEventUserConfig{
// User: &corev2.User{},
// Action: store.WatchCreate,
// //Metadata: &meta,
// }
// err = s.bus.Publish(messaging.UserConfigTopic(s.cfg.Namespace, s.cfg.AgentName), watchEvent)
// if err != nil {
// lager.WithError(err).Error("error publishing user config")
// return err
// }
//} else {
// // A user config already exists, therefore we should the stored user subscriptions
// // rather than what the agent provided us for the subscriptions
// lager.Debug("an user config was found")
//
// var storedUserConfig corev2.User
// err = usrWrapper.UnwrapInto(&storedUserConfig)
// if err != nil {
// lager.WithError(err).Error("error unwrapping user config")
// return err
// }
//
// // Remove the managed_by label if the value is sensu-agent, in case of disabled user
// if storedUserConfig.GetMetadata().Labels[corev2.ManagedByLabel] == "sensu-agent" {
// delete(storedUserConfig.GetMetadata().Labels, corev2.ManagedByLabel)
// }
//
// // Send back this user config to the agent so it uses that rather than it's local config
// watchEvent := &store.WatchEventUserConfig{
// Action: store.WatchUpdate,
// User: &storedUserConfig,
// }
// err = s.bus.Publish(messaging.UserConfigTopic(s.cfg.Namespace, s.cfg.AgentName), watchEvent)
// if err != nil {
// lager.WithError(err).Error("error publishing user config")
// return err
// }
//}

// Determine if the entity already exists
subscription, err := s.bus.Subscribe(topic, agentName, s.entityConfig)
Expand Down
127 changes: 125 additions & 2 deletions backend/agentd/session_test.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
package agentd

import (
"bytes"
"context"
"errors"
"fmt"
"github.com/sirupsen/logrus"
"reflect"
"sync"
"testing"
"time"

"github.com/gogo/protobuf/proto"
"github.com/sensu/sensu-go/agent"
corev2 "github.com/sensu/core/v2"
corev3 "github.com/sensu/core/v3"
"github.com/sensu/sensu-go/agent"
"github.com/sensu/sensu-go/backend/messaging"
"github.com/sensu/sensu-go/backend/store"
storev2 "github.com/sensu/sensu-go/backend/store/v2"
Expand Down Expand Up @@ -75,11 +77,126 @@ func TestMakeEntitySwitchBurialEvent(t *testing.T) {
}
}

type UserConfig struct {
updatesChannel chan interface{}

Check failure on line 81 in backend/agentd/session_test.go

View workflow job for this annotation

GitHub Actions / staticcheck (project)

field updatesChannel is unused (U1000)
}

func TestSession_sender(t *testing.T) {
type busFunc func(*messaging.WizardBus, *sync.WaitGroup)
type connFunc func(*mocktransport.MockTransport, *sync.WaitGroup)
type storeFunc func(*storetest.Store, *sync.WaitGroup)

userTests := []struct {
name string
connFunc connFunc
watchEvent *store.WatchEventUserConfig
expectedLog string
expectedError bool
busFunc busFunc
storeFunc storeFunc
subscriptions []string
}{
{
name: "valid watchEvent received",
watchEvent: &store.WatchEventUserConfig{
Action: store.WatchUpdate,
User: &corev2.User{
Username: "testUser",
},
},
expectedLog: "user update received",
},
{
name: "watchEvent with nil user",
watchEvent: &store.WatchEventUserConfig{
Action: store.WatchCreate,
User: nil,
},
expectedLog: "session received nil user in watch event",
expectedError: true,
},
}

for _, tt := range userTests {
t.Run(tt.name, func(t *testing.T) {
wg := &sync.WaitGroup{}

// Mock our transport
conn := new(mocktransport.MockTransport)
if tt.connFunc != nil {
tt.connFunc(conn, wg)
}

// Mock our store
st := &mockstore.MockStore{}
storev2 := &storetest.Store{}
if tt.storeFunc != nil {
tt.storeFunc(storev2, wg)
}

// Mock our bus
bus, err := messaging.NewWizardBus(messaging.WizardBusConfig{})
if err != nil {
t.Fatal(err)
}
if err := bus.Start(); err != nil {
t.Fatal(err)
}

// Mocking logger
var logBuffer bytes.Buffer
logger := logrus.New()
logger.SetOutput(&logBuffer)

s := SessionConfig{
AgentName: "testing",
Namespace: "default",
Conn: conn,
Bus: bus,
Store: st,
Storev2: storev2,
Unmarshal: agent.UnmarshalJSON,
Marshal: agent.MarshalJSON,
userConfig: &userConfig{
updatesChannel: make(chan interface{}),
},
}

session, err := NewSession(context.Background(), s)
if err != nil {
t.Fatal(err)
}
session.wg = &sync.WaitGroup{}
session.wg.Add(1)

userTopic := messaging.UserConfigTopic(session.cfg.AgentName)
_, err = session.bus.Subscribe(userTopic, session.cfg.AgentName, session.userConfig)
if err != nil {
t.Fatal(err)
}

go session.sender()
// Send our watch events over the wizard bus
if tt.busFunc != nil {
tt.busFunc(bus, wg)
}

done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()

select {
case <-session.ctx.Done():
case <-done:
session.Stop()
case <-time.After(5 * time.Second):
t.Fatal("session never stopped, we probably never received an user update over the channel")
}
})
}

tests := []struct {
name string
busFunc busFunc
Expand Down Expand Up @@ -299,6 +416,12 @@ func TestSession_sender(t *testing.T) {
if err != nil {
t.Fatal(err)
}
//
//userTopic := messaging.UserConfigTopic(session.cfg.AgentName)
//_, err = session.bus.Subscribe(userTopic, session.cfg.AgentName, session.userConfig)
//if err != nil {
// t.Fatal(err)
//}

go session.sender()

Expand All @@ -318,7 +441,7 @@ func TestSession_sender(t *testing.T) {
case <-done:
session.Stop()
case <-time.After(5 * time.Second):
t.Fatal("session never stopped, we probably never received an entity update over the channel")
t.Fatal("session never stopped, we probably never received an entity/user update over the channel")
}
})
}
Expand Down

0 comments on commit 76f7b3c

Please sign in to comment.