WIP: adding test data via JSON file #44

This commit is contained in:
Sonja Happ 2021-01-26 15:44:51 +01:00
parent d99b769159
commit 616a1c74dc
16 changed files with 621 additions and 369 deletions

View file

@ -61,6 +61,7 @@ func InitConfig() error {
s3PathStyle = flag.Bool("s3-pathstyle", false, "Use path-style S3 API") 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") 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") 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() flag.Parse()
@ -85,6 +86,7 @@ func InitConfig() error {
"s3.region": *s3Region, "s3.region": *s3Region,
"jwt.secret": *jwtSecret, "jwt.secret": *jwtSecret,
"jwt.expires-after": *jwtExpiresAfter, "jwt.expires-after": *jwtExpiresAfter,
"test.datapath": *testDataPath,
} }
if *s3NoSSL == true { if *s3NoSSL == true {
@ -122,6 +124,7 @@ func InitConfig() error {
"S3_PATHSTYLE": "s3.pathstyle", "S3_PATHSTYLE": "s3.pathstyle",
"JWT_SECRET": "jwt.secret", "JWT_SECRET": "jwt.secret",
"JWT_EXPIRES_AFTER": "jwt.expires-after", "JWT_EXPIRES_AFTER": "jwt.expires-after",
"TEST_DATA_PATH": "test.datapath",
} }
defaults := config.NewStatic(static) defaults := config.NewStatic(static)

View file

@ -23,8 +23,11 @@ package database
import ( import (
"fmt" "fmt"
"golang.org/x/crypto/bcrypt"
"log" "log"
"math/rand"
"strings" "strings"
"time"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres" _ "github.com/jinzhu/gorm/dialects/postgres"
@ -110,3 +113,58 @@ func MigrateModels() {
DBpool.AutoMigrate(&Widget{}) DBpool.AutoMigrate(&Widget{})
DBpool.AutoMigrate(&Result{}) 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()
}

267
database/testdata.json Normal file
View file

@ -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
}
]
}

View file

@ -24,20 +24,37 @@ package helper
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"math/rand" "git.rwth-aachen.de/acs/public/villas/web-backend-go/configuration"
"strings"
"time"
"git.rwth-aachen.de/acs/public/villas/web-backend-go/database" "git.rwth-aachen.de/acs/public/villas/web-backend-go/database"
"github.com/jinzhu/gorm/dialects/postgres" "github.com/jinzhu/gorm/dialects/postgres"
"github.com/zpatrick/go-config"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"io/ioutil"
"log"
"os"
) )
// ####################################################################### // #######################################################################
// #################### Data used for testing ############################ // #################### 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 // Credentials
var StrPassword0 = "xyz789" var StrPassword0 = "xyz789"
var StrPasswordA = "abc123" var StrPasswordA = "abc123"
@ -46,13 +63,10 @@ var StrPasswordC = "guestpw"
// Hash passwords with bcrypt algorithm // Hash passwords with bcrypt algorithm
var bcryptCost = 10 var bcryptCost = 10
var pw0, _ = bcrypt.GenerateFromPassword([]byte(StrPassword0), bcryptCost)
var pwA, _ = bcrypt.GenerateFromPassword([]byte(StrPasswordA), bcryptCost) var pwA, _ = bcrypt.GenerateFromPassword([]byte(StrPasswordA), bcryptCost)
var pwB, _ = bcrypt.GenerateFromPassword([]byte(StrPasswordB), bcryptCost) var pwB, _ = bcrypt.GenerateFromPassword([]byte(StrPasswordB), bcryptCost)
var pwC, _ = bcrypt.GenerateFromPassword([]byte(StrPasswordC), 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), var UserA = database.User{Username: "User_A", Password: string(pwA),
Role: "User", Mail: "User_A@example.com", Active: true} Role: "User", Mail: "User_A@example.com", Active: true}
var UserB = database.User{Username: "User_B", Password: string(pwB), var UserB = database.User{Username: "User_B", Password: string(pwB),
@ -216,35 +230,6 @@ var DashboardB = database.Dashboard{
Grid: 10, 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 // Widgets
var customPropertiesBox = json.RawMessage(`{"border_color" : "#4287f5", "border_color_opacity": 1, "background_color" : "#961520", "background_color_opacity" : 1}`) 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 }`) 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{}, SignalIDs: []int64{},
} }
func generatePassword(Len int) string { func ReadTestDataFromJson(path string) error {
rand.Seed(time.Now().UnixNano())
chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789")
var b strings.Builder jsonFile, err := os.Open(path)
for i := 0; i < Len; i++ { if err != nil {
b.WriteRune(chars[rand.Intn(len(chars))]) 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 return nil
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
} }
// add default admin user, normal users and a guest to the DB // add default admin user, normal users and a guest to the DB
func DBAddAdminAndUserAndGuest() error { func AddTestUsers() error {
database.DBpool.AutoMigrate(&database.User{})
err := ReadTestDataFromJson("../../testdata/testdata.json")
if err != nil {
return err
}
//create a copy of global test data //create a copy of global test data
user0 := User0 if len(GlobalTestData.Users) == 0 {
userA := UserA return fmt.Errorf("no users in test data")
userB := UserB }
userC := UserC
// add admin user to DB database.DBpool.AutoMigrate(&database.User{})
err := database.DBpool.Create(&user0).Error err, _ = database.DBAddAdminUser(configuration.GlobalConfig)
// add normal users to DB if err != nil {
err = database.DBpool.Create(&userA).Error return err
err = database.DBpool.Create(&userB).Error }
// add guest user to DB
err = database.DBpool.Create(&userC).Error for _, user := range GlobalTestData.Users {
return err 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
} }

View file

@ -41,13 +41,13 @@ type KeyModels map[string]interface{}
// ####################################################################### // #######################################################################
type Credentials struct { type Credentials struct {
Username string Username string `json:"username,required"`
Password string Password string `json:"password,required"`
} }
var AdminCredentials = Credentials{ var AdminCredentials = Credentials{
Username: "User_0", Username: "admin",
Password: StrPassword0, Password: "xyz789",
} }
var UserACredentials = Credentials{ var UserACredentials = Credentials{

View file

@ -172,7 +172,7 @@ func TestMain(m *testing.M) {
func TestAddConfig(t *testing.T) { func TestAddConfig(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// by adding a scenario and a IC to the DB // by adding a scenario and a IC to the DB
@ -268,7 +268,7 @@ func TestUpdateConfig(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// by adding a scenario and a IC to the DB // by adding a scenario and a IC to the DB
@ -380,7 +380,7 @@ func TestUpdateConfig(t *testing.T) {
func TestDeleteConfig(t *testing.T) { func TestDeleteConfig(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// by adding a scenario and a IC to the DB // by adding a scenario and a IC to the DB
@ -453,7 +453,7 @@ func TestDeleteConfig(t *testing.T) {
func TestGetAllConfigsOfScenario(t *testing.T) { func TestGetAllConfigsOfScenario(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// by adding a scenario and a IC to the DB // by adding a scenario and a IC to the DB

View file

@ -103,7 +103,7 @@ func TestMain(m *testing.M) {
func TestAddDashboard(t *testing.T) { func TestAddDashboard(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as normal user // authenticate as normal user
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -189,7 +189,7 @@ func TestAddDashboard(t *testing.T) {
func TestUpdateDashboard(t *testing.T) { func TestUpdateDashboard(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as normal user // authenticate as normal user
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -270,7 +270,7 @@ func TestUpdateDashboard(t *testing.T) {
func TestDeleteDashboard(t *testing.T) { func TestDeleteDashboard(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as normal user // authenticate as normal user
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -343,7 +343,7 @@ func TestDeleteDashboard(t *testing.T) {
func TestGetAllDashboardsOfScenario(t *testing.T) { func TestGetAllDashboardsOfScenario(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as normal user // authenticate as normal user
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,

View file

@ -106,7 +106,7 @@ func TestMain(m *testing.M) {
func TestAddFile(t *testing.T) { func TestAddFile(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// using the respective endpoints of the API // using the respective endpoints of the API
@ -207,7 +207,7 @@ func TestUpdateFile(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// using the respective endpoints of the API // using the respective endpoints of the API
@ -340,7 +340,7 @@ func TestUpdateFile(t *testing.T) {
func TestDeleteFile(t *testing.T) { func TestDeleteFile(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// using the respective endpoints of the API // using the respective endpoints of the API
@ -477,7 +477,7 @@ func TestGetAllFilesOfScenario(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// using the respective endpoints of the API // using the respective endpoints of the API

View file

@ -119,7 +119,7 @@ func TestMain(m *testing.M) {
func TestAddICAsAdmin(t *testing.T) { func TestAddICAsAdmin(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// check AMQP connection // check AMQP connection
err := CheckConnection() err := CheckConnection()
@ -232,7 +232,7 @@ func TestAddICAsAdmin(t *testing.T) {
func TestAddICAsUser(t *testing.T) { func TestAddICAsUser(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as user // authenticate as user
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -264,7 +264,7 @@ func TestAddICAsUser(t *testing.T) {
func TestUpdateICAsAdmin(t *testing.T) { func TestUpdateICAsAdmin(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -382,7 +382,7 @@ func TestUpdateICAsAdmin(t *testing.T) {
func TestUpdateICAsUser(t *testing.T) { func TestUpdateICAsUser(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -429,7 +429,7 @@ func TestUpdateICAsUser(t *testing.T) {
func TestDeleteICAsAdmin(t *testing.T) { func TestDeleteICAsAdmin(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -540,7 +540,7 @@ func TestDeleteICAsAdmin(t *testing.T) {
func TestDeleteICAsUser(t *testing.T) { func TestDeleteICAsUser(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -586,7 +586,7 @@ func TestDeleteICAsUser(t *testing.T) {
func TestGetAllICs(t *testing.T) { func TestGetAllICs(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -658,7 +658,7 @@ func TestGetAllICs(t *testing.T) {
func TestGetConfigsOfIC(t *testing.T) { func TestGetConfigsOfIC(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -719,7 +719,7 @@ func TestGetConfigsOfIC(t *testing.T) {
func TestSendActionToIC(t *testing.T) { func TestSendActionToIC(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -774,7 +774,7 @@ func TestCreateUpdateViaAMQPRecv(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -907,7 +907,7 @@ func TestDeleteICViaAMQPRecv(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,

View file

@ -26,6 +26,7 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"log"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@ -87,221 +88,154 @@ func AddTestData(cfg *config.Config, router *gin.Engine) (*bytes.Buffer, error)
} }
database.MigrateModels() database.MigrateModels()
// Create entries of each model (data defined in test_data.go)
// add Admin user // add Admin user (defaults to User_0, xyz789)
err = helper.DBAddAdminUser(cfg) err, adminpw := database.DBAddAdminUser(cfg)
var Admin = helper.Credentials{
Username: "admin",
Password: adminpw,
}
if err != nil { if err != nil {
return nil, err return nil, err
} }
// authenticate as admin // 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 { if err != nil {
return nil, err return nil, err
} }
// add 2 normal and 1 guest user // add users
code, resp, err := helper.TestEndpoint(router, token, basePath+"/users", "POST", helper.KeyModels{"user": helper.NewUserA}) for _, u := range helper.GlobalTestData.Users {
if code != http.StatusOK { code, resp, err := helper.TestEndpoint(router, token, basePath+"/users", "POST", helper.KeyModels{"user": u})
return resp, fmt.Errorf("error adding User_A") if code != http.StatusOK {
} return resp, fmt.Errorf("error adding user %v: %v", u.Username, err)
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 infrastructure components // add infrastructure components
code, resp, err = helper.TestEndpoint(router, token, basePath+"/ic", "POST", helper.KeyModels{"ic": helper.ICA}) amqphost, _ := cfg.String("amqp.host")
if code != http.StatusOK { counterICs := 0
return resp, fmt.Errorf("error adding IC A") log.Println("ICS", helper.GlobalTestData.ICs)
} for _, i := range helper.GlobalTestData.ICs {
amqphost, err := cfg.String("amqp.host")
if err != nil && amqphost != "" { if (i.ManagedExternally && amqphost != "") || !i.ManagedExternally {
code, resp, err = helper.TestEndpoint(router, token, basePath+"/ic", "POST", helper.KeyModels{"ic": helper.ICB}) code, resp, err := helper.TestEndpoint(router, token, basePath+"/ic", "POST", helper.KeyModels{"ic": i})
if code != http.StatusOK { if code != http.StatusOK {
return resp, fmt.Errorf("error adding IC B") return resp, fmt.Errorf("error adding IC %v: %v", i.Name, err)
}
counterICs++
} }
} }
// add scenarios // add scenarios
code, resp, err = helper.TestEndpoint(router, token, basePath+"/scenarios", "POST", helper.KeyModels{"scenario": helper.ScenarioA}) for _, s := range helper.GlobalTestData.Scenarios {
if code != http.StatusOK { code, resp, err := helper.TestEndpoint(router, token, basePath+"/scenarios", "POST", helper.KeyModels{"scenario": s})
return resp, fmt.Errorf("error adding Scenario A") if code != http.StatusOK {
} return resp, fmt.Errorf("error adding Scenario %v: %v", s.Name, err)
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") // 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 // If there is at least one scenario and one IC in the test data, add component configs
code, resp, err = helper.TestEndpoint(router, token, fmt.Sprintf("%v/scenarios/1/user?username=User_A", basePath), "PUT", nil) configCounter := 0
if code != http.StatusOK { if len(helper.GlobalTestData.Scenarios) > 0 && counterICs > 0 {
return resp, fmt.Errorf("error adding User_A to Scenario A")
} for _, c := range helper.GlobalTestData.Configs {
code, resp, err = helper.TestEndpoint(router, token, fmt.Sprintf("%v/scenarios/2/user?username=User_A", basePath), "PUT", nil) c.ScenarioID = 1
if code != http.StatusOK { c.ICID = 1
return resp, fmt.Errorf("error adding User_A to Scenario B") code, resp, err := helper.TestEndpoint(router, token, basePath+"/configs", "POST", helper.KeyModels{"config": c})
} if code != http.StatusOK {
code, resp, err = helper.TestEndpoint(router, token, fmt.Sprintf("%v/scenarios/2/user?username=User_B", basePath), "PUT", nil) return resp, fmt.Errorf("error adding Config %v: %v", c.Name, err)
if code != http.StatusOK { }
return resp, fmt.Errorf("error adding User_B to Scenario B") configCounter++
} }
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")
} }
// add component configurations // If there is at least one scenario, add dashboards and 2 test files
configA := helper.ConfigA dashboardCounter := 0
configB := helper.ConfigB if len(helper.GlobalTestData.Scenarios) > 0 {
configA.ScenarioID = 1 for _, d := range helper.GlobalTestData.Dashboards {
configB.ScenarioID = 1 d.ScenarioID = 1
configA.ICID = 1 code, resp, err := helper.TestEndpoint(router, token, basePath+"/dashboards", "POST", helper.KeyModels{"dashboard": d})
configB.ICID = 1 if code != http.StatusOK {
code, resp, err = helper.TestEndpoint(router, token, basePath+"/configs", "POST", helper.KeyModels{"config": configA}) return resp, fmt.Errorf("error adding Dashboard %v: %v", d.Name, err)
if code != http.StatusOK { }
return resp, fmt.Errorf("error adding Config A") dashboardCounter++
} }
code, resp, err = helper.TestEndpoint(router, token, basePath+"/configs", "POST", helper.KeyModels{"config": configB})
if code != http.StatusOK { // upload files
return resp, fmt.Errorf("error adding Config B")
// 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 // If there is at least one dashboard, add widgets
dashboardA := helper.DashboardA if dashboardCounter > 0 {
dashboardB := helper.DashboardB for _, w := range helper.GlobalTestData.Widgets {
dashboardA.ScenarioID = 1 w.DashboardID = 1
dashboardB.ScenarioID = 1 code, resp, err := helper.TestEndpoint(router, token, basePath+"/widgets", "POST", helper.KeyModels{"widget": w})
code, resp, err = helper.TestEndpoint(router, token, basePath+"/dashboards", "POST", helper.KeyModels{"dashboard": dashboardA}) if code != http.StatusOK {
if code != http.StatusOK { return resp, fmt.Errorf("error adding Widget %v: %v", w.Name, err)
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")
} }
// add widgets // If there is at least one config, add signals
widgetA := helper.WidgetA if configCounter > 0 {
widgetB := helper.WidgetB for _, s := range helper.GlobalTestData.Signals {
widgetC := helper.WidgetC s.ConfigID = 1
widgetD := helper.WidgetD code, resp, err := helper.TestEndpoint(router, token, basePath+"/signals", "POST", helper.KeyModels{"signal": s})
widgetE := helper.WidgetE if code != http.StatusOK {
widgetA.DashboardID = 1 return resp, fmt.Errorf("error adding Signal %v: %v", s.Name, err)
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")
} }
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 return nil, nil
} }

View file

@ -124,7 +124,7 @@ func TestGetAllResultsOfScenario(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// by adding a scenario // by adding a scenario
@ -175,7 +175,7 @@ func TestAddGetUpdateDeleteResult(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// by adding a scenario // by adding a scenario
@ -360,7 +360,7 @@ func TestAddGetUpdateDeleteResult(t *testing.T) {
func TestAddDeleteResultFile(t *testing.T) { func TestAddDeleteResultFile(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// by adding a scenario // by adding a scenario

View file

@ -80,7 +80,7 @@ func TestAddScenario(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
newScenario := ScenarioRequest{ newScenario := ScenarioRequest{
Name: helper.ScenarioA.Name, Name: helper.ScenarioA.Name,
@ -182,7 +182,7 @@ func TestUpdateScenario(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as normal user // authenticate as normal user
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -252,7 +252,7 @@ func TestGetAllScenariosAsAdmin(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -313,7 +313,7 @@ func TestGetAllScenariosAsUser(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as normal userB // authenticate as normal userB
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -370,7 +370,7 @@ func TestDeleteScenario(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as normal user // authenticate as normal user
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -442,7 +442,7 @@ func TestAddUserToScenario(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as normal user // authenticate as normal user
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -527,7 +527,7 @@ func TestGetAllUsersOfScenario(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as normal user // authenticate as normal user
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -612,7 +612,7 @@ func TestRemoveUserFromScenario(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as normal user // authenticate as normal user
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,

View file

@ -170,7 +170,7 @@ func TestMain(m *testing.M) {
func TestAddSignal(t *testing.T) { func TestAddSignal(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// by adding a scenario and a IC to the DB // by adding a scenario and a IC to the DB
@ -265,7 +265,7 @@ func TestAddSignal(t *testing.T) {
func TestUpdateSignal(t *testing.T) { func TestUpdateSignal(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// by adding a scenario and a IC to the DB // by adding a scenario and a IC to the DB
@ -367,7 +367,7 @@ func TestUpdateSignal(t *testing.T) {
func TestDeleteSignal(t *testing.T) { func TestDeleteSignal(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// by adding a scenario and a IC to the DB // by adding a scenario and a IC to the DB
@ -462,7 +462,7 @@ func TestDeleteSignal(t *testing.T) {
func TestGetAllInputSignalsOfConfig(t *testing.T) { func TestGetAllInputSignalsOfConfig(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// prepare the content of the DB for testing // prepare the content of the DB for testing
// by adding a scenario and a IC to the DB // by adding a scenario and a IC to the DB

View file

@ -25,6 +25,7 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
@ -55,7 +56,6 @@ func TestMain(m *testing.M) {
if err != nil { if err != nil {
panic(m) panic(m)
} }
err = database.InitDB(configuration.GlobalConfig) err = database.InitDB(configuration.GlobalConfig)
if err != nil { if err != nil {
panic(m) panic(m)
@ -75,7 +75,8 @@ func TestMain(m *testing.M) {
func TestAuthenticate(t *testing.T) { func TestAuthenticate(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig)
assert.NoError(t, err)
// try to authenticate with non JSON body // try to authenticate with non JSON body
// should result in unauthorized // should result in unauthorized
@ -125,8 +126,9 @@ func TestAuthenticate(t *testing.T) {
assert.Equal(t, 401, w4.Code, w4.Body) assert.Equal(t, 401, w4.Code, w4.Body)
// authenticate as admin // authenticate as admin
log.Println(helper.AdminCredentials)
_, err = helper.AuthenticateForTest(router, _, err = helper.AuthenticateForTest(router,
"/api/authenticate", "POST", helper.AdminCredentials) "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw})
assert.NoError(t, err) assert.NoError(t, err)
} }
@ -135,11 +137,12 @@ func TestAuthenticateQueryToken(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig)
assert.NoError(t, err)
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
"/api/authenticate", "POST", helper.AdminCredentials) "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw})
assert.NoError(t, err) assert.NoError(t, err)
w := httptest.NewRecorder() w := httptest.NewRecorder()
@ -156,11 +159,12 @@ func TestAddGetUser(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig)
assert.NoError(t, err)
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
"/api/authenticate", "POST", helper.AdminCredentials) "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw})
assert.NoError(t, err) assert.NoError(t, err)
// try to POST with non JSON body // try to POST with non JSON body
@ -225,7 +229,7 @@ func TestAddGetUser(t *testing.T) {
wrongUser.Mail = "test@test.com" wrongUser.Mail = "test@test.com"
wrongUser.Role = "Guest" wrongUser.Role = "Guest"
wrongUser.Password = "blablabla" wrongUser.Password = "blablabla"
wrongUser.Username = "User_A" wrongUser.Username = "admin"
code, resp, err = helper.TestEndpoint(router, token, code, resp, err = helper.TestEndpoint(router, token,
"/api/users", "POST", helper.KeyModels{"user": wrongUser}) "/api/users", "POST", helper.KeyModels{"user": wrongUser})
assert.NoError(t, err) assert.NoError(t, err)
@ -280,11 +284,12 @@ func TestUsersNotAllowedActions(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig)
assert.NoError(t, err)
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
"/api/authenticate", "POST", helper.AdminCredentials) "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw})
assert.NoError(t, err) assert.NoError(t, err)
// Add a user // Add a user
@ -340,11 +345,12 @@ func TestGetAllUsers(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig)
assert.NoError(t, err)
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
"/api/authenticate", "POST", helper.AdminCredentials) "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw})
assert.NoError(t, err) assert.NoError(t, err)
// get the length of the GET all users response // get the length of the GET all users response
@ -371,9 +377,14 @@ func TestGetAllUsers(t *testing.T) {
assert.Equal(t, finalNumber, initialNumber+1) assert.Equal(t, finalNumber, initialNumber+1)
newUserCredentials := helper.Credentials{
Username: newUser.Username,
Password: newUser.Password,
}
// authenticate as normal user // authenticate as normal user
token, err = helper.AuthenticateForTest(router, token, err = helper.AuthenticateForTest(router,
"/api/authenticate", "POST", helper.UserACredentials) "/api/authenticate", "POST", newUserCredentials)
assert.NoError(t, err) assert.NoError(t, err)
// try to get all users as normal user // try to get all users as normal user
@ -389,11 +400,12 @@ func TestModifyAddedUserAsUser(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig)
assert.NoError(t, err)
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
"/api/authenticate", "POST", helper.AdminCredentials) "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw})
assert.NoError(t, err) assert.NoError(t, err)
// Add a user that will modify itself // Add a user that will modify itself
@ -546,11 +558,12 @@ func TestInvalidUserUpdate(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig)
assert.NoError(t, err)
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
"/api/authenticate", "POST", helper.AdminCredentials) "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw})
assert.NoError(t, err) assert.NoError(t, err)
// Add a user // Add a user
@ -582,7 +595,7 @@ func TestInvalidUserUpdate(t *testing.T) {
// try to PUT with username that is already taken // try to PUT with username that is already taken
// should result in bad request // should result in bad request
modRequest.Password = "" modRequest.Password = ""
modRequest.Username = "User_A" modRequest.Username = "admin"
code, resp, err = helper.TestEndpoint(router, token, code, resp, err = helper.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "PUT", fmt.Sprintf("/api/users/%v", newUserID), "PUT",
helper.KeyModels{"user": modRequest}) helper.KeyModels{"user": modRequest})
@ -619,11 +632,12 @@ func TestModifyAddedUserAsAdmin(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig)
assert.NoError(t, err)
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
"/api/authenticate", "POST", helper.AdminCredentials) "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw})
assert.NoError(t, err) assert.NoError(t, err)
// Add a user // Add a user
@ -693,7 +707,7 @@ func TestModifyAddedUserAsAdmin(t *testing.T) {
// modify newUser's password, requires admin password // modify newUser's password, requires admin password
modRequest = UserRequest{ modRequest = UserRequest{
Password: "4_g00d_pw!", Password: "4_g00d_pw!",
OldPassword: helper.StrPassword0, OldPassword: adminpw,
} }
code, resp, err = helper.TestEndpoint(router, token, code, resp, err = helper.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "PUT", fmt.Sprintf("/api/users/%v", newUserID), "PUT",
@ -711,7 +725,7 @@ func TestModifyAddedUserAsAdmin(t *testing.T) {
// authenticate as admin // authenticate as admin
token, err = helper.AuthenticateForTest(router, token, err = helper.AuthenticateForTest(router,
"/api/authenticate", "POST", helper.AdminCredentials) "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw})
assert.NoError(t, err) assert.NoError(t, err)
// modify newUser's Active status // modify newUser's Active status
@ -738,11 +752,12 @@ func TestDeleteUser(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) err, adminpw := database.DBAddAdminUser(configuration.GlobalConfig)
assert.NoError(t, err)
// authenticate as admin // authenticate as admin
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
"/api/authenticate", "POST", helper.AdminCredentials) "/api/authenticate", "POST", helper.Credentials{Username: "admin", Password: adminpw})
assert.NoError(t, err) assert.NoError(t, err)
// Add a user // Add a user

View file

@ -131,7 +131,7 @@ func TestMain(m *testing.M) {
func TestAddWidget(t *testing.T) { func TestAddWidget(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as normal user // authenticate as normal user
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -231,7 +231,7 @@ func TestAddWidget(t *testing.T) {
func TestUpdateWidget(t *testing.T) { func TestUpdateWidget(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as normal user // authenticate as normal user
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -343,7 +343,7 @@ func TestUpdateWidget(t *testing.T) {
func TestDeleteWidget(t *testing.T) { func TestDeleteWidget(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as normal user // authenticate as normal user
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,
@ -420,7 +420,7 @@ func TestDeleteWidget(t *testing.T) {
func TestGetAllWidgetsOfDashboard(t *testing.T) { func TestGetAllWidgetsOfDashboard(t *testing.T) {
database.DropTables() database.DropTables()
database.MigrateModels() database.MigrateModels()
assert.NoError(t, helper.DBAddAdminAndUserAndGuest()) assert.NoError(t, helper.AddTestUsers())
// authenticate as normal user // authenticate as normal user
token, err := helper.AuthenticateForTest(router, token, err := helper.AuthenticateForTest(router,

View file

@ -23,12 +23,12 @@ package main
import ( import (
"fmt" "fmt"
"git.rwth-aachen.de/acs/public/villas/web-backend-go/helper"
"log" "log"
"git.rwth-aachen.de/acs/public/villas/web-backend-go/configuration" "git.rwth-aachen.de/acs/public/villas/web-backend-go/configuration"
"git.rwth-aachen.de/acs/public/villas/web-backend-go/database" "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 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" "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" infrastructure_component "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/infrastructure-component"
"github.com/gin-gonic/gin" "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 // test mode: drop all tables and add test data to DB
database.DropTables() database.DropTables()
log.Println("Database tables dropped, using API to add test data") 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) resp, err := routes.AddTestData(cfg, router)
if err != nil { if err != nil {
fmt.Println("error: testdata could not be added to DB:", err.Error(), "Response body: ", resp) 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 { } else {
// release mode: make sure that at least one admin user exists in DB // release mode: make sure that at least one admin user exists in DB
err := helper.DBAddAdminUser(cfg) err, _ := database.DBAddAdminUser(cfg)
if err != nil { if err != nil {
fmt.Println("error: adding admin user failed:", err.Error()) fmt.Println("error: adding admin user failed:", err.Error())
return err return err