From 70b2ded851924eb2cb35c9eee8419c3d8173f49d Mon Sep 17 00:00:00 2001 From: Sonja Happ Date: Thu, 19 Mar 2020 10:50:18 +0100 Subject: [PATCH] modularize main function, use DBpool instead of local DB in database package and all testing functions --- database/database.go | 56 ++--- database/database_test.go | 221 +++++++++--------- database/testdata.go | 27 ++- routes/component-configuration/config_test.go | 30 ++- routes/dashboard/dashboard_test.go | 30 ++- routes/file/file_test.go | 30 ++- routes/healthz/healthz_test.go | 12 +- routes/infrastructure-component/ic_test.go | 54 +++-- routes/metrics/metrics_endpoint.go | 6 +- routes/scenario/scenario_test.go | 54 +++-- routes/signal/signal_test.go | 30 ++- routes/user/user_test.go | 54 +++-- routes/widget/widget_test.go | 30 ++- start.go | 144 +++++++----- 14 files changed, 393 insertions(+), 385 deletions(-) diff --git a/database/database.go b/database/database.go index c271d48..c10bbf9 100644 --- a/database/database.go +++ b/database/database.go @@ -34,29 +34,29 @@ import ( var DBpool *gorm.DB // database used by backend // Initialize connection to the database -func InitDB(cfg *config.Config) (*gorm.DB, error) { +func InitDB(cfg *config.Config) error { name, err := cfg.String("db.name") if err != nil { - return nil, err + return err } host, err := cfg.String("db.host") if err != nil { - return nil, err + return err } user, err := cfg.String("db.user") if err != nil && !strings.Contains(err.Error(), "Required setting 'db.user' not set") { - return nil, err + return err } pass := "" if user != "" { pass, err = cfg.String("db.pass") if err != nil { - return nil, err + return err } } sslmode, err := cfg.String("db.ssl") if err != nil { - return nil, err + return err } dbinfo := fmt.Sprintf("host=%s sslmode=%s dbname=%s", host, sslmode, name) @@ -66,14 +66,14 @@ func InitDB(cfg *config.Config) (*gorm.DB, error) { db, err := gorm.Open("postgres", dbinfo) if err != nil { - return nil, err + return err } DBpool = db - MigrateModels(db) + MigrateModels() log.Println("Database connection established") - return db, nil + return nil } // Connection pool to already opened DB @@ -84,27 +84,27 @@ func GetDB() *gorm.DB { // Drop all the tables of the database // TODO: Remove that function from the codebase and substitute the body // to the Dummy*() where it is called -func DropTables(db *gorm.DB) { - db.DropTableIfExists(&InfrastructureComponent{}) - db.DropTableIfExists(&Signal{}) - db.DropTableIfExists(&ComponentConfiguration{}) - db.DropTableIfExists(&File{}) - db.DropTableIfExists(&Scenario{}) - db.DropTableIfExists(&User{}) - db.DropTableIfExists(&Dashboard{}) - db.DropTableIfExists(&Widget{}) +func DropTables() { + DBpool.DropTableIfExists(&InfrastructureComponent{}) + DBpool.DropTableIfExists(&Signal{}) + DBpool.DropTableIfExists(&ComponentConfiguration{}) + DBpool.DropTableIfExists(&File{}) + DBpool.DropTableIfExists(&Scenario{}) + DBpool.DropTableIfExists(&User{}) + DBpool.DropTableIfExists(&Dashboard{}) + DBpool.DropTableIfExists(&Widget{}) // The following statement deletes the many to many relationship between users and scenarios - db.DropTableIfExists("user_scenarios") + DBpool.DropTableIfExists("user_scenarios") } // AutoMigrate the models -func MigrateModels(db *gorm.DB) { - db.AutoMigrate(&InfrastructureComponent{}) - db.AutoMigrate(&Signal{}) - db.AutoMigrate(&ComponentConfiguration{}) - db.AutoMigrate(&File{}) - db.AutoMigrate(&Scenario{}) - db.AutoMigrate(&User{}) - db.AutoMigrate(&Dashboard{}) - db.AutoMigrate(&Widget{}) +func MigrateModels() { + DBpool.AutoMigrate(&InfrastructureComponent{}) + DBpool.AutoMigrate(&Signal{}) + DBpool.AutoMigrate(&ComponentConfiguration{}) + DBpool.AutoMigrate(&File{}) + DBpool.AutoMigrate(&Scenario{}) + DBpool.AutoMigrate(&User{}) + DBpool.AutoMigrate(&Dashboard{}) + DBpool.AutoMigrate(&Widget{}) } diff --git a/database/database_test.go b/database/database_test.go index 2ff39aa..b4ad508 100644 --- a/database/database_test.go +++ b/database/database_test.go @@ -23,7 +23,6 @@ package database import ( "fmt" - "github.com/jinzhu/gorm" "log" "os" "testing" @@ -32,33 +31,31 @@ import ( "github.com/stretchr/testify/assert" ) -var db *gorm.DB - func TestMain(m *testing.M) { err := configuration.InitConfig() if err != nil { panic(m) } - db, err = InitDB(configuration.GolbalConfig) + err = InitDB(configuration.GolbalConfig) if err != nil { panic(m) } // Verify that you can connect to the database - err = db.DB().Ping() + err = DBpool.DB().Ping() if err != nil { log.Panic("Error: DB must ping to run tests") } - defer db.Close() + defer DBpool.Close() os.Exit(m.Run()) } func TestUserAssociations(t *testing.T) { - DropTables(db) - MigrateModels(db) + DropTables() + MigrateModels() // create copies of global test data scenarioA := ScenarioA @@ -68,28 +65,28 @@ func TestUserAssociations(t *testing.T) { userB := UserB // add three users to DB - assert.NoError(t, db.Create(&user0).Error) // Admin - assert.NoError(t, db.Create(&userA).Error) // Normal User - assert.NoError(t, db.Create(&userB).Error) // Normal User + assert.NoError(t, DBpool.Create(&user0).Error) // Admin + assert.NoError(t, DBpool.Create(&userA).Error) // Normal User + assert.NoError(t, DBpool.Create(&userB).Error) // Normal User // add two scenarios to DB - assert.NoError(t, db.Create(&scenarioA).Error) - assert.NoError(t, db.Create(&scenarioB).Error) + assert.NoError(t, DBpool.Create(&scenarioA).Error) + assert.NoError(t, DBpool.Create(&scenarioB).Error) // add many-to-many associations between users and scenarios // User HM Scenarios, Scenario HM Users (Many-to-Many) - assert.NoError(t, db.Model(&userA).Association("Scenarios").Append(&scenarioA).Error) - assert.NoError(t, db.Model(&userA).Association("Scenarios").Append(&scenarioB).Error) - assert.NoError(t, db.Model(&userB).Association("Scenarios").Append(&scenarioA).Error) - assert.NoError(t, db.Model(&userB).Association("Scenarios").Append(&scenarioB).Error) + assert.NoError(t, DBpool.Model(&userA).Association("Scenarios").Append(&scenarioA).Error) + assert.NoError(t, DBpool.Model(&userA).Association("Scenarios").Append(&scenarioB).Error) + assert.NoError(t, DBpool.Model(&userB).Association("Scenarios").Append(&scenarioA).Error) + assert.NoError(t, DBpool.Model(&userB).Association("Scenarios").Append(&scenarioB).Error) var usr1 User - assert.NoError(t, db.Find(&usr1, "ID = ?", 2).Error, fmt.Sprintf("Find User with ID=2")) + assert.NoError(t, DBpool.Find(&usr1, "ID = ?", 2).Error, fmt.Sprintf("Find User with ID=2")) assert.EqualValues(t, "User_A", usr1.Username) // Get scenarios of usr1 var scenarios []Scenario - assert.NoError(t, db.Model(&usr1).Related(&scenarios, "Scenarios").Error) + assert.NoError(t, DBpool.Model(&usr1).Related(&scenarios, "Scenarios").Error) if len(scenarios) != 2 { assert.Fail(t, "User Associations", "Expected to have %v Scenarios. Has %v.", 2, len(scenarios)) @@ -98,8 +95,8 @@ func TestUserAssociations(t *testing.T) { func TestScenarioAssociations(t *testing.T) { - DropTables(db) - MigrateModels(db) + DropTables() + MigrateModels() // create copies of global test data scenarioA := ScenarioA @@ -113,44 +110,44 @@ func TestScenarioAssociations(t *testing.T) { dashboardB := DashboardB // add scenarios to DB - assert.NoError(t, db.Create(&scenarioA).Error) - assert.NoError(t, db.Create(&scenarioB).Error) + assert.NoError(t, DBpool.Create(&scenarioA).Error) + assert.NoError(t, DBpool.Create(&scenarioB).Error) // add users to DB - assert.NoError(t, db.Create(&user0).Error) // Admin - assert.NoError(t, db.Create(&userA).Error) // Normal User - assert.NoError(t, db.Create(&userB).Error) // Normal User + assert.NoError(t, DBpool.Create(&user0).Error) // Admin + assert.NoError(t, DBpool.Create(&userA).Error) // Normal User + assert.NoError(t, DBpool.Create(&userB).Error) // Normal User // add component configurations to DB - assert.NoError(t, db.Create(&configA).Error) - assert.NoError(t, db.Create(&configB).Error) + assert.NoError(t, DBpool.Create(&configA).Error) + assert.NoError(t, DBpool.Create(&configB).Error) // add dashboards to DB - assert.NoError(t, db.Create(&dashboardA).Error) - assert.NoError(t, db.Create(&dashboardB).Error) + assert.NoError(t, DBpool.Create(&dashboardA).Error) + assert.NoError(t, DBpool.Create(&dashboardB).Error) // add many-to-many associations between users and scenarios // User HM Scenarios, Scenario HM Users (Many-to-Many) - assert.NoError(t, db.Model(&scenarioA).Association("Users").Append(&userA).Error) - assert.NoError(t, db.Model(&scenarioA).Association("Users").Append(&userB).Error) - assert.NoError(t, db.Model(&scenarioB).Association("Users").Append(&userA).Error) - assert.NoError(t, db.Model(&scenarioB).Association("Users").Append(&userB).Error) + assert.NoError(t, DBpool.Model(&scenarioA).Association("Users").Append(&userA).Error) + assert.NoError(t, DBpool.Model(&scenarioA).Association("Users").Append(&userB).Error) + assert.NoError(t, DBpool.Model(&scenarioB).Association("Users").Append(&userA).Error) + assert.NoError(t, DBpool.Model(&scenarioB).Association("Users").Append(&userB).Error) // add scenario has many component configurations associations - assert.NoError(t, db.Model(&scenarioA).Association("ComponentConfigurations").Append(&configA).Error) - assert.NoError(t, db.Model(&scenarioA).Association("ComponentConfigurations").Append(&configB).Error) + assert.NoError(t, DBpool.Model(&scenarioA).Association("ComponentConfigurations").Append(&configA).Error) + assert.NoError(t, DBpool.Model(&scenarioA).Association("ComponentConfigurations").Append(&configB).Error) // Scenario HM Dashboards - assert.NoError(t, db.Model(&scenarioA).Association("Dashboards").Append(&dashboardA).Error) - assert.NoError(t, db.Model(&scenarioA).Association("Dashboards").Append(&dashboardB).Error) + assert.NoError(t, DBpool.Model(&scenarioA).Association("Dashboards").Append(&dashboardA).Error) + assert.NoError(t, DBpool.Model(&scenarioA).Association("Dashboards").Append(&dashboardB).Error) var scenario1 Scenario - assert.NoError(t, db.Find(&scenario1, 1).Error, fmt.Sprintf("Find Scenario with ID=1")) + assert.NoError(t, DBpool.Find(&scenario1, 1).Error, fmt.Sprintf("Find Scenario with ID=1")) assert.EqualValues(t, "Scenario_A", scenario1.Name) // Get users of scenario1 var users []User - assert.NoError(t, db.Model(&scenario1).Association("Users").Find(&users).Error) + assert.NoError(t, DBpool.Model(&scenario1).Association("Users").Find(&users).Error) if len(users) != 2 { assert.Fail(t, "Scenario Associations", "Expected to have %v Users. Has %v.", 2, len(users)) @@ -158,7 +155,7 @@ func TestScenarioAssociations(t *testing.T) { // Get component configurations of scenario1 var configs []ComponentConfiguration - assert.NoError(t, db.Model(&scenario1).Related(&configs, "ComponentConfigurations").Error) + assert.NoError(t, DBpool.Model(&scenario1).Related(&configs, "ComponentConfigurations").Error) if len(configs) != 2 { assert.Fail(t, "Scenario Associations", "Expected to have %v component configs. Has %v.", 2, len(configs)) @@ -166,7 +163,7 @@ func TestScenarioAssociations(t *testing.T) { // Get dashboards of scenario1 var dashboards []Dashboard - assert.NoError(t, db.Model(&scenario1).Related(&dashboards, "Dashboards").Error) + assert.NoError(t, DBpool.Model(&scenario1).Related(&dashboards, "Dashboards").Error) if len(dashboards) != 2 { assert.Fail(t, "Scenario Associations", "Expected to have %v Dashboards. Has %v.", 2, len(dashboards)) @@ -175,8 +172,8 @@ func TestScenarioAssociations(t *testing.T) { func TestICAssociations(t *testing.T) { - DropTables(db) - MigrateModels(db) + DropTables() + MigrateModels() // create copies of global test data icA := ICA @@ -185,24 +182,24 @@ func TestICAssociations(t *testing.T) { configB := ConfigB // add ICs to DB - assert.NoError(t, db.Create(&icA).Error) - assert.NoError(t, db.Create(&icB).Error) + assert.NoError(t, DBpool.Create(&icA).Error) + assert.NoError(t, DBpool.Create(&icB).Error) // add component configurations to DB - assert.NoError(t, db.Create(&configA).Error) - assert.NoError(t, db.Create(&configB).Error) + assert.NoError(t, DBpool.Create(&configA).Error) + assert.NoError(t, DBpool.Create(&configB).Error) // add IC has many component configurations association to DB - assert.NoError(t, db.Model(&icA).Association("ComponentConfigurations").Append(&configA).Error) - assert.NoError(t, db.Model(&icA).Association("ComponentConfigurations").Append(&configB).Error) + assert.NoError(t, DBpool.Model(&icA).Association("ComponentConfigurations").Append(&configA).Error) + assert.NoError(t, DBpool.Model(&icA).Association("ComponentConfigurations").Append(&configB).Error) var ic1 InfrastructureComponent - assert.NoError(t, db.Find(&ic1, 1).Error, fmt.Sprintf("Find InfrastructureComponent with ID=1")) + assert.NoError(t, DBpool.Find(&ic1, 1).Error, fmt.Sprintf("Find InfrastructureComponent with ID=1")) assert.EqualValues(t, "Host_A", ic1.Host) // Get Component Configurations of ic1 var configs []ComponentConfiguration - assert.NoError(t, db.Model(&ic1).Association("ComponentConfigurations").Find(&configs).Error) + assert.NoError(t, DBpool.Model(&ic1).Association("ComponentConfigurations").Find(&configs).Error) if len(configs) != 2 { assert.Fail(t, "InfrastructureComponent Associations", "Expected to have %v Component Configurations. Has %v.", 2, len(configs)) @@ -211,8 +208,8 @@ func TestICAssociations(t *testing.T) { func TestComponentConfigurationAssociations(t *testing.T) { - DropTables(db) - MigrateModels(db) + DropTables() + MigrateModels() // create copies of global test data configA := ConfigA @@ -229,41 +226,41 @@ func TestComponentConfigurationAssociations(t *testing.T) { icB := ICB // add Component Configurations to DB - assert.NoError(t, db.Create(&configA).Error) - assert.NoError(t, db.Create(&configB).Error) + assert.NoError(t, DBpool.Create(&configA).Error) + assert.NoError(t, DBpool.Create(&configB).Error) // add signals to DB - assert.NoError(t, db.Create(&outSignalA).Error) - assert.NoError(t, db.Create(&outSignalB).Error) - assert.NoError(t, db.Create(&inSignalA).Error) - assert.NoError(t, db.Create(&inSignalB).Error) + assert.NoError(t, DBpool.Create(&outSignalA).Error) + assert.NoError(t, DBpool.Create(&outSignalB).Error) + assert.NoError(t, DBpool.Create(&inSignalA).Error) + assert.NoError(t, DBpool.Create(&inSignalB).Error) // add files to DB - assert.NoError(t, db.Create(&fileA).Error) - assert.NoError(t, db.Create(&fileB).Error) - assert.NoError(t, db.Create(&fileC).Error) - assert.NoError(t, db.Create(&fileD).Error) + assert.NoError(t, DBpool.Create(&fileA).Error) + assert.NoError(t, DBpool.Create(&fileB).Error) + assert.NoError(t, DBpool.Create(&fileC).Error) + assert.NoError(t, DBpool.Create(&fileD).Error) // add ICs to DB - assert.NoError(t, db.Create(&icA).Error) - assert.NoError(t, db.Create(&icB).Error) + assert.NoError(t, DBpool.Create(&icA).Error) + assert.NoError(t, DBpool.Create(&icB).Error) // add Component Configuration has many signals associations - assert.NoError(t, db.Model(&configA).Association("InputMapping").Append(&inSignalA).Error) - assert.NoError(t, db.Model(&configA).Association("InputMapping").Append(&inSignalB).Error) - assert.NoError(t, db.Model(&configA).Association("OutputMapping").Append(&outSignalA).Error) - assert.NoError(t, db.Model(&configA).Association("OutputMapping").Append(&outSignalB).Error) + assert.NoError(t, DBpool.Model(&configA).Association("InputMapping").Append(&inSignalA).Error) + assert.NoError(t, DBpool.Model(&configA).Association("InputMapping").Append(&inSignalB).Error) + assert.NoError(t, DBpool.Model(&configA).Association("OutputMapping").Append(&outSignalA).Error) + assert.NoError(t, DBpool.Model(&configA).Association("OutputMapping").Append(&outSignalB).Error) // add Component Configuration has many files associations - assert.NoError(t, db.Model(&configA).Association("Files").Append(&fileC).Error) - assert.NoError(t, db.Model(&configA).Association("Files").Append(&fileD).Error) + assert.NoError(t, DBpool.Model(&configA).Association("Files").Append(&fileC).Error) + assert.NoError(t, DBpool.Model(&configA).Association("Files").Append(&fileD).Error) // associate Component Configurations with IC - assert.NoError(t, db.Model(&icA).Association("ComponentConfigurations").Append(&configA).Error) - assert.NoError(t, db.Model(&icA).Association("ComponentConfigurations").Append(&configB).Error) + assert.NoError(t, DBpool.Model(&icA).Association("ComponentConfigurations").Append(&configA).Error) + assert.NoError(t, DBpool.Model(&icA).Association("ComponentConfigurations").Append(&configB).Error) var config1 ComponentConfiguration - assert.NoError(t, db.Find(&config1, 1).Error, fmt.Sprintf("Find ComponentConfiguration with ID=1")) + assert.NoError(t, DBpool.Find(&config1, 1).Error, fmt.Sprintf("Find ComponentConfiguration with ID=1")) assert.EqualValues(t, ConfigA.Name, config1.Name) // Check IC ID @@ -273,7 +270,7 @@ func TestComponentConfigurationAssociations(t *testing.T) { // Get OutputMapping signals of config1 var signals []Signal - assert.NoError(t, db.Model(&config1).Where("Direction = ?", "out").Related(&signals, "OutputMapping").Error) + assert.NoError(t, DBpool.Model(&config1).Where("Direction = ?", "out").Related(&signals, "OutputMapping").Error) if len(signals) != 2 { assert.Fail(t, "ComponentConfiguration Associations", "Expected to have %v Output Signals. Has %v.", 2, len(signals)) @@ -281,7 +278,7 @@ func TestComponentConfigurationAssociations(t *testing.T) { // Get files of config1 var files []File - assert.NoError(t, db.Model(&config1).Related(&files, "Files").Error) + assert.NoError(t, DBpool.Model(&config1).Related(&files, "Files").Error) if len(files) != 2 { assert.Fail(t, "ComponentConfiguration Associations", "Expected to have %v Files. Has %v.", 2, len(files)) @@ -290,8 +287,8 @@ func TestComponentConfigurationAssociations(t *testing.T) { func TestDashboardAssociations(t *testing.T) { - DropTables(db) - MigrateModels(db) + DropTables() + MigrateModels() // create copies of global test data dashboardA := DashboardA @@ -300,24 +297,24 @@ func TestDashboardAssociations(t *testing.T) { widgetB := WidgetB // add dashboards to DB - assert.NoError(t, db.Create(&dashboardA).Error) - assert.NoError(t, db.Create(&dashboardB).Error) + assert.NoError(t, DBpool.Create(&dashboardA).Error) + assert.NoError(t, DBpool.Create(&dashboardB).Error) // add widgets to DB - assert.NoError(t, db.Create(&widgetA).Error) - assert.NoError(t, db.Create(&widgetB).Error) + assert.NoError(t, DBpool.Create(&widgetA).Error) + assert.NoError(t, DBpool.Create(&widgetB).Error) // add dashboard has many widgets associations to DB - assert.NoError(t, db.Model(&dashboardA).Association("Widgets").Append(&widgetA).Error) - assert.NoError(t, db.Model(&dashboardA).Association("Widgets").Append(&widgetB).Error) + assert.NoError(t, DBpool.Model(&dashboardA).Association("Widgets").Append(&widgetA).Error) + assert.NoError(t, DBpool.Model(&dashboardA).Association("Widgets").Append(&widgetB).Error) var dashboard1 Dashboard - assert.NoError(t, db.Find(&dashboard1, 1).Error, fmt.Sprintf("Find Dashboard with ID=1")) + assert.NoError(t, DBpool.Find(&dashboard1, 1).Error, fmt.Sprintf("Find Dashboard with ID=1")) assert.EqualValues(t, "Dashboard_A", dashboard1.Name) //Get widgets of dashboard1 var widgets []Widget - assert.NoError(t, db.Model(&dashboard1).Related(&widgets, "Widgets").Error) + assert.NoError(t, DBpool.Model(&dashboard1).Related(&widgets, "Widgets").Error) if len(widgets) != 2 { assert.Fail(t, "Dashboard Associations", "Expected to have %v Widget. Has %v.", 2, len(widgets)) @@ -326,8 +323,8 @@ func TestDashboardAssociations(t *testing.T) { func TestWidgetAssociations(t *testing.T) { - DropTables(db) - MigrateModels(db) + DropTables() + MigrateModels() // create copies of global test data widgetA := WidgetA @@ -338,26 +335,26 @@ func TestWidgetAssociations(t *testing.T) { fileD := FileD // add widgets to DB - assert.NoError(t, db.Create(&widgetA).Error) - assert.NoError(t, db.Create(&widgetB).Error) + assert.NoError(t, DBpool.Create(&widgetA).Error) + assert.NoError(t, DBpool.Create(&widgetB).Error) // add files to DB - assert.NoError(t, db.Create(&fileA).Error) - assert.NoError(t, db.Create(&fileB).Error) - assert.NoError(t, db.Create(&fileC).Error) - assert.NoError(t, db.Create(&fileD).Error) + assert.NoError(t, DBpool.Create(&fileA).Error) + assert.NoError(t, DBpool.Create(&fileB).Error) + assert.NoError(t, DBpool.Create(&fileC).Error) + assert.NoError(t, DBpool.Create(&fileD).Error) // add widget has many files associations to DB - assert.NoError(t, db.Model(&widgetA).Association("Files").Append(&fileA).Error) - assert.NoError(t, db.Model(&widgetA).Association("Files").Append(&fileB).Error) + assert.NoError(t, DBpool.Model(&widgetA).Association("Files").Append(&fileA).Error) + assert.NoError(t, DBpool.Model(&widgetA).Association("Files").Append(&fileB).Error) var widget1 Widget - assert.NoError(t, db.Find(&widget1, 1).Error, fmt.Sprintf("Find Widget with ID=1")) + assert.NoError(t, DBpool.Find(&widget1, 1).Error, fmt.Sprintf("Find Widget with ID=1")) assert.EqualValues(t, widgetA.Name, widget1.Name) // Get files of widget var files []File - assert.NoError(t, db.Model(&widget1).Related(&files, "Files").Error) + assert.NoError(t, DBpool.Model(&widget1).Related(&files, "Files").Error) if len(files) != 2 { assert.Fail(t, "Widget Associations", "Expected to have %v Files. Has %v.", 2, len(files)) @@ -366,8 +363,8 @@ func TestWidgetAssociations(t *testing.T) { func TestFileAssociations(t *testing.T) { - DropTables(db) - MigrateModels(db) + DropTables() + MigrateModels() // create copies of global test data fileA := FileA @@ -376,26 +373,26 @@ func TestFileAssociations(t *testing.T) { fileD := FileD // add files to DB - assert.NoError(t, db.Create(&fileA).Error) - assert.NoError(t, db.Create(&fileB).Error) - assert.NoError(t, db.Create(&fileC).Error) - assert.NoError(t, db.Create(&fileD).Error) + assert.NoError(t, DBpool.Create(&fileA).Error) + assert.NoError(t, DBpool.Create(&fileB).Error) + assert.NoError(t, DBpool.Create(&fileC).Error) + assert.NoError(t, DBpool.Create(&fileD).Error) var file1 File - assert.NoError(t, db.Find(&file1, 1).Error, fmt.Sprintf("Find File with ID=1")) + assert.NoError(t, DBpool.Find(&file1, 1).Error, fmt.Sprintf("Find File with ID=1")) assert.EqualValues(t, "File_A", file1.Name) } func TestAddAdmin(t *testing.T) { - DropTables(db) - MigrateModels(db) + DropTables() + MigrateModels() - assert.NoError(t, DBAddAdminUser(db)) + assert.NoError(t, DBAddAdminUser()) } func TestAddAdminAndUsers(t *testing.T) { - DropTables(db) - MigrateModels(db) + DropTables() + MigrateModels() - assert.NoError(t, DBAddAdminAndUserAndGuest(db)) + assert.NoError(t, DBAddAdminAndUserAndGuest()) } diff --git a/database/testdata.go b/database/testdata.go index fa42aaf..9cf3841 100644 --- a/database/testdata.go +++ b/database/testdata.go @@ -27,7 +27,6 @@ import ( "fmt" "git.rwth-aachen.de/acs/public/villas/web-backend-go/helper" "github.com/gin-gonic/gin" - "github.com/jinzhu/gorm" "github.com/jinzhu/gorm/dialects/postgres" "golang.org/x/crypto/bcrypt" "io" @@ -306,26 +305,26 @@ var WidgetE = Widget{ SignalIDs: []int64{4}, } -func DBAddAdminUser(db *gorm.DB) error { - db.AutoMigrate(&User{}) +func DBAddAdminUser() error { + DBpool.AutoMigrate(&User{}) // Check if admin user exists in DB var users []User - err := db.Where("Role = ?", "Admin").Find(&users).Error + err := DBpool.Where("Role = ?", "Admin").Find(&users).Error if len(users) == 0 { fmt.Println("No admin user found in DB, adding default admin user.") //create a copy of global test data user0 := User0 // add admin user to DB - err = db.Create(&user0).Error + err = DBpool.Create(&user0).Error } return err } -func DBAddAdminAndUserAndGuest(db *gorm.DB) error { - db.AutoMigrate(&User{}) +func DBAddAdminAndUserAndGuest() error { + DBpool.AutoMigrate(&User{}) //create a copy of global test data user0 := User0 @@ -334,22 +333,22 @@ func DBAddAdminAndUserAndGuest(db *gorm.DB) error { userC := UserC // add admin user to DB - err := db.Create(&user0).Error + err := DBpool.Create(&user0).Error // add normal users to DB - err = db.Create(&userA).Error - err = db.Create(&userB).Error + err = DBpool.Create(&userA).Error + err = DBpool.Create(&userB).Error // add guest user to DB - err = db.Create(&userC).Error + err = DBpool.Create(&userC).Error return err } // Populates DB with test data -func DBAddTestData(db *gorm.DB, basePath string, router *gin.Engine) error { +func DBAddTestData(basePath string, router *gin.Engine) error { - MigrateModels(db) + MigrateModels() // Create entries of each model (data defined in testdata.go) // add Admin user - err := DBAddAdminUser(db) + err := DBAddAdminUser() if err != nil { return err } diff --git a/routes/component-configuration/config_test.go b/routes/component-configuration/config_test.go index 41bb5f5..e7f9c77 100644 --- a/routes/component-configuration/config_test.go +++ b/routes/component-configuration/config_test.go @@ -30,7 +30,6 @@ import ( "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/scenario" "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/user" "github.com/gin-gonic/gin" - "github.com/jinzhu/gorm" "github.com/jinzhu/gorm/dialects/postgres" "github.com/stretchr/testify/assert" "os" @@ -38,7 +37,6 @@ import ( ) var router *gin.Engine -var db *gorm.DB var base_api_configs = "/api/configs" var base_api_auth = "/api/authenticate" @@ -124,11 +122,11 @@ func TestMain(m *testing.M) { panic(m) } - db, err = database.InitDB(configuration.GolbalConfig) + err = database.InitDB(configuration.GolbalConfig) if err != nil { panic(m) } - defer db.Close() + defer database.DBpool.Close() router = gin.Default() api := router.Group("/api") @@ -147,9 +145,9 @@ func TestMain(m *testing.M) { } func TestAddConfig(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // prepare the content of the DB for testing // by adding a scenario and a IC to the DB @@ -243,9 +241,9 @@ func TestAddConfig(t *testing.T) { func TestUpdateConfig(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // prepare the content of the DB for testing // by adding a scenario and a IC to the DB @@ -355,9 +353,9 @@ func TestUpdateConfig(t *testing.T) { } func TestDeleteConfig(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // prepare the content of the DB for testing // by adding a scenario and a IC to the DB @@ -428,9 +426,9 @@ func TestDeleteConfig(t *testing.T) { } func TestGetAllConfigsOfScenario(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // prepare the content of the DB for testing // by adding a scenario and a IC to the DB diff --git a/routes/dashboard/dashboard_test.go b/routes/dashboard/dashboard_test.go index 79fe931..3040323 100644 --- a/routes/dashboard/dashboard_test.go +++ b/routes/dashboard/dashboard_test.go @@ -29,7 +29,6 @@ import ( "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/scenario" "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/user" "github.com/gin-gonic/gin" - "github.com/jinzhu/gorm" "github.com/jinzhu/gorm/dialects/postgres" "github.com/stretchr/testify/assert" "log" @@ -38,7 +37,6 @@ import ( ) var router *gin.Engine -var db *gorm.DB type DashboardRequest struct { Name string `json:"name,omitempty"` @@ -81,11 +79,11 @@ func TestMain(m *testing.M) { if err != nil { panic(m) } - db, err = database.InitDB(configuration.GolbalConfig) + err = database.InitDB(configuration.GolbalConfig) if err != nil { panic(m) } - defer db.Close() + defer database.DBpool.Close() router = gin.Default() api := router.Group("/api") @@ -101,9 +99,9 @@ func TestMain(m *testing.M) { } func TestAddDashboard(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -187,9 +185,9 @@ func TestAddDashboard(t *testing.T) { } func TestUpdateDashboard(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -268,9 +266,9 @@ func TestUpdateDashboard(t *testing.T) { } func TestDeleteDashboard(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -341,9 +339,9 @@ func TestDeleteDashboard(t *testing.T) { } func TestGetAllDashboardsOfScenario(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, diff --git a/routes/file/file_test.go b/routes/file/file_test.go index cbe1d1a..30c3a5b 100644 --- a/routes/file/file_test.go +++ b/routes/file/file_test.go @@ -34,7 +34,6 @@ import ( "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/user" "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/widget" "github.com/gin-gonic/gin" - "github.com/jinzhu/gorm" "github.com/jinzhu/gorm/dialects/postgres" "github.com/stretchr/testify/assert" "io" @@ -47,7 +46,6 @@ import ( ) var router *gin.Engine -var db *gorm.DB type ConfigRequest struct { Name string `json:"name,omitempty"` @@ -185,11 +183,11 @@ func TestMain(m *testing.M) { if err != nil { panic(m) } - db, err = database.InitDB(configuration.GolbalConfig) + err = database.InitDB(configuration.GolbalConfig) if err != nil { panic(m) } - defer db.Close() + defer database.DBpool.Close() router = gin.Default() api := router.Group("/api") @@ -218,9 +216,9 @@ func TestMain(m *testing.M) { } func TestAddFile(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // prepare the content of the DB for testing // using the respective endpoints of the API @@ -334,9 +332,9 @@ func TestAddFile(t *testing.T) { func TestUpdateFile(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // prepare the content of the DB for testing // using the respective endpoints of the API @@ -468,9 +466,9 @@ func TestUpdateFile(t *testing.T) { } func TestDeleteFile(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // prepare the content of the DB for testing // using the respective endpoints of the API @@ -619,9 +617,9 @@ func TestDeleteFile(t *testing.T) { func TestGetAllFilesOfConfig(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // prepare the content of the DB for testing // using the respective endpoints of the API diff --git a/routes/healthz/healthz_test.go b/routes/healthz/healthz_test.go index 415a89c..9b175de 100644 --- a/routes/healthz/healthz_test.go +++ b/routes/healthz/healthz_test.go @@ -27,7 +27,6 @@ import ( "git.rwth-aachen.de/acs/public/villas/web-backend-go/database" "git.rwth-aachen.de/acs/public/villas/web-backend-go/helper" "github.com/gin-gonic/gin" - "github.com/jinzhu/gorm" "github.com/stretchr/testify/assert" "net/http" @@ -35,23 +34,22 @@ import ( ) var router *gin.Engine -var db *gorm.DB func TestHealthz(t *testing.T) { err := configuration.InitConfig() assert.NoError(t, err) // connect DB - db, err = database.InitDB(configuration.GolbalConfig) + err = database.InitDB(configuration.GolbalConfig) assert.NoError(t, err) - defer db.Close() + defer database.DBpool.Close() router = gin.Default() RegisterHealthzEndpoint(router.Group("/healthz")) // close db connection - err = db.Close() + err = database.DBpool.Close() assert.NoError(t, err) // test healthz endpoint for unconnected DB and AMQP client @@ -60,9 +58,9 @@ func TestHealthz(t *testing.T) { assert.Equalf(t, 500, code, "Response body: \n%v\n", resp) // reconnect DB - db, err = database.InitDB(configuration.GolbalConfig) + err = database.InitDB(configuration.GolbalConfig) assert.NoError(t, err) - defer db.Close() + defer database.DBpool.Close() // test healthz endpoint for connected DB and unconnected AMQP client code, resp, err = helper.TestEndpoint(router, "", "healthz", http.MethodGet, nil) diff --git a/routes/infrastructure-component/ic_test.go b/routes/infrastructure-component/ic_test.go index 58ff248..d303c84 100644 --- a/routes/infrastructure-component/ic_test.go +++ b/routes/infrastructure-component/ic_test.go @@ -24,7 +24,6 @@ package infrastructure_component import ( "fmt" "git.rwth-aachen.de/acs/public/villas/web-backend-go/helper" - "github.com/jinzhu/gorm" "github.com/jinzhu/gorm/dialects/postgres" "github.com/stretchr/testify/assert" "os" @@ -38,7 +37,6 @@ import ( ) var router *gin.Engine -var db *gorm.DB type ICRequest struct { UUID string `json:"uuid,omitempty"` @@ -54,11 +52,11 @@ func TestMain(m *testing.M) { panic(m) } - db, err = database.InitDB(configuration.GolbalConfig) + err = database.InitDB(configuration.GolbalConfig) if err != nil { panic(m) } - defer db.Close() + defer database.DBpool.Close() router = gin.Default() api := router.Group("/api") @@ -71,9 +69,9 @@ func TestMain(m *testing.M) { } func TestAddICAsAdmin(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -138,9 +136,9 @@ func TestAddICAsAdmin(t *testing.T) { } func TestAddICAsUser(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as user token, err := helper.AuthenticateForTest(router, @@ -165,9 +163,9 @@ func TestAddICAsUser(t *testing.T) { } func TestUpdateICAsAdmin(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -227,9 +225,9 @@ func TestUpdateICAsAdmin(t *testing.T) { } func TestUpdateICAsUser(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -269,9 +267,9 @@ func TestUpdateICAsUser(t *testing.T) { } func TestDeleteICAsAdmin(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -319,9 +317,9 @@ func TestDeleteICAsAdmin(t *testing.T) { } func TestDeleteICAsUser(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -360,9 +358,9 @@ func TestDeleteICAsUser(t *testing.T) { } func TestGetAllICs(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -421,9 +419,9 @@ func TestGetAllICs(t *testing.T) { } func TestGetConfigsOfIC(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, diff --git a/routes/metrics/metrics_endpoint.go b/routes/metrics/metrics_endpoint.go index 4d37606..37779b9 100644 --- a/routes/metrics/metrics_endpoint.go +++ b/routes/metrics/metrics_endpoint.go @@ -22,9 +22,9 @@ package metrics import ( + "git.rwth-aachen.de/acs/public/villas/web-backend-go/database" "github.com/chenjiandongx/ginprom" "github.com/gin-gonic/gin" - "github.com/jinzhu/gorm" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) @@ -111,9 +111,11 @@ func RegisterMetricsEndpoint(rg *gin.RouterGroup) { ) } -func InitCounters(db *gorm.DB) { +func InitCounters() { var infrastructure_components, component_configurations, files, scenarios, users, dashboards float64 + db := database.GetDB() + db.Table("infrastructure_components").Count(&infrastructure_components) db.Table("component_configurations").Count(&component_configurations) db.Table("files").Count(&files) diff --git a/routes/scenario/scenario_test.go b/routes/scenario/scenario_test.go index 0b82407..14c82db 100644 --- a/routes/scenario/scenario_test.go +++ b/routes/scenario/scenario_test.go @@ -28,7 +28,6 @@ import ( "git.rwth-aachen.de/acs/public/villas/web-backend-go/helper" "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/user" "github.com/gin-gonic/gin" - "github.com/jinzhu/gorm" "github.com/jinzhu/gorm/dialects/postgres" "github.com/stretchr/testify/assert" "os" @@ -36,7 +35,6 @@ import ( ) var router *gin.Engine -var db *gorm.DB type ScenarioRequest struct { Name string `json:"name,omitempty"` @@ -58,11 +56,11 @@ func TestMain(m *testing.M) { panic(m) } - db, err = database.InitDB(configuration.GolbalConfig) + err = database.InitDB(configuration.GolbalConfig) if err != nil { panic(m) } - defer db.Close() + defer database.DBpool.Close() router = gin.Default() api := router.Group("/api") @@ -79,9 +77,9 @@ func TestMain(m *testing.M) { func TestAddScenario(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) newScenario := ScenarioRequest{ Name: database.ScenarioA.Name, @@ -181,9 +179,9 @@ func TestAddScenario(t *testing.T) { func TestUpdateScenario(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -251,9 +249,9 @@ func TestUpdateScenario(t *testing.T) { func TestGetAllScenariosAsAdmin(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -312,9 +310,9 @@ func TestGetAllScenariosAsAdmin(t *testing.T) { func TestGetAllScenariosAsUser(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as normal userB token, err := helper.AuthenticateForTest(router, @@ -369,9 +367,9 @@ func TestGetAllScenariosAsUser(t *testing.T) { func TestDeleteScenario(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -441,9 +439,9 @@ func TestDeleteScenario(t *testing.T) { func TestAddUserToScenario(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -521,9 +519,9 @@ func TestAddUserToScenario(t *testing.T) { func TestGetAllUsersOfScenario(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -606,9 +604,9 @@ func TestGetAllUsersOfScenario(t *testing.T) { func TestRemoveUserFromScenario(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, diff --git a/routes/signal/signal_test.go b/routes/signal/signal_test.go index 3670e7d..48546c8 100644 --- a/routes/signal/signal_test.go +++ b/routes/signal/signal_test.go @@ -31,7 +31,6 @@ import ( "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/scenario" "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/user" "github.com/gin-gonic/gin" - "github.com/jinzhu/gorm" "github.com/jinzhu/gorm/dialects/postgres" "github.com/stretchr/testify/assert" "os" @@ -39,7 +38,6 @@ import ( ) var router *gin.Engine -var db *gorm.DB type SignalRequest struct { Name string `json:"name,omitempty"` @@ -132,11 +130,11 @@ func TestMain(m *testing.M) { panic(m) } - db, err = database.InitDB(configuration.GolbalConfig) + err = database.InitDB(configuration.GolbalConfig) if err != nil { panic(m) } - defer db.Close() + defer database.DBpool.Close() router = gin.Default() api := router.Group("/api") @@ -158,9 +156,9 @@ func TestMain(m *testing.M) { } func TestAddSignal(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // prepare the content of the DB for testing // by adding a scenario and a IC to the DB @@ -253,9 +251,9 @@ func TestAddSignal(t *testing.T) { } func TestUpdateSignal(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // prepare the content of the DB for testing // by adding a scenario and a IC to the DB @@ -355,9 +353,9 @@ func TestUpdateSignal(t *testing.T) { } func TestDeleteSignal(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // prepare the content of the DB for testing // by adding a scenario and a IC to the DB @@ -450,9 +448,9 @@ func TestDeleteSignal(t *testing.T) { } func TestGetAllInputSignalsOfConfig(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // prepare the content of the DB for testing // by adding a scenario and a IC to the DB diff --git a/routes/user/user_test.go b/routes/user/user_test.go index 87b2020..1d87f27 100644 --- a/routes/user/user_test.go +++ b/routes/user/user_test.go @@ -32,7 +32,6 @@ import ( "testing" "github.com/gin-gonic/gin" - "github.com/jinzhu/gorm" "github.com/stretchr/testify/assert" "git.rwth-aachen.de/acs/public/villas/web-backend-go/configuration" @@ -40,7 +39,6 @@ import ( ) var router *gin.Engine -var db *gorm.DB type UserRequest struct { Username string `json:"username,omitempty"` @@ -57,11 +55,11 @@ func TestMain(m *testing.M) { panic(m) } - db, err = database.InitDB(configuration.GolbalConfig) + err = database.InitDB(configuration.GolbalConfig) if err != nil { panic(m) } - defer db.Close() + defer database.DBpool.Close() router = gin.Default() api := router.Group("/api") @@ -74,9 +72,9 @@ func TestMain(m *testing.M) { } func TestAuthenticate(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // try to authenticate with non JSON body // should result in unauthorized @@ -134,9 +132,9 @@ func TestAuthenticate(t *testing.T) { func TestAddGetUser(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -258,9 +256,9 @@ func TestAddGetUser(t *testing.T) { func TestUsersNotAllowedActions(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -318,9 +316,9 @@ func TestUsersNotAllowedActions(t *testing.T) { func TestGetAllUsers(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -367,9 +365,9 @@ func TestGetAllUsers(t *testing.T) { func TestModifyAddedUserAsUser(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -524,9 +522,9 @@ func TestModifyAddedUserAsUser(t *testing.T) { func TestInvalidUserUpdate(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -597,9 +595,9 @@ func TestInvalidUserUpdate(t *testing.T) { func TestModifyAddedUserAsAdmin(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -716,9 +714,9 @@ func TestModifyAddedUserAsAdmin(t *testing.T) { func TestDeleteUser(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as admin token, err := helper.AuthenticateForTest(router, diff --git a/routes/widget/widget_test.go b/routes/widget/widget_test.go index 2bfc280..4814b6a 100644 --- a/routes/widget/widget_test.go +++ b/routes/widget/widget_test.go @@ -30,7 +30,6 @@ import ( "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/scenario" "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/user" "github.com/gin-gonic/gin" - "github.com/jinzhu/gorm" "github.com/jinzhu/gorm/dialects/postgres" "github.com/stretchr/testify/assert" "os" @@ -38,7 +37,6 @@ import ( ) var router *gin.Engine -var db *gorm.DB type WidgetRequest struct { Name string `json:"name,omitempty"` @@ -107,11 +105,11 @@ func TestMain(m *testing.M) { panic(m) } - db, err = database.InitDB(configuration.GolbalConfig) + err = database.InitDB(configuration.GolbalConfig) if err != nil { panic(m) } - defer db.Close() + defer database.DBpool.Close() router = gin.Default() api := router.Group("/api") @@ -130,9 +128,9 @@ func TestMain(m *testing.M) { } func TestAddWidget(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -230,9 +228,9 @@ func TestAddWidget(t *testing.T) { } func TestUpdateWidget(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -342,9 +340,9 @@ func TestUpdateWidget(t *testing.T) { } func TestDeleteWidget(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -419,9 +417,9 @@ func TestDeleteWidget(t *testing.T) { } func TestGetAllWidgetsOfDashboard(t *testing.T) { - database.DropTables(db) - database.MigrateModels(db) - assert.NoError(t, database.DBAddAdminAndUserAndGuest(db)) + database.DropTables() + database.MigrateModels() + assert.NoError(t, database.DBAddAdminAndUserAndGuest()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, diff --git a/start.go b/start.go index cf08a96..688780f 100644 --- a/start.go +++ b/start.go @@ -23,88 +23,80 @@ package main import ( "fmt" - "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/healthz" - "log" - "time" - - "git.rwth-aachen.de/acs/public/villas/web-backend-go/amqp" - "github.com/gin-gonic/gin" - ginSwagger "github.com/swaggo/gin-swagger" - "github.com/swaggo/gin-swagger/swaggerFiles" - - "git.rwth-aachen.de/acs/public/villas/web-backend-go/configuration" - "git.rwth-aachen.de/acs/public/villas/web-backend-go/database" - apidocs "git.rwth-aachen.de/acs/public/villas/web-backend-go/doc/api" // doc/api folder is used by Swag CLI, you have to import it - "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/component-configuration" + component_configuration "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/component-configuration" "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/dashboard" "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/file" - "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/infrastructure-component" - "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/metrics" + "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/healthz" + infrastructure_component "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/infrastructure-component" "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/scenario" "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/signal" "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/user" "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/widget" + ginSwagger "github.com/swaggo/gin-swagger" + "github.com/swaggo/gin-swagger/swaggerFiles" + "log" + "time" + + "git.rwth-aachen.de/acs/public/villas/web-backend-go/amqp" + "git.rwth-aachen.de/acs/public/villas/web-backend-go/configuration" + "git.rwth-aachen.de/acs/public/villas/web-backend-go/database" + apidocs "git.rwth-aachen.de/acs/public/villas/web-backend-go/doc/api" // doc/api folder is used by Swag CLI, you have to import it + "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/metrics" + "github.com/gin-gonic/gin" ) -// @title VILLASweb Backend API -// @version 2.0 -// @description This is the VILLASweb Backend API v2.0. -// @description Parts of this API are still in development. Please check the [VILLASweb-backend-go repository](https://git.rwth-aachen.de/acs/public/villas/web-backend-go) for more information. -// @description This documentation is auto-generated based on the API documentation in the code. The tool [swag](https://github.com/swaggo/swag) is used to auto-generate API docs for the [gin-gonic](https://github.com/gin-gonic/gin) framework. -// @contact.name Sonja Happ -// @contact.email sonja.happ@eonerc.rwth-aachen.de -// @license.name GNU GPL 3.0 -// @license.url http://www.gnu.de/documents/gpl-3.0.en.html -// @BasePath /api/v2 -func main() { - log.Println("Starting VILLASweb-backend-go") +func configureBackend() (string, string, string, string, string, error) { err := configuration.InitConfig() if err != nil { log.Printf("Error during initialization of global configuration: %v, aborting.", err.Error()) - return + return "", "", "", "", "", err } - db, err := database.InitDB(configuration.GolbalConfig) + + err = database.InitDB(configuration.GolbalConfig) if err != nil { log.Printf("Error during initialization of database: %v, aborting.", err.Error()) - return + return "", "", "", "", "", err } - defer db.Close() - m, err := configuration.GolbalConfig.String("mode") + mode, err := configuration.GolbalConfig.String("mode") if err != nil { log.Printf("Error reading mode from global configuration: %v, aborting.", err.Error()) - return + return "", "", "", "", "", err } - if m == "release" { + if mode == "release" { gin.SetMode(gin.ReleaseMode) } baseHost, err := configuration.GolbalConfig.String("base.host") if err != nil { log.Printf("Error reading base.host from global configuration: %v, aborting.", err.Error()) - return + return "", "", "", "", "", err } basePath, err := configuration.GolbalConfig.String("base.path") if err != nil { log.Printf("Error reading base.path from global configuration: %v, aborting.", err.Error()) - return + return "", "", "", "", "", err } port, err := configuration.GolbalConfig.String("port") if err != nil { log.Printf("Error reading port from global configuration: %v, aborting.", err.Error()) - return + return "", "", "", "", "", err } apidocs.SwaggerInfo.Host = baseHost apidocs.SwaggerInfo.BasePath = basePath - metrics.InitCounters(db) + metrics.InitCounters() - r := gin.Default() + AMQPurl, _ := configuration.GolbalConfig.String("amqp.url") - api := r.Group(basePath) + return mode, baseHost, basePath, port, AMQPurl, nil + +} + +func registerEndpoints(router *gin.Engine, api *gin.RouterGroup) { healthz.RegisterHealthzEndpoint(api.Group("/healthz")) metrics.RegisterMetricsEndpoint(api.Group("/metrics")) @@ -123,43 +115,42 @@ func main() { user.RegisterUserEndpoints(api.Group("/users")) infrastructure_component.RegisterICEndpoints(api.Group("/ic")) - r.GET("swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) + router.GET("swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) + +} + +func addData(router *gin.Engine, mode string, basePath string) error { - // add test data to DB if test mode is activated - mode, err := configuration.GolbalConfig.String("mode") - if err != nil { - fmt.Println(err.Error()) - fmt.Println("error: mode parameter missing in global configuration, aborting") - return - } if mode == "test" { // test mode: drop all tables and add test data to DB - database.DropTables(db) + database.DropTables() log.Println("Database tables dropped, adding test data to DB") - err = database.DBAddTestData(db, basePath, r) + err := database.DBAddTestData(basePath, router) if err != nil { fmt.Println(err.Error()) fmt.Println("error: testdata could not be added to DB, aborting") - panic(err) + return err } log.Println("Database initialized with test data") } else { // release mode: make sure that at least one admin user exists in DB - err = database.DBAddAdminUser(db) + err := database.DBAddAdminUser() if err != nil { fmt.Println(err.Error()) fmt.Println("error: adding admin user failed, aborting") - panic(err) + return err } } + return nil +} - amqpurl, _ := configuration.GolbalConfig.String("amqp.url") - if amqpurl != "" { +func connectAMQP(AMQPurl string, api *gin.RouterGroup) error { + if AMQPurl != "" { log.Println("Starting AMQP client") - err := amqp.ConnectAMQP(amqpurl) + err := amqp.ConnectAMQP(AMQPurl) if err != nil { - log.Panic(err) + return err } // register IC action endpoint only if AMQP client is used @@ -181,8 +172,45 @@ func main() { }() - log.Printf("Connected AMQP client to %s", amqpurl) + log.Printf("Connected AMQP client to %s", AMQPurl) } + + return nil +} + +// @title VILLASweb Backend API +// @version 2.0 +// @description This is the VILLASweb Backend API v2.0. +// @description Parts of this API are still in development. Please check the [VILLASweb-backend-go repository](https://git.rwth-aachen.de/acs/public/villas/web-backend-go) for more information. +// @description This documentation is auto-generated based on the API documentation in the code. The tool [swag](https://github.com/swaggo/swag) is used to auto-generate API docs for the [gin-gonic](https://github.com/gin-gonic/gin) framework. +// @contact.name Sonja Happ +// @contact.email sonja.happ@eonerc.rwth-aachen.de +// @license.name GNU GPL 3.0 +// @license.url http://www.gnu.de/documents/gpl-3.0.en.html +// @BasePath /api/v2 +func main() { + log.Println("Starting VILLASweb-backend-go") + + mode, _, basePath, port, amqpurl, err := configureBackend() + if err != nil { + panic(err) + } + defer database.DBpool.Close() + + r := gin.Default() + api := r.Group(basePath) + registerEndpoints(r, api) + + err = addData(r, mode, basePath) + if err != nil { + panic(err) + } + + err = connectAMQP(amqpurl, api) + if err != nil { + panic(err) + } + // server at port 4000 to match frontend's redirect path r.Run(":" + port) }