diff --git a/configuration/config.go b/configuration/config.go index 23de639..f44c044 100644 --- a/configuration/config.go +++ b/configuration/config.go @@ -61,6 +61,7 @@ func InitConfig() error { s3PathStyle = flag.Bool("s3-pathstyle", false, "Use path-style S3 API") jwtSecret = flag.String("jwt-secret", "This should NOT be here!!@33$8&", "The JSON Web Token secret") jwtExpiresAfter = flag.String("jwt-expires-after", "168h" /* 1 week */, "The time after which the JSON Web Token expires") + testDataPath = flag.String("test-data-path", "database/testdata.json", "The path to the test data json file (used in test mode)") ) flag.Parse() @@ -85,6 +86,7 @@ func InitConfig() error { "s3.region": *s3Region, "jwt.secret": *jwtSecret, "jwt.expires-after": *jwtExpiresAfter, + "test.datapath": *testDataPath, } if *s3NoSSL == true { @@ -122,6 +124,7 @@ func InitConfig() error { "S3_PATHSTYLE": "s3.pathstyle", "JWT_SECRET": "jwt.secret", "JWT_EXPIRES_AFTER": "jwt.expires-after", + "TEST_DATA_PATH": "test.datapath", } defaults := config.NewStatic(static) diff --git a/database/database.go b/database/database.go index 2dd0f27..e278746 100644 --- a/database/database.go +++ b/database/database.go @@ -23,8 +23,11 @@ package database import ( "fmt" + "golang.org/x/crypto/bcrypt" "log" + "math/rand" "strings" + "time" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" @@ -110,3 +113,58 @@ func MigrateModels() { DBpool.AutoMigrate(&Widget{}) DBpool.AutoMigrate(&Result{}) } + +// DBAddAdminUser adds a default admin user to the DB +func DBAddAdminUser(cfg *config.Config) (error, string) { + DBpool.AutoMigrate(User{}) + + // Check if admin user exists in DB + var users []User + err := DBpool.Where("Role = ?", "Admin").Find(&users).Error + adminPW := "" + + if len(users) == 0 { + fmt.Println("No admin user found in DB, adding default admin user.") + + name, err := cfg.String("admin.user") + if err != nil || name == "" { + name = "admin" + } + + adminPW, err = cfg.String("admin.pass") + if err != nil || adminPW == "" { + adminPW = generatePassword(16) + fmt.Printf(" Generated admin password: %s\n", adminPW) + } + + mail, err := cfg.String("admin.mail") + if err == nil || mail == "" { + mail = "admin@example.com" + } + + pwEnc, _ := bcrypt.GenerateFromPassword([]byte(adminPW), 10) + + // create a copy of global test data + user := User{Username: name, Password: string(pwEnc), + Role: "Admin", Mail: mail, Active: true} + + // add admin user to DB + err = DBpool.Create(&user).Error + } + + return err, adminPW +} + +func generatePassword(Len int) string { + rand.Seed(time.Now().UnixNano()) + chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + "abcdefghijklmnopqrstuvwxyz" + + "0123456789") + + var b strings.Builder + for i := 0; i < Len; i++ { + b.WriteRune(chars[rand.Intn(len(chars))]) + } + + return b.String() +} diff --git a/database/testdata.json b/database/testdata.json new file mode 100644 index 0000000..8a31c0f --- /dev/null +++ b/database/testdata.json @@ -0,0 +1,267 @@ +{ + "users": [ + { + "username": "User_0", + "password": "xyz789", + "role": "Admin", + "mail": "User_0@example.com" + }, + { + "username": "User_A", + "password": "abc123", + "role": "User", + "mail": "User_A@example.com" + }, + { + "username": "User_B", + "password": "bcd234", + "role": "User", + "mail": "User_B@example.com" + }, + { + "username": "User_C", + "password": "guestpw", + "role": "Guest", + "mail": "User_C@example.com" + } + ], + "ics": [ + { + "uuid": "7be0322d-354e-431e-84bd-ae4c9633138b", + "name": "ACS Demo Signals", + "type": "villas-node", + "category": "gateway", + "websocketurl": "https://villas.k8s.eonerc.rwth-aachen.de/ws/ws_sig", + "apiurl": "https://villas.k8s.eonerc.rwth-aachen.de/ws/api/v2", + "location": "K8S", + "description": "A signal generator for testing purposes", + "state": "idle", + "managedexternally": false, + "startparameterscheme": { + "param1": 42, + "param2": "testvalue" + } + }, + { + "uuid": "4854af30-325f-44a5-ad59-b67b2597de68", + "name": "Test DPsim Simulator", + "type": "dpsim", + "category": "simulator", + "location": "acs lab", + "description": "DPsim simulator", + "state": "running", + "managedexternally": true, + "startparameterscheme": { + "param1": 55, + "param2": "testvalue2" + } + } + ], + "scenarios": [ + { + "name": "Scenario_A", + "startParameters": { + "param1": "a nice param", + "param2": "a not so nice param" + } + }, + { + "name": "Scenario_B", + "startParameters": { + "param1": "another nice param", + "param2": "another not so nice param" + } + } + ], + "configs": [ + { + "name": "Example for Signal generator", + "startParameters": { + "param1": "nice param", + "param2": "not so nice" + }, + "fileIDs" : [] + }, + { + "name": "Example for DPsim simulator", + "startParameters": { + "param1": "cool thing", + "param2": "who needs this" + }, + "fileIDs" : [] + } + ], + "dashboards": [ + { + "name": "Dashboard_A", + "grid": 15 + }, + { + "name": "Dashboard_B", + "grid": 10 + } + + ], + "results": [ + { + "description": "Test run 1" + }, + { + "description": "Test run 2" + } + ], + "widgets": [ + { + "name": "MyLabel", + "type": "Label", + "width": 100, + "height": 50, + "minWidth": 40, + "minHeight": 80, + "x": 10, + "y": 10, + "z": 200, + "isLocked": false, + "signalIDs": [], + "customProperties": { + "textSize" : "20", + "fontColor" : "#4287f5", + "fontColor_opacity": 1 + } + }, + { + "name": "MySlider", + "type": "Slider", + "width": 400, + "height": 50, + "minWidth": 30, + "minHeight": 380, + "x": 70, + "y": 400, + "z": 0, + "isLocked": false, + "signalIDs": [], + "customProperties": { + "default_value" : 0, + "orientation" : 0, + "rangeMin" : 0, + "rangeMax": 200, + "rangeUseMinMax" : true, + "showUnit": true, + "continous_update": false, + "value": "", + "resizeLeftRightLock": false, + "resizeTopBottomLock": true, + "step": 0.1 + } + }, + { + "name": "MyBox", + "type": "Box", + "width": 200, + "height": 200, + "minWidth": 10, + "minHeight": 50, + "x": 300, + "y": 10, + "z": 0, + "isLocked": false, + "signalIDs": [], + "customProperties": { + "border_color" : "#4287f5", + "border_color_opacity": 1, + "background_color" : "#961520", + "background_color_opacity" : 1 + } + }, + { + "name": "MyButton", + "type": "Button", + "width": 100, + "height": 100, + "minWidth": 50, + "minHeight": 100, + "x": 10, + "y": 50, + "z": 0, + "isLocked": false, + "signalIDs": [], + "customProperties": { + "pressed": false, + "toggle" : false, + "on_value" : 1, + "off_value" : 0, + "background_color": "#961520", + "font_color": "#4287f5", + "border_color": "#4287f5", + "background_color_opacity": 1 + } + }, + { + "name": "MyLamp", + "type": "Lamp", + "width": 200, + "height": 20, + "minWidth": 10, + "minHeight": 50, + "x": 50, + "y": 300, + "z": 0, + "isLocked": false, + "signalIDs": [], + "customProperties": { + "on_color" : "#4287f5", + "off_color": "#961520", + "threshold" : 0.5, + "on_color_opacity": 1, + "off_color_opacity": 1 + } + } + ], + "signals": [ + { + "name": "outSignal_A", + "direction": "out", + "unit": "V", + "index": 1 + }, + { + "name": "outSignal_B", + "direction": "out", + "unit": "V", + "index": 2 + }, + { + "name": "outSignal_C", + "direction": "out", + "unit": "---", + "index": 3 + }, + { + "name": "outSignal_D", + "direction": "out", + "unit": "---", + "index": 4 + }, + { + "name": "outSignal_E", + "direction": "out", + "unit": "---", + "index": 5 + }, + { + "name": "inSignal_A", + "direction": "in", + "unit": "---", + "index": 1 + }, + { + "name": "inSignal_B", + "direction": "in", + "unit": "---", + "index": 2 + } + + ] + +} \ No newline at end of file diff --git a/helper/test_data.go b/helper/test_data.go index 6140e64..6ba8b94 100644 --- a/helper/test_data.go +++ b/helper/test_data.go @@ -24,20 +24,37 @@ package helper import ( "encoding/json" "fmt" - "math/rand" - "strings" - "time" - + "git.rwth-aachen.de/acs/public/villas/web-backend-go/configuration" "git.rwth-aachen.de/acs/public/villas/web-backend-go/database" "github.com/jinzhu/gorm/dialects/postgres" - "github.com/zpatrick/go-config" "golang.org/x/crypto/bcrypt" + "io/ioutil" + "log" + "os" ) // ####################################################################### // #################### Data used for testing ############################ // ####################################################################### +type jsonUser struct { + Username string + Password string + Mail string + Role string +} + +var GlobalTestData struct { + Users []jsonUser + ICs []database.InfrastructureComponent + Scenarios []database.Scenario + Results []database.Result + Configs []database.ComponentConfiguration + Dashboards []database.Dashboard + Widgets []database.Widget + Signals []database.Signal +} + // Credentials var StrPassword0 = "xyz789" var StrPasswordA = "abc123" @@ -46,13 +63,10 @@ var StrPasswordC = "guestpw" // Hash passwords with bcrypt algorithm var bcryptCost = 10 -var pw0, _ = bcrypt.GenerateFromPassword([]byte(StrPassword0), bcryptCost) var pwA, _ = bcrypt.GenerateFromPassword([]byte(StrPasswordA), bcryptCost) var pwB, _ = bcrypt.GenerateFromPassword([]byte(StrPasswordB), bcryptCost) var pwC, _ = bcrypt.GenerateFromPassword([]byte(StrPasswordC), bcryptCost) -var User0 = database.User{Username: "User_0", Password: string(pw0), - Role: "Admin", Mail: "User_0@example.com", Active: true} var UserA = database.User{Username: "User_A", Password: string(pwA), Role: "User", Mail: "User_A@example.com", Active: true} var UserB = database.User{Username: "User_B", Password: string(pwB), @@ -216,35 +230,6 @@ var DashboardB = database.Dashboard{ Grid: 10, } -// Files - -var FileA = database.File{ - Name: "File_A", - Type: "text/plain", - Size: 42, - Date: time.Now().String(), -} - -var FileB = database.File{ - Name: "File_B", - Type: "text/plain", - Size: 1234, - Date: time.Now().String(), -} - -var FileC = database.File{ - Name: "File_C", - Type: "text/plain", - Size: 32, - Date: time.Now().String(), -} -var FileD = database.File{ - Name: "File_D", - Type: "text/plain", - Size: 5000, - Date: time.Now().String(), -} - // Widgets var customPropertiesBox = json.RawMessage(`{"border_color" : "#4287f5", "border_color_opacity": 1, "background_color" : "#961520", "background_color_opacity" : 1}`) var customPropertiesSlider = json.RawMessage(`{"default_value" : 0, "orientation" : 0, "rangeUseMinMax": false, "rangeMin" : 0, "rangeMax": 200, "rangeUseMinMax" : true, "showUnit": true, "continous_update": false, "value": "", "resizeLeftRightLock": false, "resizeTopBottomLock": true, "step": 0.1 }`) @@ -327,84 +312,63 @@ var WidgetE = database.Widget{ SignalIDs: []int64{}, } -func generatePassword(Len int) string { - rand.Seed(time.Now().UnixNano()) - chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ" + - "abcdefghijklmnopqrstuvwxyz" + - "0123456789") +func ReadTestDataFromJson(path string) error { - var b strings.Builder - for i := 0; i < Len; i++ { - b.WriteRune(chars[rand.Intn(len(chars))]) + jsonFile, err := os.Open(path) + if err != nil { + return fmt.Errorf("error opening json file: %v", err) + } + log.Println("Successfully opened json data file", path) + + defer jsonFile.Close() + + byteValue, _ := ioutil.ReadAll(jsonFile) + + err = json.Unmarshal(byteValue, &GlobalTestData) + if err != nil { + return fmt.Errorf("error unmarshalling json: %v", err) } - return b.String() -} + log.Println(len(GlobalTestData.Users)) -// DBAddAdminUser adds a default admin user to the DB -func DBAddAdminUser(cfg *config.Config) error { - database.DBpool.AutoMigrate(&database.User{}) - - // Check if admin user exists in DB - var users []database.User - err := database.DBpool.Where("Role = ?", "Admin").Find(&users).Error - - if len(users) == 0 { - fmt.Println("No admin user found in DB, adding default admin user.") - - mode, err := cfg.String("mode") - - name, err := cfg.String("admin.user") - if (err != nil || name == "") && mode != "test" { - name = "admin" - } else if mode == "test" { - name = User0.Username - } - - pw, err := cfg.String("admin.pass") - if (err != nil || pw == "") && mode != "test" { - pw = generatePassword(16) - fmt.Printf(" Generated admin password: %s\n", pw) - } else if mode == "test" { - pw = StrPassword0 - } - - mail, err := cfg.String("admin.mail") - if (err == nil || mail == "") && mode != "test" { - mail = "admin@example.com" - } else if mode == "test" { - mail = User0.Mail - } - - pwEnc, _ := bcrypt.GenerateFromPassword([]byte(pw), bcryptCost) - - // create a copy of global test data - user := database.User{Username: name, Password: string(pwEnc), - Role: "Admin", Mail: mail, Active: true} - - // add admin user to DB - err = database.DBpool.Create(&user).Error - } - - return err + return nil } // add default admin user, normal users and a guest to the DB -func DBAddAdminAndUserAndGuest() error { - database.DBpool.AutoMigrate(&database.User{}) +func AddTestUsers() error { + + err := ReadTestDataFromJson("../../testdata/testdata.json") + if err != nil { + return err + } //create a copy of global test data - user0 := User0 - userA := UserA - userB := UserB - userC := UserC + if len(GlobalTestData.Users) == 0 { + return fmt.Errorf("no users in test data") + } - // add admin user to DB - err := database.DBpool.Create(&user0).Error - // add normal users to DB - err = database.DBpool.Create(&userA).Error - err = database.DBpool.Create(&userB).Error - // add guest user to DB - err = database.DBpool.Create(&userC).Error - return err + database.DBpool.AutoMigrate(&database.User{}) + err, _ = database.DBAddAdminUser(configuration.GlobalConfig) + if err != nil { + return err + } + + for _, user := range GlobalTestData.Users { + if user.Role != "Admin" { + // add users to DB that are not admin users + var newUser database.User + newUser.Username = user.Username + newUser.Role = user.Role + newUser.Mail = user.Mail + + pwEnc, _ := bcrypt.GenerateFromPassword([]byte(user.Password), 10) + newUser.Password = string(pwEnc) + err = database.DBpool.Create(&newUser).Error + if err != nil { + return err + } + } + } + + return nil } diff --git a/helper/test_utilities.go b/helper/test_utilities.go index a84e018..dd014bd 100644 --- a/helper/test_utilities.go +++ b/helper/test_utilities.go @@ -41,13 +41,13 @@ type KeyModels map[string]interface{} // ####################################################################### type Credentials struct { - Username string - Password string + Username string `json:"username,required"` + Password string `json:"password,required"` } var AdminCredentials = Credentials{ - Username: "User_0", - Password: StrPassword0, + Username: "admin", + Password: "xyz789", } var UserACredentials = Credentials{ diff --git a/routes/component-configuration/config_test.go b/routes/component-configuration/config_test.go index 1950896..2bbbd03 100644 --- a/routes/component-configuration/config_test.go +++ b/routes/component-configuration/config_test.go @@ -172,7 +172,7 @@ func TestMain(m *testing.M) { func TestAddConfig(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // prepare the content of the DB for testing // by adding a scenario and a IC to the DB @@ -268,7 +268,7 @@ func TestUpdateConfig(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // prepare the content of the DB for testing // by adding a scenario and a IC to the DB @@ -380,7 +380,7 @@ func TestUpdateConfig(t *testing.T) { func TestDeleteConfig(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // prepare the content of the DB for testing // by adding a scenario and a IC to the DB @@ -453,7 +453,7 @@ func TestDeleteConfig(t *testing.T) { func TestGetAllConfigsOfScenario(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // 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 a4c576b..6114db1 100644 --- a/routes/dashboard/dashboard_test.go +++ b/routes/dashboard/dashboard_test.go @@ -103,7 +103,7 @@ func TestMain(m *testing.M) { func TestAddDashboard(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -189,7 +189,7 @@ func TestAddDashboard(t *testing.T) { func TestUpdateDashboard(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -270,7 +270,7 @@ func TestUpdateDashboard(t *testing.T) { func TestDeleteDashboard(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -343,7 +343,7 @@ func TestDeleteDashboard(t *testing.T) { func TestGetAllDashboardsOfScenario(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, diff --git a/routes/file/file_test.go b/routes/file/file_test.go index 5f10771..55af5b3 100644 --- a/routes/file/file_test.go +++ b/routes/file/file_test.go @@ -106,7 +106,7 @@ func TestMain(m *testing.M) { func TestAddFile(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // prepare the content of the DB for testing // using the respective endpoints of the API @@ -207,7 +207,7 @@ func TestUpdateFile(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // prepare the content of the DB for testing // using the respective endpoints of the API @@ -340,7 +340,7 @@ func TestUpdateFile(t *testing.T) { func TestDeleteFile(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // prepare the content of the DB for testing // using the respective endpoints of the API @@ -477,7 +477,7 @@ func TestGetAllFilesOfScenario(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // prepare the content of the DB for testing // using the respective endpoints of the API diff --git a/routes/infrastructure-component/ic_test.go b/routes/infrastructure-component/ic_test.go index 186b9cb..49f01e0 100644 --- a/routes/infrastructure-component/ic_test.go +++ b/routes/infrastructure-component/ic_test.go @@ -119,7 +119,7 @@ func TestMain(m *testing.M) { func TestAddICAsAdmin(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // check AMQP connection err := CheckConnection() @@ -232,7 +232,7 @@ func TestAddICAsAdmin(t *testing.T) { func TestAddICAsUser(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as user token, err := helper.AuthenticateForTest(router, @@ -264,7 +264,7 @@ func TestAddICAsUser(t *testing.T) { func TestUpdateICAsAdmin(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -382,7 +382,7 @@ func TestUpdateICAsAdmin(t *testing.T) { func TestUpdateICAsUser(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -429,7 +429,7 @@ func TestUpdateICAsUser(t *testing.T) { func TestDeleteICAsAdmin(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -540,7 +540,7 @@ func TestDeleteICAsAdmin(t *testing.T) { func TestDeleteICAsUser(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -586,7 +586,7 @@ func TestDeleteICAsUser(t *testing.T) { func TestGetAllICs(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -658,7 +658,7 @@ func TestGetAllICs(t *testing.T) { func TestGetConfigsOfIC(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -719,7 +719,7 @@ func TestGetConfigsOfIC(t *testing.T) { func TestSendActionToIC(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -774,7 +774,7 @@ func TestCreateUpdateViaAMQPRecv(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -907,7 +907,7 @@ func TestDeleteICViaAMQPRecv(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as admin token, err := helper.AuthenticateForTest(router, diff --git a/routes/register.go b/routes/register.go index 10b86a1..abe94ff 100644 --- a/routes/register.go +++ b/routes/register.go @@ -26,6 +26,7 @@ import ( "bytes" "fmt" "io" + "log" "mime/multipart" "net/http" "net/http/httptest" @@ -87,221 +88,154 @@ func AddTestData(cfg *config.Config, router *gin.Engine) (*bytes.Buffer, error) } database.MigrateModels() - // Create entries of each model (data defined in test_data.go) - // add Admin user - err = helper.DBAddAdminUser(cfg) + + // add Admin user (defaults to User_0, xyz789) + err, adminpw := database.DBAddAdminUser(cfg) + + var Admin = helper.Credentials{ + Username: "admin", + Password: adminpw, + } + if err != nil { return nil, err } // authenticate as admin - token, err := helper.AuthenticateForTest(router, basePath+"/authenticate", "POST", helper.AdminCredentials) + token, err := helper.AuthenticateForTest(router, basePath+"/authenticate", "POST", Admin) if err != nil { return nil, err } - // add 2 normal and 1 guest user - code, resp, err := helper.TestEndpoint(router, token, basePath+"/users", "POST", helper.KeyModels{"user": helper.NewUserA}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding User_A") - } - code, resp, err = helper.TestEndpoint(router, token, basePath+"/users", "POST", helper.KeyModels{"user": helper.NewUserB}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding User_B") - } - code, resp, err = helper.TestEndpoint(router, token, basePath+"/users", "POST", helper.KeyModels{"user": helper.NewUserC}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding User_C") + // add users + for _, u := range helper.GlobalTestData.Users { + code, resp, err := helper.TestEndpoint(router, token, basePath+"/users", "POST", helper.KeyModels{"user": u}) + if code != http.StatusOK { + return resp, fmt.Errorf("error adding user %v: %v", u.Username, err) + } } // add infrastructure components - code, resp, err = helper.TestEndpoint(router, token, basePath+"/ic", "POST", helper.KeyModels{"ic": helper.ICA}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding IC A") - } - amqphost, err := cfg.String("amqp.host") - if err != nil && amqphost != "" { - code, resp, err = helper.TestEndpoint(router, token, basePath+"/ic", "POST", helper.KeyModels{"ic": helper.ICB}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding IC B") + amqphost, _ := cfg.String("amqp.host") + counterICs := 0 + log.Println("ICS", helper.GlobalTestData.ICs) + for _, i := range helper.GlobalTestData.ICs { + + if (i.ManagedExternally && amqphost != "") || !i.ManagedExternally { + code, resp, err := helper.TestEndpoint(router, token, basePath+"/ic", "POST", helper.KeyModels{"ic": i}) + if code != http.StatusOK { + return resp, fmt.Errorf("error adding IC %v: %v", i.Name, err) + } + counterICs++ } } // add scenarios - code, resp, err = helper.TestEndpoint(router, token, basePath+"/scenarios", "POST", helper.KeyModels{"scenario": helper.ScenarioA}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding Scenario A") - } - code, resp, err = helper.TestEndpoint(router, token, basePath+"/scenarios", "POST", helper.KeyModels{"scenario": helper.ScenarioB}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding Scenario B") + for _, s := range helper.GlobalTestData.Scenarios { + code, resp, err := helper.TestEndpoint(router, token, basePath+"/scenarios", "POST", helper.KeyModels{"scenario": s}) + if code != http.StatusOK { + return resp, fmt.Errorf("error adding Scenario %v: %v", s.Name, err) + } + + // add all users to the scenario + for _, u := range helper.GlobalTestData.Users { + code, resp, err := helper.TestEndpoint(router, token, fmt.Sprintf("%v/scenarios/1/user?username="+u.Username, basePath), "PUT", nil) + if code != http.StatusOK { + return resp, fmt.Errorf("error adding user %v to scenario %v: %v", u.Username, s.Name, err) + } + } } - // add users to scenario - code, resp, err = helper.TestEndpoint(router, token, fmt.Sprintf("%v/scenarios/1/user?username=User_A", basePath), "PUT", nil) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding User_A to Scenario A") - } - code, resp, err = helper.TestEndpoint(router, token, fmt.Sprintf("%v/scenarios/2/user?username=User_A", basePath), "PUT", nil) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding User_A to Scenario B") - } - code, resp, err = helper.TestEndpoint(router, token, fmt.Sprintf("%v/scenarios/2/user?username=User_B", basePath), "PUT", nil) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding User_B to Scenario B") - } - code, resp, err = helper.TestEndpoint(router, token, fmt.Sprintf("%v/scenarios/1/user?username=User_C", basePath), "PUT", nil) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding User_C to Scenario A") + // If there is at least one scenario and one IC in the test data, add component configs + configCounter := 0 + if len(helper.GlobalTestData.Scenarios) > 0 && counterICs > 0 { + + for _, c := range helper.GlobalTestData.Configs { + c.ScenarioID = 1 + c.ICID = 1 + code, resp, err := helper.TestEndpoint(router, token, basePath+"/configs", "POST", helper.KeyModels{"config": c}) + if code != http.StatusOK { + return resp, fmt.Errorf("error adding Config %v: %v", c.Name, err) + } + configCounter++ + } } - // add component configurations - configA := helper.ConfigA - configB := helper.ConfigB - configA.ScenarioID = 1 - configB.ScenarioID = 1 - configA.ICID = 1 - configB.ICID = 1 - code, resp, err = helper.TestEndpoint(router, token, basePath+"/configs", "POST", helper.KeyModels{"config": configA}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding Config A") - } - code, resp, err = helper.TestEndpoint(router, token, basePath+"/configs", "POST", helper.KeyModels{"config": configB}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding Config B") + // If there is at least one scenario, add dashboards and 2 test files + dashboardCounter := 0 + if len(helper.GlobalTestData.Scenarios) > 0 { + for _, d := range helper.GlobalTestData.Dashboards { + d.ScenarioID = 1 + code, resp, err := helper.TestEndpoint(router, token, basePath+"/dashboards", "POST", helper.KeyModels{"dashboard": d}) + if code != http.StatusOK { + return resp, fmt.Errorf("error adding Dashboard %v: %v", d.Name, err) + } + dashboardCounter++ + } + + // upload files + + // upload readme file + bodyBuf := &bytes.Buffer{} + bodyWriter := multipart.NewWriter(bodyBuf) + fileWriter, _ := bodyWriter.CreateFormFile("file", "Readme.md") + fh, _ := os.Open("README.md") + defer fh.Close() + + // io copy + _, err = io.Copy(fileWriter, fh) + contentType := bodyWriter.FormDataContentType() + bodyWriter.Close() + + // Create the request and add file to scenario + w1 := httptest.NewRecorder() + req1, _ := http.NewRequest("POST", basePath+"/files?scenarioID=1", bodyBuf) + req1.Header.Set("Content-Type", contentType) + req1.Header.Add("Authorization", "Bearer "+token) + router.ServeHTTP(w1, req1) + + // upload image file + bodyBuf = &bytes.Buffer{} + bodyWriter = multipart.NewWriter(bodyBuf) + fileWriter, _ = bodyWriter.CreateFormFile("file", "logo.png") + fh, _ = os.Open("doc/pictures/villas_web.png") + defer fh.Close() + + // io copy + _, err = io.Copy(fileWriter, fh) + contentType = bodyWriter.FormDataContentType() + bodyWriter.Close() + + // Create the request and add a second file to scenario + w2 := httptest.NewRecorder() + req2, _ := http.NewRequest("POST", basePath+"/files?scenarioID=1", bodyBuf) + req2.Header.Set("Content-Type", contentType) + req2.Header.Add("Authorization", "Bearer "+token) + router.ServeHTTP(w2, req2) + } - // add dashboards - dashboardA := helper.DashboardA - dashboardB := helper.DashboardB - dashboardA.ScenarioID = 1 - dashboardB.ScenarioID = 1 - code, resp, err = helper.TestEndpoint(router, token, basePath+"/dashboards", "POST", helper.KeyModels{"dashboard": dashboardA}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding Dashboard B") - } - code, resp, err = helper.TestEndpoint(router, token, basePath+"/dashboards", "POST", helper.KeyModels{"dashboard": dashboardB}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding Dashboard B") + // If there is at least one dashboard, add widgets + if dashboardCounter > 0 { + for _, w := range helper.GlobalTestData.Widgets { + w.DashboardID = 1 + code, resp, err := helper.TestEndpoint(router, token, basePath+"/widgets", "POST", helper.KeyModels{"widget": w}) + if code != http.StatusOK { + return resp, fmt.Errorf("error adding Widget %v: %v", w.Name, err) + } + } } - // add widgets - widgetA := helper.WidgetA - widgetB := helper.WidgetB - widgetC := helper.WidgetC - widgetD := helper.WidgetD - widgetE := helper.WidgetE - widgetA.DashboardID = 1 - widgetB.DashboardID = 1 - widgetC.DashboardID = 1 - widgetD.DashboardID = 1 - widgetE.DashboardID = 1 - code, resp, err = helper.TestEndpoint(router, token, basePath+"/widgets", "POST", helper.KeyModels{"widget": widgetA}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding Widget A") + // If there is at least one config, add signals + if configCounter > 0 { + for _, s := range helper.GlobalTestData.Signals { + s.ConfigID = 1 + code, resp, err := helper.TestEndpoint(router, token, basePath+"/signals", "POST", helper.KeyModels{"signal": s}) + if code != http.StatusOK { + return resp, fmt.Errorf("error adding Signal %v: %v", s.Name, err) + } + } } - code, resp, err = helper.TestEndpoint(router, token, basePath+"/widgets", "POST", helper.KeyModels{"widget": widgetB}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding Widget B") - } - code, resp, err = helper.TestEndpoint(router, token, basePath+"/widgets", "POST", helper.KeyModels{"widget": widgetC}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding Widget C") - } - code, resp, err = helper.TestEndpoint(router, token, basePath+"/widgets", "POST", helper.KeyModels{"widget": widgetD}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding Widget D") - } - code, resp, err = helper.TestEndpoint(router, token, basePath+"/widgets", "POST", helper.KeyModels{"widget": widgetE}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding Widget E") - } - - // add signals - outSignalA := helper.OutSignalA - outSignalB := helper.OutSignalB - inSignalA := helper.InSignalA - inSignalB := helper.InSignalB - outSignalC := helper.OutSignalC - outSignalD := helper.OutSignalD - outSignalE := helper.OutSignalE - outSignalA.ConfigID = 1 - outSignalB.ConfigID = 1 - outSignalC.ConfigID = 1 - outSignalD.ConfigID = 1 - outSignalE.ConfigID = 1 - inSignalA.ConfigID = 1 - inSignalB.ConfigID = 2 - - code, resp, err = helper.TestEndpoint(router, token, basePath+"/signals", "POST", helper.KeyModels{"signal": outSignalB}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding outSignalB") - } - code, resp, err = helper.TestEndpoint(router, token, basePath+"/signals", "POST", helper.KeyModels{"signal": outSignalA}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding outSignalA") - } - code, resp, err = helper.TestEndpoint(router, token, basePath+"/signals", "POST", helper.KeyModels{"signal": outSignalC}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding outSignalC") - } - code, resp, err = helper.TestEndpoint(router, token, basePath+"/signals", "POST", helper.KeyModels{"signal": outSignalD}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding outSignalD") - } - code, resp, err = helper.TestEndpoint(router, token, basePath+"/signals", "POST", helper.KeyModels{"signal": outSignalE}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding outSignalE") - } - - code, resp, err = helper.TestEndpoint(router, token, basePath+"/signals", "POST", helper.KeyModels{"signal": inSignalA}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding inSignalA") - } - code, resp, err = helper.TestEndpoint(router, token, basePath+"/signals", "POST", helper.KeyModels{"signal": inSignalB}) - if code != http.StatusOK { - return resp, fmt.Errorf("error adding inSignalB") - } - - // upload files - - // upload readme file - bodyBuf := &bytes.Buffer{} - bodyWriter := multipart.NewWriter(bodyBuf) - fileWriter, _ := bodyWriter.CreateFormFile("file", "Readme.md") - fh, _ := os.Open("README.md") - defer fh.Close() - - // io copy - _, err = io.Copy(fileWriter, fh) - contentType := bodyWriter.FormDataContentType() - bodyWriter.Close() - - // Create the request and add file to scenario - w1 := httptest.NewRecorder() - req1, _ := http.NewRequest("POST", basePath+"/files?scenarioID=1", bodyBuf) - req1.Header.Set("Content-Type", contentType) - req1.Header.Add("Authorization", "Bearer "+token) - router.ServeHTTP(w1, req1) - - // upload image file - bodyBuf = &bytes.Buffer{} - bodyWriter = multipart.NewWriter(bodyBuf) - fileWriter, _ = bodyWriter.CreateFormFile("file", "logo.png") - fh, _ = os.Open("doc/pictures/villas_web.png") - defer fh.Close() - - // io copy - _, err = io.Copy(fileWriter, fh) - contentType = bodyWriter.FormDataContentType() - bodyWriter.Close() - - // Create the request and add a second file to scenario - w2 := httptest.NewRecorder() - req2, _ := http.NewRequest("POST", basePath+"/files?scenarioID=1", bodyBuf) - req2.Header.Set("Content-Type", contentType) - req2.Header.Add("Authorization", "Bearer "+token) - router.ServeHTTP(w2, req2) return nil, nil } diff --git a/routes/result/result_test.go b/routes/result/result_test.go index 853bcd4..bae80fc 100644 --- a/routes/result/result_test.go +++ b/routes/result/result_test.go @@ -124,7 +124,7 @@ func TestGetAllResultsOfScenario(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // prepare the content of the DB for testing // by adding a scenario @@ -175,7 +175,7 @@ func TestAddGetUpdateDeleteResult(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // prepare the content of the DB for testing // by adding a scenario @@ -360,7 +360,7 @@ func TestAddGetUpdateDeleteResult(t *testing.T) { func TestAddDeleteResultFile(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // prepare the content of the DB for testing // by adding a scenario diff --git a/routes/scenario/scenario_test.go b/routes/scenario/scenario_test.go index 598e2aa..4c3c7d8 100644 --- a/routes/scenario/scenario_test.go +++ b/routes/scenario/scenario_test.go @@ -80,7 +80,7 @@ func TestAddScenario(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) newScenario := ScenarioRequest{ Name: helper.ScenarioA.Name, @@ -182,7 +182,7 @@ func TestUpdateScenario(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -252,7 +252,7 @@ func TestGetAllScenariosAsAdmin(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as admin token, err := helper.AuthenticateForTest(router, @@ -313,7 +313,7 @@ func TestGetAllScenariosAsUser(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as normal userB token, err := helper.AuthenticateForTest(router, @@ -370,7 +370,7 @@ func TestDeleteScenario(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -442,7 +442,7 @@ func TestAddUserToScenario(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -527,7 +527,7 @@ func TestGetAllUsersOfScenario(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -612,7 +612,7 @@ func TestRemoveUserFromScenario(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, diff --git a/routes/signal/signal_test.go b/routes/signal/signal_test.go index 6814667..c31144a 100644 --- a/routes/signal/signal_test.go +++ b/routes/signal/signal_test.go @@ -170,7 +170,7 @@ func TestMain(m *testing.M) { func TestAddSignal(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // prepare the content of the DB for testing // by adding a scenario and a IC to the DB @@ -265,7 +265,7 @@ func TestAddSignal(t *testing.T) { func TestUpdateSignal(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // prepare the content of the DB for testing // by adding a scenario and a IC to the DB @@ -367,7 +367,7 @@ func TestUpdateSignal(t *testing.T) { func TestDeleteSignal(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // prepare the content of the DB for testing // by adding a scenario and a IC to the DB @@ -462,7 +462,7 @@ func TestDeleteSignal(t *testing.T) { func TestGetAllInputSignalsOfConfig(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // 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 c8f240d..b90b0ce 100644 --- a/routes/user/user_test.go +++ b/routes/user/user_test.go @@ -25,6 +25,7 @@ import ( "bytes" "encoding/json" "fmt" + "log" "net/http" "net/http/httptest" "os" @@ -55,7 +56,6 @@ func TestMain(m *testing.M) { if err != nil { panic(m) } - err = database.InitDB(configuration.GlobalConfig) if err != nil { panic(m) @@ -75,7 +75,8 @@ func TestMain(m *testing.M) { func TestAuthenticate(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig) + assert.NoError(t, err) // try to authenticate with non JSON body // should result in unauthorized @@ -125,8 +126,9 @@ func TestAuthenticate(t *testing.T) { assert.Equal(t, 401, w4.Code, w4.Body) // authenticate as admin + log.Println(helper.AdminCredentials) _, err = helper.AuthenticateForTest(router, - "/api/authenticate", "POST", helper.AdminCredentials) + "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw}) assert.NoError(t, err) } @@ -135,11 +137,12 @@ func TestAuthenticateQueryToken(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig) + assert.NoError(t, err) // authenticate as admin token, err := helper.AuthenticateForTest(router, - "/api/authenticate", "POST", helper.AdminCredentials) + "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw}) assert.NoError(t, err) w := httptest.NewRecorder() @@ -156,11 +159,12 @@ func TestAddGetUser(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig) + assert.NoError(t, err) // authenticate as admin token, err := helper.AuthenticateForTest(router, - "/api/authenticate", "POST", helper.AdminCredentials) + "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw}) assert.NoError(t, err) // try to POST with non JSON body @@ -225,7 +229,7 @@ func TestAddGetUser(t *testing.T) { wrongUser.Mail = "test@test.com" wrongUser.Role = "Guest" wrongUser.Password = "blablabla" - wrongUser.Username = "User_A" + wrongUser.Username = "admin" code, resp, err = helper.TestEndpoint(router, token, "/api/users", "POST", helper.KeyModels{"user": wrongUser}) assert.NoError(t, err) @@ -280,11 +284,12 @@ func TestUsersNotAllowedActions(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig) + assert.NoError(t, err) // authenticate as admin token, err := helper.AuthenticateForTest(router, - "/api/authenticate", "POST", helper.AdminCredentials) + "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw}) assert.NoError(t, err) // Add a user @@ -340,11 +345,12 @@ func TestGetAllUsers(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig) + assert.NoError(t, err) // authenticate as admin token, err := helper.AuthenticateForTest(router, - "/api/authenticate", "POST", helper.AdminCredentials) + "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw}) assert.NoError(t, err) // get the length of the GET all users response @@ -371,9 +377,14 @@ func TestGetAllUsers(t *testing.T) { assert.Equal(t, finalNumber, initialNumber+1) + newUserCredentials := helper.Credentials{ + Username: newUser.Username, + Password: newUser.Password, + } + // authenticate as normal user token, err = helper.AuthenticateForTest(router, - "/api/authenticate", "POST", helper.UserACredentials) + "/api/authenticate", "POST", newUserCredentials) assert.NoError(t, err) // try to get all users as normal user @@ -389,11 +400,12 @@ func TestModifyAddedUserAsUser(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig) + assert.NoError(t, err) // authenticate as admin token, err := helper.AuthenticateForTest(router, - "/api/authenticate", "POST", helper.AdminCredentials) + "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw}) assert.NoError(t, err) // Add a user that will modify itself @@ -546,11 +558,12 @@ func TestInvalidUserUpdate(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig) + assert.NoError(t, err) // authenticate as admin token, err := helper.AuthenticateForTest(router, - "/api/authenticate", "POST", helper.AdminCredentials) + "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw}) assert.NoError(t, err) // Add a user @@ -582,7 +595,7 @@ func TestInvalidUserUpdate(t *testing.T) { // try to PUT with username that is already taken // should result in bad request modRequest.Password = "" - modRequest.Username = "User_A" + modRequest.Username = "admin" code, resp, err = helper.TestEndpoint(router, token, fmt.Sprintf("/api/users/%v", newUserID), "PUT", helper.KeyModels{"user": modRequest}) @@ -619,11 +632,12 @@ func TestModifyAddedUserAsAdmin(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig) + assert.NoError(t, err) // authenticate as admin token, err := helper.AuthenticateForTest(router, - "/api/authenticate", "POST", helper.AdminCredentials) + "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw}) assert.NoError(t, err) // Add a user @@ -693,7 +707,7 @@ func TestModifyAddedUserAsAdmin(t *testing.T) { // modify newUser's password, requires admin password modRequest = UserRequest{ Password: "4_g00d_pw!", - OldPassword: helper.StrPassword0, + OldPassword: adminpw, } code, resp, err = helper.TestEndpoint(router, token, fmt.Sprintf("/api/users/%v", newUserID), "PUT", @@ -711,7 +725,7 @@ func TestModifyAddedUserAsAdmin(t *testing.T) { // authenticate as admin token, err = helper.AuthenticateForTest(router, - "/api/authenticate", "POST", helper.AdminCredentials) + "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw}) assert.NoError(t, err) // modify newUser's Active status @@ -738,11 +752,12 @@ func TestDeleteUser(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig) + assert.NoError(t, err) // authenticate as admin token, err := helper.AuthenticateForTest(router, - "/api/authenticate", "POST", helper.AdminCredentials) + "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw}) assert.NoError(t, err) // Add a user diff --git a/routes/widget/widget_test.go b/routes/widget/widget_test.go index 1abf0aa..e7cd6d9 100644 --- a/routes/widget/widget_test.go +++ b/routes/widget/widget_test.go @@ -131,7 +131,7 @@ func TestMain(m *testing.M) { func TestAddWidget(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -231,7 +231,7 @@ func TestAddWidget(t *testing.T) { func TestUpdateWidget(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -343,7 +343,7 @@ func TestUpdateWidget(t *testing.T) { func TestDeleteWidget(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, @@ -420,7 +420,7 @@ func TestDeleteWidget(t *testing.T) { func TestGetAllWidgetsOfDashboard(t *testing.T) { database.DropTables() database.MigrateModels() - assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) + assert.NoError(t, helper.AddTestUsers()) // authenticate as normal user token, err := helper.AuthenticateForTest(router, diff --git a/start.go b/start.go index ffcbd13..79c0edc 100644 --- a/start.go +++ b/start.go @@ -23,12 +23,12 @@ package main import ( "fmt" + "git.rwth-aachen.de/acs/public/villas/web-backend-go/helper" "log" "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/helper" "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes" infrastructure_component "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/infrastructure-component" "github.com/gin-gonic/gin" @@ -41,6 +41,17 @@ func addData(router *gin.Engine, cfg *config.Config) error { // test mode: drop all tables and add test data to DB database.DropTables() log.Println("Database tables dropped, using API to add test data") + + testDataPath, err := cfg.String("test.datapath") + if err != nil { + return err + } + err = helper.ReadTestDataFromJson(testDataPath) + if err != nil { + log.Println("testdata could not be read from json") + return err + } + resp, err := routes.AddTestData(cfg, router) if err != nil { fmt.Println("error: testdata could not be added to DB:", err.Error(), "Response body: ", resp) @@ -48,7 +59,7 @@ func addData(router *gin.Engine, cfg *config.Config) error { } } else { // release mode: make sure that at least one admin user exists in DB - err := helper.DBAddAdminUser(cfg) + err, _ := database.DBAddAdminUser(cfg) if err != nil { fmt.Println("error: adding admin user failed:", err.Error()) return err