Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
application_test.go 6.92 KiB
package integration_test_application

import (
	"context"
	"fmt"
	"os"
	"testing"

	"code.fbi.h-da.de/danet/gosdn/api/go/gosdn/conflict"
	mnepb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/networkelement"
	apb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/rbac"
	tpb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/transport"
	"code.fbi.h-da.de/danet/gosdn/application-framework/event"
	integration_test_utils "code.fbi.h-da.de/danet/gosdn/integration-tests/integrationTestUtils"
	"github.com/stretchr/testify/assert"

	"google.golang.org/grpc"
)

// Notes:
//When adding tests take into account all the messages that get added to the message
// queue during test setups. So make sure to read from the eventChannel of the application accordingly!
//
// Do not reset test setup in this because it causes weird interactions with the test cases that are hard
// to deal with when writing actual test cases.

const targetAAdress = "gnmi-target_A:7030"
const targetUserAndPW = "admin"
const pndID = "5f20f34b-cbd0-4511-9ddc-c50cf6a3b49d"
const pluginID = "d1c269a2-6482-4010-b0d8-679dff73153b"
const mneID = "9ee7bf15-15ff-44b8-aafa-035487d1e97f"

const userID = "23224223-aeb6-433b-a797-2d671d7424f0"
const roleID = "679f7982-d740-452e-b78d-c1d133233694"

// The connection to the controller to use in each test.
var conn *grpc.ClientConn

// The context containing the credentials when authenticated.
var ctx context.Context

// A defaultSDN config with default/empty values.
var defaultSDNConfig string

var application *Application

func TestMain(m *testing.M) {
	localConn, localCtx, err := integration_test_utils.CreateSecureConnection()
	if err != nil {
		fmt.Println(err.Error())
	}
	conn = localConn
	ctx = localCtx

	sndConfig, err := integration_test_utils.ExportCurrentSDNConfig(conn, ctx)
	defaultSDNConfig = sndConfig
	if err != nil {
		fmt.Println(err.Error())
	}

	integration_test_utils.ApplySDNConfig(conn, ctx, defaultSDNConfig)
	integration_test_utils.CleanUserAndRolesExceptAdmin(conn, ctx)

	topics := []event.Topic{event.ManagedNetworkElement, event.User, event.Role}

	rabbitMQAddress := ""
	envVarRabbitmq := os.Getenv("RABBITMQ")
	if envVarRabbitmq != "" {
		rabbitMQAddress = envVarRabbitmq
	}

	application = NewApplication(ctx, conn, ":55055", topics, rabbitMQAddress)

	eventTypeCallbackTuples := []event.TypeToCallbackTuple{
		{
			Type:     event.Add,
			Callback: application.callback,
		},
		{
			Type:     event.Update,
			Callback: application.callback,
		},
		{
			Type:     event.Delete,
			Callback: application.callback,
		},
		{
			Type:     event.Subscribe,
			Callback: application.callback,
		},
	}
	go application.Run(eventTypeCallbackTuples)

	// This is needed to clear the go channel of the messages sent by RabbitMQ when creating
	// and logging in with the admin user.
	// Important note: only works once after starting the setup, because first time use creates
	// a user and updates it because of the login. After then only logins are done, no user creations.
	// This means that this will block after trying once, because the two attempts to read from eventChannel.

	_ = <-application.eventChannel
	_ = <-application.eventChannel
	_ = <-application.eventChannel

	m.Run()
}

func TestNetworkElementAddAndSubscribeEvent(t *testing.T) {
	// setup required parameters
	opt := &tpb.TransportOption{
		Address:  targetAAdress,
		Username: targetUserAndPW,
		Password: targetUserAndPW,
		TransportOption: &tpb.TransportOption_GnmiTransportOption{
			GnmiTransportOption: &tpb.GnmiTransportOption{},
		},
		Tls: true,
	}

	addListRequest := &mnepb.AddListRequest{
		Timestamp: integration_test_utils.GetTimestamp(),
		Mne: []*mnepb.SetMne{
			{
				MneId:           mneID,
				Address:         "gnmi-target_A:7030",
				Pid:             pndID,
				PluginId:        pluginID,
				MneName:         "Horst",
				TransportOption: opt,
			},
		},
		Pid: pndID,
	}

	// setup gRPC services
	mneService := mnepb.NewNetworkElementServiceClient(conn)

	// add one device to the controller
	_, err := mneService.AddList(ctx, addListRequest)
	if err != nil {
		t.Error(err)
		t.FailNow()
	}

	// check if events are available and correct type and content
	addEvent := <-application.eventChannel
	assert.Equal(t, event.Add.String(), addEvent.Type)
	assert.Equal(t, mneID, addEvent.EntityID.String())

	subscribeEvent := <-application.eventChannel
	assert.Equal(t, event.Subscribe.String(), subscribeEvent.Type)

	subscribeEvent = <-application.eventChannel
	assert.Equal(t, event.Subscribe.String(), subscribeEvent.Type)
}

func TestUserAddAndUpdateEvent(t *testing.T) {
	// setup required parameters
	addUserRequest := &apb.CreateUsersRequest{
		Timestamp: integration_test_utils.GetTimestamp(),
		User: []*apb.User{
			{
				Id:       userID,
				Name:     "user",
				Roles:    map[string]string{pndID: "admin"},
				Password: targetUserAndPW,
				Metadata: &conflict.Metadata{
					ResourceVersion: 0,
				},
			},
		},
	}

	updateUserRequest := &apb.UpdateUsersRequest{
		Timestamp: integration_test_utils.GetTimestamp(),
		User: []*apb.UpdateUser{
			{
				Id:       userID,
				Name:     "new name",
				Metadata: &conflict.Metadata{},
			},
		},
	}

	// setup gRPC services
	userService := apb.NewUserServiceClient(conn)

	// add one device to the controller
	_, err := userService.CreateUsers(ctx, addUserRequest)
	if err != nil {
		t.Error(err)
		t.FailNow()
	}

	// check if event is available and correct type
	addEvent := <-application.eventChannel
	assert.Equal(t, event.Add.String(), addEvent.Type)
	assert.Equal(t, userID, addEvent.EntityID.String())

	// update user and check for event
	_, err = userService.UpdateUsers(ctx, updateUserRequest)
	if err != nil {
		t.Error(err)
		t.FailNow()
	}

	updateEvent := <-application.eventChannel
	assert.Equal(t, event.Update.String(), updateEvent.Type)
	assert.Equal(t, userID, updateEvent.EntityID.String())
}
func TestRoleAddAndDeleteEvent(t *testing.T) {
	// setup required parameters
	const roleName = "new role"

	addRoleRequest := &apb.CreateRolesRequest{
		Timestamp: integration_test_utils.GetTimestamp(),
		Roles: []*apb.Role{
			{
				Id:          roleID,
				Name:        roleName,
				Description: "well, not much to see here",
				Permissions: []string{"some permission"},
			},
		},
	}

	deleteRoleRequest := &apb.DeleteRolesRequest{
		Timestamp: integration_test_utils.GetTimestamp(),
		RoleName:  []string{roleName},
	}

	// setup gRPC services
	roleService := apb.NewRoleServiceClient(conn)

	// add role and check add event
	_, err := roleService.CreateRoles(ctx, addRoleRequest)
	if err != nil {
		t.Error(err)
		t.FailNow()
	}

	addEvent := <-application.eventChannel
	assert.Equal(t, event.Add.String(), addEvent.Type)
	assert.Equal(t, roleID, addEvent.EntityID.String())

	// delete new role and check for event
	_, err = roleService.DeleteRoles(ctx, deleteRoleRequest)
	if err != nil {
		t.Error(err)
		t.FailNow()
	}

	deleteEvent := <-application.eventChannel
	assert.Equal(t, event.Delete.String(), deleteEvent.Type)
	assert.Equal(t, roleID, deleteEvent.EntityID.String())
}