Skip to content

Commit

Permalink
more tests
Browse files Browse the repository at this point in the history
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
  • Loading branch information
matthyx committed Nov 21, 2023
1 parent 9d427c8 commit ae18fb1
Show file tree
Hide file tree
Showing 14 changed files with 746 additions and 28 deletions.
9 changes: 5 additions & 4 deletions adapters/backend/v1/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/kubescape/synchronizer/adapters"
"github.com/kubescape/synchronizer/domain"
"github.com/kubescape/synchronizer/messaging"
"github.com/kubescape/synchronizer/utils"
)

type Adapter struct {
Expand All @@ -31,15 +32,15 @@ func NewBackendAdapter(mainContext context.Context, messageProducer messaging.Me
var _ adapters.Adapter = (*Adapter)(nil)

func (b *Adapter) getClient(ctx context.Context) (adapters.Client, error) {
id := domain.ClientIdentifierFromContext(ctx)
id := utils.ClientIdentifierFromContext(ctx)
if client, ok := b.clientsMap.Load(id.String()); ok {
return client.(adapters.Client), nil
}
return nil, fmt.Errorf("unknown resource %s", id.String())
}

func (b *Adapter) Callbacks(ctx context.Context) (domain.Callbacks, error) {
id := domain.ClientIdentifierFromContext(ctx)
id := utils.ClientIdentifierFromContext(ctx)
if callbacks, ok := b.callbacksMap.Load(id.String()); ok {
return callbacks.(domain.Callbacks), nil
}
Expand Down Expand Up @@ -79,7 +80,7 @@ func (b *Adapter) PutObject(ctx context.Context, id domain.KindName, object []by
}

func (b *Adapter) RegisterCallbacks(ctx context.Context, callbacks domain.Callbacks) {
id := domain.ClientIdentifierFromContext(ctx)
id := utils.ClientIdentifierFromContext(ctx)
b.callbacksMap.Store(id.String(), callbacks)
}

Expand All @@ -89,7 +90,7 @@ func (b *Adapter) Start(ctx context.Context) error {
})

client := NewClient(b.producer)
id := domain.ClientIdentifierFromContext(ctx)
id := utils.ClientIdentifierFromContext(ctx)
b.clientsMap.Store(id.String(), client)
callbacks, err := b.Callbacks(ctx)
if err != nil {
Expand Down
12 changes: 6 additions & 6 deletions adapters/backend/v1/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (c *Client) sendServerConnectedMessage(ctx context.Context) error {

depth := ctx.Value(domain.ContextKeyDepth).(int)
msgId := ctx.Value(domain.ContextKeyMsgId).(string)
id := domain.ClientIdentifierFromContext(ctx)
id := utils.ClientIdentifierFromContext(ctx)

msg := messaging.ServerConnectedMessage{
Cluster: id.Cluster,
Expand Down Expand Up @@ -111,7 +111,7 @@ func (c *Client) VerifyObject(ctx context.Context, id domain.KindName, checksum
func (c *Client) sendDeleteObjectMessage(ctx context.Context, id domain.KindName) error {
depth := ctx.Value(domain.ContextKeyDepth).(int)
msgId := ctx.Value(domain.ContextKeyMsgId).(string)
cId := domain.ClientIdentifierFromContext(ctx)
cId := utils.ClientIdentifierFromContext(ctx)

msg := messaging.DeleteObjectMessage{
Cluster: cId.Cluster,
Expand All @@ -138,7 +138,7 @@ func (c *Client) sendDeleteObjectMessage(ctx context.Context, id domain.KindName
func (c *Client) sendGetObjectMessage(ctx context.Context, id domain.KindName, baseObject []byte) error {
depth := ctx.Value(domain.ContextKeyDepth).(int)
msgId := ctx.Value(domain.ContextKeyMsgId).(string)
cId := domain.ClientIdentifierFromContext(ctx)
cId := utils.ClientIdentifierFromContext(ctx)

msg := messaging.GetObjectMessage{
BaseObject: baseObject,
Expand Down Expand Up @@ -167,7 +167,7 @@ func (c *Client) sendGetObjectMessage(ctx context.Context, id domain.KindName, b
func (c *Client) sendPatchObjectMessage(ctx context.Context, id domain.KindName, checksum string, patch []byte) error {
depth := ctx.Value(domain.ContextKeyDepth).(int)
msgId := ctx.Value(domain.ContextKeyMsgId).(string)
cId := domain.ClientIdentifierFromContext(ctx)
cId := utils.ClientIdentifierFromContext(ctx)

msg := messaging.PatchObjectMessage{
Checksum: checksum,
Expand Down Expand Up @@ -198,7 +198,7 @@ func (c *Client) sendPatchObjectMessage(ctx context.Context, id domain.KindName,
func (c *Client) sendPutObjectMessage(ctx context.Context, id domain.KindName, object []byte) error {
depth := ctx.Value(domain.ContextKeyDepth).(int)
msgId := ctx.Value(domain.ContextKeyMsgId).(string)
cId := domain.ClientIdentifierFromContext(ctx)
cId := utils.ClientIdentifierFromContext(ctx)

msg := messaging.PutObjectMessage{
Cluster: cId.Cluster,
Expand Down Expand Up @@ -227,7 +227,7 @@ func (c *Client) sendPutObjectMessage(ctx context.Context, id domain.KindName, o
func (c *Client) sendVerifyObjectMessage(ctx context.Context, id domain.KindName, checksum string) error {
depth := ctx.Value(domain.ContextKeyDepth).(int)
msgId := ctx.Value(domain.ContextKeyMsgId).(string)
cId := domain.ClientIdentifierFromContext(ctx)
cId := utils.ClientIdentifierFromContext(ctx)

msg := messaging.VerifyObjectMessage{
Checksum: checksum,
Expand Down
15 changes: 8 additions & 7 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,22 +55,23 @@ func (r Resource) String() string {

// LoadConfig reads configuration from file or environment variables.
func LoadConfig(path string) (Config, error) {
v := viper.New() // singleton prevents running tests in parallel
if configPathFromEnv := os.Getenv("CONFIG"); configPathFromEnv != "" {
viper.AddConfigPath(configPathFromEnv)
v.AddConfigPath(configPathFromEnv)
}
viper.AddConfigPath(path)
viper.SetConfigName("config")
viper.SetConfigType("json")
v.AddConfigPath(path)
v.SetConfigName("config")
v.SetConfigType("json")

viper.AutomaticEnv()
v.AutomaticEnv()

err := viper.ReadInConfig()
err := v.ReadInConfig()
if err != nil {
return Config{}, err
}

var config Config
err = viper.Unmarshal(&config)
err = v.Unmarshal(&config)
return config, err
}

Expand Down
204 changes: 204 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
package config

import (
"os"
"testing"

"github.com/armosec/armoapi-go/armotypes"
"github.com/armosec/utils-k8s-go/armometadata"
"github.com/kubescape/backend/pkg/servicediscovery/schema"
v2 "github.com/kubescape/backend/pkg/servicediscovery/v2"
pulsarconfig "github.com/kubescape/messaging/pulsar/config"
"github.com/kubescape/synchronizer/domain"
"github.com/stretchr/testify/assert"
"k8s.io/utils/ptr"
)

func TestLoadClusterConfig(t *testing.T) {
tests := []struct {
name string
env map[string]string
want armometadata.ClusterConfig
}{
{
name: "cluster config",
env: map[string]string{"CLUSTER_CONFIG": "../configuration/clusterData.json"},
want: armometadata.ClusterConfig{
ClusterName: "kind",
GatewayWebsocketURL: "gateway:8001",
GatewayRestURL: "gateway:8002",
KubevulnURL: "kubevuln:8080",
KubescapeURL: "kubescape:8080",
InstallationData: armotypes.InstallationData{
StorageEnabled: ptr.To[bool](true),
RelevantImageVulnerabilitiesEnabled: ptr.To[bool](false),
RelevantImageVulnerabilitiesConfiguration: "disable",
Namespace: "kubescape",
ImageVulnerabilitiesScanningEnabled: ptr.To[bool](false),
PostureScanEnabled: ptr.To[bool](false),
OtelCollectorEnabled: ptr.To[bool](true),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for k, v := range tt.env {
err := os.Setenv(k, v)
assert.NoError(t, err)
}
got, err := LoadClusterConfig()
assert.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}

func TestLoadConfig(t *testing.T) {
tests := []struct {
name string
path string
want Config
}{
{
name: "client config",
path: "../configuration/client",
want: Config{
InCluster: InCluster{
ServerUrl: "ws://127.0.0.1:8080/",
ClusterName: "cluster-1",
Account: "11111111-2222-3333-4444-11111111",
AccessKey: "xxxxxxxx-1111-1111-1111-xxxxxxxx",
Resources: []Resource{
{Group: "apps", Version: "v1", Resource: "deployments", Strategy: "patch"},
{Group: "", Version: "v1", Resource: "pods", Strategy: "patch"},
{Group: "spdx.softwarecomposition.kubescape.io", Version: "v1beta1", Resource: "sbomspdxv2p3s", Strategy: "copy"},
{Group: "spdx.softwarecomposition.kubescape.io", Version: "v1beta1", Resource: "sbomspdxv2p3filtereds", Strategy: "copy"},
},
},
},
},
{
name: "server config",
path: "../configuration/server",
want: Config{
Backend: Backend{
AuthenticationServer: &AuthenticationServerConfig{
Url: "https://api.armosec.io/api/v1",
HeaderToQueryParamMapping: map[string]string{"x-api-account": "customerGUID"},
HeaderToHeaderMapping: map[string]string{"x-api-key": "X-API-KEY"},
},
Subscription: "subscription",
PulsarConfig: &pulsarconfig.PulsarConfig{
URL: "pulsar://localhost:6650",
Tenant: "kubescape",
Namespace: "kubescape",
AdminUrl: "http://localhost:8081",
Clusters: []string{"standalone"},
RedeliveryDelaySeconds: 0,
MaxDeliveryAttempts: 2,
},
Topic: "synchronizer",
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := LoadConfig(tt.path)
assert.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}

func TestLoadServiceURLs(t *testing.T) {
tests := []struct {
name string
env map[string]string
filePath string
want schema.IBackendServices
}{
{
name: "via filePath",
filePath: "../configuration/services.json",
want: &v2.ServicesV2{
EventReceiverHttpUrl: "https://er-test.com",
EventReceiverWebsocketUrl: "wss://er-test.com",
GatewayUrl: "https://gw.test.com",
ApiServerUrl: "https://api.test.com",
MetricsUrl: "https://metrics.test.com",
SynchronizerUrl: "wss://synchronizer.test.com",
},
},
{
name: "via env",
env: map[string]string{"SERVICES": "../configuration/services.json"},
want: &v2.ServicesV2{
EventReceiverHttpUrl: "https://er-test.com",
EventReceiverWebsocketUrl: "wss://er-test.com",
GatewayUrl: "https://gw.test.com",
ApiServerUrl: "https://api.test.com",
MetricsUrl: "https://metrics.test.com",
SynchronizerUrl: "wss://synchronizer.test.com",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for k, v := range tt.env {
err := os.Setenv(k, v)
assert.NoError(t, err)
}
got, err := LoadServiceURLs(tt.filePath)
assert.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}

func TestResource_String(t *testing.T) {
type fields struct {
Group string
Version string
Resource string
Strategy domain.Strategy
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "deployments",
fields: fields{
Group: "apps",
Version: "v1",
Resource: "deployments",
},
want: "apps/v1/deployments",
},
{
name: "pods",
fields: fields{
Group: "",
Version: "v1",
Resource: "pods",
},
want: "/v1/pods",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := Resource{
Group: tt.fields.Group,
Version: tt.fields.Version,
Resource: tt.fields.Resource,
Strategy: tt.fields.Strategy,
}
if got := r.String(); got != tt.want {
t.Errorf("String() = %v, want %v", got, tt.want)
}
})
}
}
23 changes: 23 additions & 0 deletions configuration/clusterData.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"serviceDiscovery": true,
"gatewayWebsocketURL": "gateway:8001",
"gatewayRestURL": "gateway:8002",
"vulnScanURL": "kubevuln:8080",
"kubevulnURL": "kubevuln:8080",
"kubescapeURL": "kubescape:8080",
"triggerNewImageScan": "false",
"clusterName": "kind",
"storage": true,
"relevantImageVulnerabilitiesEnabled": false,
"namespace": "kubescape",
"imageVulnerabilitiesScanningEnabled": false,
"postureScanEnabled": false,
"otelCollector": true,
"nodeAgent": "false",
"maxImageSize": 5.36870912e+09,
"keepLocal": false,
"scanTimeout": "5m",
"vexGeneration": false,
"continuousPostureScan": false,
"relevantImageVulnerabilitiesConfiguration": "disable"
}
11 changes: 11 additions & 0 deletions configuration/services.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"version": "v2",
"response": {
"event-receiver-http": "https://er-test.com",
"event-receiver-ws": "wss://er-test.com",
"gateway": "https://gw.test.com",
"api-server": "https://api.test.com",
"metrics": "https://metrics.test.com",
"synchronizer": "wss://synchronizer.test.com"
}
}

0 comments on commit ae18fb1

Please sign in to comment.