Skip to content

Commit

Permalink
test: add unit tests for tarian-pod-agent
Browse files Browse the repository at this point in the history
  • Loading branch information
pratikjagrut committed Oct 18, 2023
1 parent 3a6af83 commit e556b08
Show file tree
Hide file tree
Showing 15 changed files with 638 additions and 71 deletions.
55 changes: 55 additions & 0 deletions cmd/tarian-pod-agent/cmd/flags/flags_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package flags

import (
"testing"

"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
)

func TestSetGlobalFlags(t *testing.T) {
// Create a FlagSet for testing
fs := pflag.NewFlagSet("test", pflag.ExitOnError)

// Initialize global flags
globalFlags := SetGlobalFlags(fs)

// Test default values
assert.Equal(t, "info", globalFlags.LogLevel)
assert.Equal(t, "text", globalFlags.LogFormatter)
}

func TestValidateGlobalFlags(t *testing.T) {
tests := []struct {
name string
globalFlags *GlobalFlags
expectedError string
}{
{
name: "Valid Flags",
globalFlags: &GlobalFlags{LogLevel: "info", LogFormatter: "text"},
expectedError: "",
},
{
name: "Invalid LogLevel",
globalFlags: &GlobalFlags{LogLevel: "invalid", LogFormatter: "text"},
expectedError: "invalid log level: invalid",
},
{
name: "Invalid LogFormatter",
globalFlags: &GlobalFlags{LogLevel: "info", LogFormatter: "invalid"},
expectedError: "invalid log formatter: invalid",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.globalFlags.ValidateGlobalFlags()
if tt.expectedError == "" {
assert.NoError(t, err)
} else {
assert.EqualError(t, err, tt.expectedError)
}
})
}
}
36 changes: 20 additions & 16 deletions cmd/tarian-pod-agent/cmd/register.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"fmt"
"os"
"os/signal"
"strings"
Expand Down Expand Up @@ -29,6 +30,8 @@ type registerCommand struct {
registerFilePaths string
registerFileIgnorePaths string
fileValidationInterval time.Duration

podAgent podagent.Agent
}

func newRegisterCommand(globalFlag *flags.GlobalFlags) *cobra.Command {
Expand Down Expand Up @@ -61,13 +64,14 @@ func newRegisterCommand(globalFlag *flags.GlobalFlags) *cobra.Command {
func (c *registerCommand) runRegisterCommand(cmd *cobra.Command, args []string) error {
c.logger.Info("tarian-pod-agent is running in register mode")
addr := c.host + ":" + c.port
agent := podagent.NewPodAgent(c.logger, addr)
if c.podAgent == nil {
c.podAgent = podagent.NewPodAgent(c.logger, addr)
}

if c.podLabelsFile != "" {
podLabels, err := readLabelsFromFile(c.podLabelsFile)

podLabels, err := readLabelsFromFile(c.logger, c.podLabelsFile)
if err != nil {
c.logger.WithError(err).Error("failed reading pod-labels-file")
return fmt.Errorf("failed reading pod-labels-file: %w", err)
}

// delete pod-template-hash
Expand All @@ -82,35 +86,35 @@ func (c *registerCommand) runRegisterCommand(cmd *cobra.Command, args []string)
}
}

agent.SetPodLabels(podLabels)
c.podAgent.SetPodLabels(podLabels)
}

if c.podName != "" {
agent.SetPodName(c.podName)
c.podAgent.SetPodName(c.podName)
} else {
hostname, err := os.Hostname()
if err == nil {
agent.SetPodName(hostname)
c.podAgent.SetPodName(hostname)
}
}

if c.podUID != "" {
agent.SetpodUID(c.podUID)
c.podAgent.SetPodUID(c.podUID)
}

if c.namespace != "" {
agent.SetNamespace(c.namespace)
c.podAgent.SetNamespace(c.namespace)
}

registerRules := strings.Split(c.registerRules, ",")
for _, rule := range registerRules {
switch strings.TrimSpace(rule) {
case "files":
c.logger.Warn("enabled auto register for files")
agent.EnableRegisterFiles()
c.podAgent.EnableRegisterFiles()
case "all":
c.logger.Info("enabled auto register for all rules")
agent.EnableRegisterFiles()
c.podAgent.EnableRegisterFiles()
}
}

Expand All @@ -119,16 +123,16 @@ func (c *registerCommand) runRegisterCommand(cmd *cobra.Command, args []string)
for _, path := range registerFilePathsArg {
registerFilePaths = append(registerFilePaths, strings.TrimSpace(path))
}
agent.SetRegisterFilePaths(registerFilePaths)
c.podAgent.SetRegisterFilePaths(registerFilePaths)

registerFileIgnorePathsArg := strings.Split(c.registerFileIgnorePaths, ",")
registerFileIgnorePaths := []string{}
for _, path := range registerFileIgnorePathsArg {
registerFileIgnorePaths = append(registerFileIgnorePaths, strings.TrimSpace(path))
}
agent.SetRegisterFileIgnorePaths(registerFileIgnorePaths)
c.podAgent.SetRegisterFileIgnorePaths(registerFileIgnorePaths)

agent.SetFileValidationInterval(c.fileValidationInterval)
c.podAgent.SetFileValidationInterval(c.fileValidationInterval)

sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
Expand All @@ -137,10 +141,10 @@ func (c *registerCommand) runRegisterCommand(cmd *cobra.Command, args []string)
sig := <-sigCh
c.logger.WithField("signal", sig).Info("got sigterm signal, attempting graceful shutdown")

agent.GracefulStop()
c.podAgent.GracefulStop()
}()

agent.RunRegister()
c.podAgent.RunRegister()
c.logger.Info("tarian-pod-agent shutdown gracefully")
return nil
}
123 changes: 123 additions & 0 deletions cmd/tarian-pod-agent/cmd/register_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package cmd

import (
"os"
"testing"

"github.com/kube-tarian/tarian/cmd/tarian-pod-agent/cmd/flags"
"github.com/kube-tarian/tarian/pkg/log"
"github.com/kube-tarian/tarian/pkg/podagent"
utesting "github.com/kube-tarian/tarian/pkg/testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
)

func TestRegisterCommandRun(t *testing.T) {
logger := log.GetLogger()
file := createTestLabelsFile(t, true)
defer os.Remove(file.Name())
tests := []struct {
name string
expectedErr string
expectedLog string

podLabelsFile string

podAgent podagent.Agent
}{
{
name: "Run Register mode Successfully",
podAgent: podagent.NewFakePodAgent(logger),
expectedLog: "tarian-pod-agent is running in register mode",
},
{
name: "Run Register mode with a empty Labels File",
podAgent: podagent.NewFakePodAgent(logger),
expectedErr: "no labels found in file",
podLabelsFile: file.Name(),
},
{
name: "Run register mode with Invalid Labels File",
expectedErr: "failed to open file",
podLabelsFile: "nonexistent_labels.txt",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := &registerCommand{
logger: logger,
podLabelsFile: tt.podLabelsFile,
podAgent: tt.podAgent,
}

logOutput := []byte{}
cmd.logger.Out = &utesting.LogOutputWriter{Output: &logOutput}
log.MiniLogFormat()

err := cmd.runRegisterCommand(nil, nil)

if tt.expectedErr != "" {
assert.Contains(t, err.Error(), tt.expectedErr)
} else {
if !assert.NoError(t, err) {
assert.FailNow(t, "error not expected")
}
}

if tt.expectedLog != "" {
assert.Contains(t, utesting.CleanLog(string(logOutput)), utesting.CleanLog(tt.expectedLog))
}
})
}
}

func TestNewRegisterModeCommand(t *testing.T) {
globalFlags := &flags.GlobalFlags{}
cmd := newRegisterCommand(globalFlags)

assert.NotNil(t, cmd)
assert.IsType(t, &cobra.Command{}, cmd)

assert.Equal(t, "register", cmd.Use)
assert.Equal(t, "Register the pod to the Tarian server", cmd.Short)

testFlags(t, cmd)
}

func testFlags(t *testing.T, cmd *cobra.Command) {
assert.Equal(t, defaultClusterAgentHost, cmd.Flags().Lookup("host").DefValue)
err := cmd.Flags().Set("host", "localhost")
assert.NoError(t, err)
assert.Equal(t, "localhost", cmd.Flags().Lookup("host").Value.String())

assert.Equal(t, defaultClusterAgentPort, cmd.Flags().Lookup("port").DefValue)
err = cmd.Flags().Set("port", "50053")
assert.NoError(t, err)
assert.Equal(t, "50053", cmd.Flags().Lookup("port").Value.String())

assert.Equal(t, "", cmd.Flags().Lookup("pod-labels-file").DefValue)
err = cmd.Flags().Set("pod-labels-file", "test_labels.txt")
assert.NoError(t, err)
assert.Equal(t, "test_labels.txt", cmd.Flags().Lookup("pod-labels-file").Value.String())

assert.Equal(t, "", cmd.Flags().Lookup("pod-name").DefValue)
err = cmd.Flags().Set("pod-name", "test_pod")
assert.NoError(t, err)
assert.Equal(t, "test_pod", cmd.Flags().Lookup("pod-name").Value.String())

assert.Equal(t, "", cmd.Flags().Lookup("pod-uid").DefValue)
err = cmd.Flags().Set("pod-uid", "test_pod_uid")
assert.NoError(t, err)
assert.Equal(t, "test_pod_uid", cmd.Flags().Lookup("pod-uid").Value.String())

assert.Equal(t, "", cmd.Flags().Lookup("namespace").DefValue)
err = cmd.Flags().Set("namespace", "test_namespace")
assert.NoError(t, err)
assert.Equal(t, "test_namespace", cmd.Flags().Lookup("namespace").Value.String())

assert.Equal(t, "3s", cmd.Flags().Lookup("file-validation-interval").DefValue)
err = cmd.Flags().Set("file-validation-interval", "5s")
assert.NoError(t, err)
assert.Equal(t, "5s", cmd.Flags().Lookup("file-validation-interval").Value.String())
}
2 changes: 1 addition & 1 deletion cmd/tarian-pod-agent/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ var globalFlags *flags.GlobalFlags

func newRootCommand(logger *logrus.Logger) *cobra.Command {
var rootCmd = &cobra.Command{
Use: "Tarian Pod Agent",
Use: "tarian-pod-agent",
Short: "The Tarian pod agent is the component which runs as a sidecar to monitor your main container.",
Version: version.GetVersion(),
SilenceUsage: true,
Expand Down
36 changes: 36 additions & 0 deletions cmd/tarian-pod-agent/cmd/root_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package cmd

import (
"bytes"
"io"
"testing"

"github.com/kube-tarian/tarian/pkg/log"
"github.com/stretchr/testify/assert"
)

func TestPodAgentRootCommand(t *testing.T) {
t.Run("TestRootCommandVersion", func(t *testing.T) {
stdout := new(bytes.Buffer)

err := runRootCommand(stdout, []string{"version"})
if assert.NoError(t, err) {
out, _ := io.ReadAll(stdout)
assert.Contains(t, string(out), "tarian pod agent version:")
}
})

t.Run("TestRootCommandInvalidSubcommand", func(t *testing.T) {
stdout := new(bytes.Buffer)
err := runRootCommand(stdout, []string{"invalidStderr-subcommand"})
assert.EqualError(t, err, `unknown command "invalidStderr-subcommand" for "tarian-pod-agent"`)
})
}

func runRootCommand(output *bytes.Buffer, args []string) error {
logger := log.GetLogger()
logger.SetOutput(output)
rootCmd := buildRootCommand(logger)
rootCmd.SetArgs(args)
return rootCmd.Execute()
}
Loading

0 comments on commit e556b08

Please sign in to comment.