Commit 28434668 authored by Sonja Happ's avatar Sonja Happ
Browse files

further cleanups, make register test work again

parent 3c4624d1
/** Helper package, test data.
*
* @author Sonja Happ <sonja.happ@eonerc.rwth-aachen.de>
* @copyright 2014-2019, Institute for Automation of Complex Power Systems, EONERC
* @license GNU General Public License (version 3)
*
* VILLASweb-backend-go
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*********************************************************************************/
package helper
import (
"encoding/json"
"fmt"
"git.rwth-aachen.de/acs/public/villas/web-backend-go/database"
"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"
var StrPasswordB = "bcd234"
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"}
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),
Role: "User", Mail: "User_B@example.com", Active: true}
var UserC = database.User{Username: "User_C", Password: string(pwC),
Role: "Guest", Mail: "User_C@example.com", Active: true}
type UserRequest struct {
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
OldPassword string `json:"oldPassword,omitempty"`
Mail string `json:"mail,omitempty"`
Role string `json:"role,omitempty"`
Active string `json:"active,omitempty"`
}
func ReadTestDataFromJson(path string) error {
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)
}
log.Println(len(GlobalTestData.Users))
return nil
}
// add test users defined above
func AddTestUsers() error {
testUsers := []database.User{User0, UserA, UserB, UserC}
database.DBpool.AutoMigrate(&database.User{})
for _, user := range testUsers {
err := database.DBpool.Create(&user).Error
if err != nil {
return err
}
}
return nil
}
......@@ -25,12 +25,13 @@ import (
"bytes"
"encoding/json"
"fmt"
"git.rwth-aachen.de/acs/public/villas/web-backend-go/database"
"github.com/gin-gonic/gin"
"github.com/nsf/jsondiff"
"golang.org/x/crypto/bcrypt"
"log"
"net/http"
"net/http/httptest"
"github.com/gin-gonic/gin"
"github.com/nsf/jsondiff"
)
// data type used in testing
......@@ -40,28 +41,59 @@ type KeyModels map[string]interface{}
// #################### User data used for testing #######################
// #######################################################################
// Credentials
var StrPassword0 = "xyz789"
var StrPasswordA = "abc123"
var StrPasswordB = "bcd234"
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"}
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),
Role: "User", Mail: "User_B@example.com", Active: true}
var UserC = database.User{Username: "User_C", Password: string(pwC),
Role: "Guest", Mail: "User_C@example.com", Active: true}
type UserRequest struct {
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
OldPassword string `json:"oldPassword,omitempty"`
Mail string `json:"mail,omitempty"`
Role string `json:"role,omitempty"`
Active string `json:"active,omitempty"`
}
type Credentials struct {
Username string `json:"username,required"`
Password string `json:"password,required"`
}
var AdminCredentials = Credentials{
Username: "User_0",
Username: User0.Username,
Password: StrPassword0,
}
var UserACredentials = Credentials{
Username: "User_A",
Username: UserA.Username,
Password: StrPasswordA,
}
var UserBCredentials = Credentials{
Username: "User_B",
Username: UserB.Username,
Password: StrPasswordB,
}
var GuestCredentials = Credentials{
Username: "User_C",
Username: UserC.Username,
Password: StrPasswordC,
}
......@@ -284,10 +316,19 @@ func AuthenticateForTest(router *gin.Engine, url string,
return token, nil
}
// Quick error check
// NOTE: maybe this is not a good idea
func checkErr(err error) {
if err != nil {
log.Fatal(err)
// add test users defined above
func AddTestUsers() error {
testUsers := []database.User{User0, UserA, UserB, UserC}
database.DBpool.AutoMigrate(&database.User{})
for _, user := range testUsers {
err := database.DBpool.Create(&user).Error
if err != nil {
return err
}
}
return nil
}
......@@ -24,8 +24,10 @@ package routes
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
......@@ -51,6 +53,28 @@ import (
"github.com/zpatrick/go-config"
)
// #######################################################################
// #################### Structures for test data #########################
// #######################################################################
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
}
// register all backend endpoints; to be called after DB is initialized
func RegisterEndpoints(router *gin.Engine, api *gin.RouterGroup) {
......@@ -78,6 +102,29 @@ func RegisterEndpoints(router *gin.Engine, api *gin.RouterGroup) {
}
// Read test data from JSON file (path set by ENV variable or command line param)
func ReadTestDataFromJson(path string) error {
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)
}
log.Println(len(GlobalTestData.Users))
return nil
}
// Uses API endpoints to add test data to the backend; All endpoints have to be registered before invoking this function.
func AddTestData(cfg *config.Config, router *gin.Engine) (*bytes.Buffer, error) {
......@@ -108,7 +155,7 @@ func AddTestData(cfg *config.Config, router *gin.Engine) (*bytes.Buffer, error)
}
// add users
for _, u := range helper.GlobalTestData.Users {
for _, u := range 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)
......@@ -118,8 +165,7 @@ func AddTestData(cfg *config.Config, router *gin.Engine) (*bytes.Buffer, error)
// add infrastructure components
amqphost, _ := cfg.String("amqp.host")
counterICs := 0
log.Println("ICS", helper.GlobalTestData.ICs)
for _, i := range helper.GlobalTestData.ICs {
for _, i := range GlobalTestData.ICs {
if (i.ManagedExternally && amqphost != "") || !i.ManagedExternally {
code, resp, err := helper.TestEndpoint(router, token, basePath+"/ic", "POST", helper.KeyModels{"ic": i})
......@@ -131,14 +177,14 @@ func AddTestData(cfg *config.Config, router *gin.Engine) (*bytes.Buffer, error)
}
// add scenarios
for _, s := range helper.GlobalTestData.Scenarios {
for _, s := range 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 {
for _, u := range 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)
......@@ -148,9 +194,9 @@ func AddTestData(cfg *config.Config, router *gin.Engine) (*bytes.Buffer, error)
// 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 {
if len(GlobalTestData.Scenarios) > 0 && counterICs > 0 {
for _, c := range helper.GlobalTestData.Configs {
for _, c := range GlobalTestData.Configs {
c.ScenarioID = 1
c.ICID = 1
code, resp, err := helper.TestEndpoint(router, token, basePath+"/configs", "POST", helper.KeyModels{"config": c})
......@@ -163,8 +209,8 @@ func AddTestData(cfg *config.Config, router *gin.Engine) (*bytes.Buffer, error)
// 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 {
if len(GlobalTestData.Scenarios) > 0 {
for _, d := range GlobalTestData.Dashboards {
d.ScenarioID = 1
code, resp, err := helper.TestEndpoint(router, token, basePath+"/dashboards", "POST", helper.KeyModels{"dashboard": d})
if code != http.StatusOK {
......@@ -217,7 +263,7 @@ func AddTestData(cfg *config.Config, router *gin.Engine) (*bytes.Buffer, error)
// If there is at least one dashboard, add widgets
if dashboardCounter > 0 {
for _, w := range helper.GlobalTestData.Widgets {
for _, w := range GlobalTestData.Widgets {
w.DashboardID = 1
code, resp, err := helper.TestEndpoint(router, token, basePath+"/widgets", "POST", helper.KeyModels{"widget": w})
if code != http.StatusOK {
......@@ -228,7 +274,7 @@ func AddTestData(cfg *config.Config, router *gin.Engine) (*bytes.Buffer, error)
// If there is at least one config, add signals
if configCounter > 0 {
for _, s := range helper.GlobalTestData.Signals {
for _, s := range GlobalTestData.Signals {
s.ConfigID = 1
code, resp, err := helper.TestEndpoint(router, token, basePath+"/signals", "POST", helper.KeyModels{"signal": s})
if code != http.StatusOK {
......
......@@ -34,7 +34,6 @@ import (
)
var router *gin.Engine
var amqpURI string
func TestMain(m *testing.M) {
err := configuration.InitConfig()
......@@ -66,7 +65,9 @@ func TestRegisterEndpoints(t *testing.T) {
database.DropTables()
database.MigrateModels()
api := router.Group("/api")
basePath, err := configuration.GlobalConfig.String("base.path")
assert.NoError(t, err)
api := router.Group(basePath)
RegisterEndpoints(router, api)
}
......@@ -76,6 +77,9 @@ func TestAddTestData(t *testing.T) {
panic(t)
}
err = ReadTestDataFromJson("../database/testdata.json")
assert.NoError(t, err)
resp, err := AddTestData(configuration.GlobalConfig, router)
assert.NoError(t, err, "Response body: %v", resp)
}
......@@ -23,7 +23,6 @@ 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"
......@@ -46,7 +45,7 @@ func addData(router *gin.Engine, cfg *config.Config) error {
if err != nil {
return err
}
err = helper.ReadTestDataFromJson(testDataPath)
err = routes.ReadTestDataFromJson(testDataPath)
if err != nil {
log.Println("testdata could not be read from json")
return err
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment