Skip to content

Commit

Permalink
add manager tests
Browse files Browse the repository at this point in the history
  • Loading branch information
leoparente committed Dec 6, 2024
1 parent 0f6b5dc commit 7b27b76
Show file tree
Hide file tree
Showing 2 changed files with 236 additions and 2 deletions.
139 changes: 139 additions & 0 deletions network-discovery/policy/manager_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
package policy_test

import (
"context"
"log/slog"
"os"
"testing"

"github.com/netboxlabs/diode-sdk-go/diode"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"

"github.com/netboxlabs/orb-discovery/network-discovery/config"
"github.com/netboxlabs/orb-discovery/network-discovery/policy"
)

// MockRunner mocks the Runner
type MockRunner struct {
mock.Mock
}

func (m *MockRunner) Configure(ctx context.Context, logger *slog.Logger, name string, policy config.Policy, client diode.Client) error {
args := m.Called(ctx, logger, name, policy, client)
return args.Error(0)
}

func (m *MockRunner) Start() {
m.Called()
}

func (m *MockRunner) Stop() error {
args := m.Called()
return args.Error(0)
}

func TestManagerConfigure(t *testing.T) {
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug, AddSource: false}))
mockClient := new(MockClient)

manager := &policy.Manager{}
err := manager.Configure(context.Background(), logger, mockClient)
assert.NoError(t, err)
assert.NotNil(t, manager)
}

func TestManagerParsePolicies(t *testing.T) {
manager := &policy.Manager{}

t.Run("Valid Policies", func(t *testing.T) {
yamlData := []byte(`
network:
policies:
policy1:
config:
defaults:
site: New York NY
scope:
targets:
- 192.168.1.1/24
`)

policies, err := manager.ParsePolicies(yamlData)
assert.NoError(t, err)
assert.Contains(t, policies, "policy1")
assert.Equal(t, "New York NY", policies["policy1"].Config.Defaults["site"])
})

t.Run("No Policies", func(t *testing.T) {
yamlData := []byte(`network: {}`)
_, err := manager.ParsePolicies(yamlData)
assert.Error(t, err)
assert.Equal(t, "no policies found in the request", err.Error())
})
}

func TestManagerPolicyLifecycle(t *testing.T) {
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug, AddSource: false}))
manager := &policy.Manager{}
err := manager.Configure(context.Background(), logger, nil)
assert.NoError(t, err)
yamlData := []byte(`
network:
policies:
policy1:
scope:
targets:
- 192.168.1.1/24
policy2:
scope:
targets:
- 192.168.2.1/24
policy3:
scope:
targets: []
`)

policies, err := manager.ParsePolicies(yamlData)
assert.NoError(t, err)

// Start policies
err = manager.StartPolicy("policy1", policies["policy1"])
assert.NoError(t, err)
err = manager.StartPolicy("policy2", policies["policy2"])
assert.NoError(t, err)

// Try to start policy 3
err = manager.StartPolicy("policy3", policies["policy3"])
assert.Contains(t, err.Error(), "no targets found in the policy")

// Check if the policies exist
assert.True(t, manager.HasPolicy("policy1"))
assert.True(t, manager.HasPolicy("policy2"))
assert.False(t, manager.HasPolicy("policy3"))

// Stop policy 1
err = manager.StopPolicy("policy1")
assert.NoError(t, err)

// Check if the policy exists
assert.False(t, manager.HasPolicy("policy1"))
assert.True(t, manager.HasPolicy("policy2"))
assert.False(t, manager.HasPolicy("policy3"))

// Stop Manager
err = manager.Stop()
assert.NoError(t, err)

// Check if the policies exist
assert.False(t, manager.HasPolicy("policy1"))
assert.False(t, manager.HasPolicy("policy2"))
assert.False(t, manager.HasPolicy("policy3"))
}

func TestManagerGetCapabilities(t *testing.T) {
manager := &policy.Manager{}

capabilities := manager.GetCapabilities()
assert.Equal(t, []string{"targets, ports"}, capabilities)
}
99 changes: 97 additions & 2 deletions network-discovery/server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func (m *MockClient) Close() error {
return args.Error(0)
}

func TestServerConfigureAndStatus(t *testing.T) {
func TestServerConfigureAndStart(t *testing.T) {
ctx := context.Background()
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug, AddSource: false}))
client := new(MockClient)
Expand All @@ -52,6 +52,10 @@ func TestServerConfigureAndStatus(t *testing.T) {
version := "1.0.0"

srv.Configure(logger, &policyManager, version, config)
err = srv.Start()

// Check if the server started successfully
assert.NoError(t, err, "Server.Start should not return an error")

// Check /status endpoint
w := httptest.NewRecorder()
Expand All @@ -68,7 +72,7 @@ func TestServerConfigureAndStatus(t *testing.T) {
srv.Stop()
}

func TestServer_GetCapabilities(t *testing.T) {
func TestServerGetCapabilities(t *testing.T) {
ctx := context.Background()
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug, AddSource: false}))
client := new(MockClient)
Expand Down Expand Up @@ -127,6 +131,18 @@ func TestServerCreateDeletePolicy(t *testing.T) {
assert.Contains(t, w.Body.String(), `policy 'test-policy' was started`)

// Try to create the same policy again
body = []byte(`
network:
policies:
test-pol:
scope:
targets:
- 192.168.31.1/24
test-policy:
scope:
targets:
- 192.168.31.1/24
`)
w = httptest.NewRecorder()
request, _ = http.NewRequest(http.MethodPost, "/api/v1/policies", bytes.NewReader(body))
request.Header.Set("Content-Type", "application/x-yaml")
Expand All @@ -152,3 +168,82 @@ func TestServerCreateDeletePolicy(t *testing.T) {
assert.Equal(t, http.StatusNotFound, w.Code)
assert.Contains(t, w.Body.String(), `policy not found`)
}

func TestServerCreateInvalidPolicy(t *testing.T) {
tests := []struct {
desc string
contentType string
body []byte
returnCode int
returnMessage string
}{
{
desc: "invalid content type",
contentType: "application/json",
body: []byte(``),
returnCode: http.StatusBadRequest,
returnMessage: `invalid Content-Type. Only 'application/x-yaml' is supported`,
},
{
desc: "invalid YAML",
contentType: "application/x-yaml",
body: []byte(`invalid`),
returnCode: http.StatusBadRequest,
returnMessage: `yaml: unmarshal errors:`,
},
{
desc: "no policies found",
contentType: "application/x-yaml",
body: []byte(`
network:
config: {}
`),
returnCode: http.StatusBadRequest,
returnMessage: `no policies found in the request`,
},
{
desc: "no targets found",
contentType: "application/x-yaml",
body: []byte(`
network:
policies:
test-policy:
scope:
targets:
- 192.168.31.1/24
test-policy-invalid:
config:
defaults:
site: New York NY
scope:
ports: [80, 443]
`),
returnCode: http.StatusBadRequest,
returnMessage: `test-policy-invalid : no targets found in the policy`,
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
ctx := context.Background()
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug, AddSource: false}))
client := new(MockClient)

policyManager := policy.Manager{}
err := policyManager.Configure(ctx, logger, client)
assert.NoError(t, err, "Manager.Configure should not return an error")

srv := &server.Server{}
srv.Configure(logger, &policyManager, "1.0.0", config.StartupConfig{})

// Create invalid policy request
w := httptest.NewRecorder()
request, _ := http.NewRequest(http.MethodPost, "/api/v1/policies", bytes.NewReader(tt.body))
request.Header.Set("Content-Type", tt.contentType)

srv.Router().ServeHTTP(w, request)

assert.Equal(t, tt.returnCode, w.Code)
assert.Contains(t, w.Body.String(), tt.returnMessage)
})
}
}

0 comments on commit 7b27b76

Please sign in to comment.