- deleting old obsolete test functions

- move all data and functions solely used for testing to the file test_utilities
- get rid of utilities file
This commit is contained in:
Sonja Happ 2019-09-09 12:11:55 +02:00
parent f339c0d135
commit ac9e564bc8
28 changed files with 682 additions and 733 deletions

View file

@ -3,9 +3,11 @@ package common
import (
"flag"
"fmt"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"log"
"net/http"
)
var DB_HOST string
@ -212,3 +214,23 @@ func checkErr(err error) {
log.Fatal(err)
}
}
func DBError(c *gin.Context, err error) bool {
if err != nil {
if err == gorm.ErrRecordNotFound {
errormsg := "Record not Found in DB: " + err.Error()
c.JSON(http.StatusNotFound, gin.H{
"success": false,
"message": errormsg,
})
} else {
errormsg := "Error on DB Query or transaction: " + err.Error()
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
"message": errormsg,
})
}
return true // Error
}
return false // No error
}

View file

@ -107,3 +107,7 @@ func ValidateRole(c *gin.Context, model ModelName, action CRUD) error {
return nil
}
// elements added to context about a user
const UserIDCtx = "user_id"
const UserRoleCtx = "user_role"

406
common/test_utilities.go Normal file
View file

@ -0,0 +1,406 @@
package common
import (
"bytes"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm/dialects/postgres"
"github.com/nsf/jsondiff"
"golang.org/x/crypto/bcrypt"
"net/http"
"net/http/httptest"
"time"
)
// data type used in testing
type KeyModels map[string]interface{}
// #######################################################################
// #################### Data used for testing ############################
// #######################################################################
// Users
var StrPassword0 = "xyz789"
var StrPasswordA = "abc123"
var StrPasswordB = "bcd234"
// 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 User0 = User{Username: "User_0", Password: string(pw0),
Role: "Admin", Mail: "User_0@example.com"}
var UserA = User{Username: "User_A", Password: string(pwA),
Role: "User", Mail: "User_A@example.com"}
var UserB = User{Username: "User_B", Password: string(pwB),
Role: "User", Mail: "User_B@example.com"}
// Credentials
type Credentials struct {
Username string
Password string
}
var AdminCredentials = Credentials{
Username: User0.Username,
Password: StrPassword0,
}
var UserACredentials = Credentials{
Username: UserA.Username,
Password: StrPasswordA,
}
var UserBCredentials = Credentials{
Username: UserB.Username,
Password: StrPasswordB,
}
// Simulators
var propertiesA = json.RawMessage(`{"name" : "TestNameA", "category" : "CategoryA", "location" : "anywhere on earth", "type": "dummy"}`)
var propertiesB = json.RawMessage(`{"name" : "TestNameB", "category" : "CategoryB", "location" : "where ever you want", "type": "generic"}`)
var SimulatorA = Simulator{
UUID: "4854af30-325f-44a5-ad59-b67b2597de68",
Host: "Host_A",
Modeltype: "ModelTypeA",
Uptime: 0,
State: "running",
StateUpdateAt: time.Now().String(),
Properties: postgres.Jsonb{propertiesA},
RawProperties: postgres.Jsonb{propertiesA},
}
var SimulatorB = Simulator{
UUID: "7be0322d-354e-431e-84bd-ae4c9633138b",
Host: "Host_B",
Modeltype: "ModelTypeB",
Uptime: 0,
State: "idle",
StateUpdateAt: time.Now().String(),
Properties: postgres.Jsonb{propertiesB},
RawProperties: postgres.Jsonb{propertiesB},
}
// Scenarios
var startParametersA = json.RawMessage(`{"parameter1" : "testValue1A", "parameter2" : "testValue2A", "parameter3" : 42}`)
var startParametersB = json.RawMessage(`{"parameter1" : "testValue1B", "parameter2" : "testValue2B", "parameter3" : 43}`)
var ScenarioA = Scenario{
Name: "Scenario_A",
Running: true,
StartParameters: postgres.Jsonb{startParametersA},
}
var ScenarioB = Scenario{
Name: "Scenario_B",
Running: false,
StartParameters: postgres.Jsonb{startParametersB},
}
// Simulation Models
var SimulationModelA = SimulationModel{
Name: "SimulationModel_A",
StartParameters: postgres.Jsonb{startParametersA},
}
var SimulationModelB = SimulationModel{
Name: "SimulationModel_B",
StartParameters: postgres.Jsonb{startParametersB},
}
// Signals
var OutSignalA = Signal{
Name: "outSignal_A",
Direction: "out",
Index: 0,
Unit: "V",
}
var OutSignalB = Signal{
Name: "outSignal_B",
Direction: "out",
Index: 1,
Unit: "V",
}
var InSignalA = Signal{
Name: "inSignal_A",
Direction: "in",
Index: 0,
Unit: "A",
}
var InSignalB = Signal{
Name: "inSignal_B",
Direction: "in",
Index: 1,
Unit: "A",
}
// Dashboards
var DashboardA = Dashboard{
Name: "Dashboard_A",
Grid: 15,
}
var DashboardB = Dashboard{
Name: "Dashboard_B",
Grid: 10,
}
// Files
var FileA = File{
Name: "File_A",
Type: "text/plain",
Size: 42,
ImageHeight: 333,
ImageWidth: 111,
Date: time.Now().String(),
}
var FileB = File{
Name: "File_B",
Type: "text/plain",
Size: 1234,
ImageHeight: 55,
ImageWidth: 22,
Date: time.Now().String(),
}
var FileC = File{
Name: "File_C",
Type: "text/plain",
Size: 32,
ImageHeight: 10,
ImageWidth: 10,
Date: time.Now().String(),
}
var FileD = File{
Name: "File_D",
Type: "text/plain",
Size: 5000,
ImageHeight: 400,
ImageWidth: 800,
Date: time.Now().String(),
}
// Widgets
var customPropertiesA = json.RawMessage(`{"property1" : "testValue1A", "property2" : "testValue2A", "property3" : 42}`)
var customPropertiesB = json.RawMessage(`{"property1" : "testValue1B", "property2" : "testValue2B", "property3" : 43}`)
var WidgetA = Widget{
Name: "Widget_A",
Type: "graph",
Width: 100,
Height: 50,
MinHeight: 40,
MinWidth: 80,
X: 10,
Y: 10,
Z: 10,
IsLocked: false,
CustomProperties: postgres.Jsonb{customPropertiesA},
}
var WidgetB = Widget{
Name: "Widget_B",
Type: "slider",
Width: 200,
Height: 20,
MinHeight: 10,
MinWidth: 50,
X: 100,
Y: -40,
Z: -1,
IsLocked: false,
CustomProperties: postgres.Jsonb{customPropertiesB},
}
// ############################################################################
// #################### Functions used for testing ############################
// ############################################################################
// Return the ID of an element contained in a response
func GetResponseID(resp *bytes.Buffer) (int, error) {
// Transform bytes buffer into byte slice
respBytes := []byte(resp.String())
// Map JSON response to a map[string]map[string]interface{}
var respRemapped map[string]map[string]interface{}
err := json.Unmarshal(respBytes, &respRemapped)
if err != nil {
return 0, fmt.Errorf("Unmarshal failed for respRemapped %v", err)
}
// Get an arbitrary key from tha map. The only key (entry) of
// course is the model's name. With that trick we do not have to
// pass the higher level key as argument.
for arbitrary_key := range respRemapped {
// The marshaler turns numerical values into float64 types so we
// first have to make a type assertion to the interface and then
// the conversion to integer before returning
id, ok := respRemapped[arbitrary_key]["id"].(float64)
if !ok {
return 0, fmt.Errorf("Cannot type assert respRemapped")
}
return int(id), nil
}
return 0, fmt.Errorf("GetResponse reached exit")
}
// Return the length of an response in case it is an array
func LengthOfResponse(router *gin.Engine, token string, url string,
method string, body []byte) (int, error) {
w := httptest.NewRecorder()
req, err := http.NewRequest(method, url, nil)
if err != nil {
return 0, fmt.Errorf("Failed to create new request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
// HTTP Code of response must be 200
if w.Code != 200 {
return 0, fmt.Errorf("HTTP Code: Expected \"200\". Got \"%v\""+
".\nResponse message:\n%v", w.Code, w.Body.String())
}
// Convert the response in array of bytes
responseBytes := []byte(w.Body.String())
// First we are trying to unmarshal the response into an array of
// general type variables ([]interface{}). If this fails we will try
// to unmarshal into a single general type variable (interface{}).
// If that also fails we will return 0.
// Response might be array of objects
var arrayResponse map[string][]interface{}
err = json.Unmarshal(responseBytes, &arrayResponse)
if err == nil {
// Get an arbitrary key from tha map. The only key (entry) of
// course is the model's name. With that trick we do not have to
// pass the higher level key as argument.
for arbitrary_key := range arrayResponse {
return len(arrayResponse[arbitrary_key]), nil
}
}
// Response might be a single object
var singleResponse map[string]interface{}
err = json.Unmarshal(responseBytes, &singleResponse)
if err == nil {
return 1, nil
}
// Failed to identify response.
return 0, fmt.Errorf("Length of response cannot be detected")
}
// Make a request to an endpoint
func TestEndpoint(router *gin.Engine, token string, url string,
method string, requestBody interface{}) (int, *bytes.Buffer, error) {
w := httptest.NewRecorder()
// Marshal the HTTP request body
body, err := json.Marshal(requestBody)
if err != nil {
return 0, nil, fmt.Errorf("Failed to marshal request body: %v", err)
}
// Create the request
req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
if err != nil {
return 0, nil, fmt.Errorf("Failed to create new request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
return w.Code, w.Body, nil
}
// Compare the response of a query with a JSON
func CompareResponse(resp *bytes.Buffer, expected interface{}) error {
// Serialize expected response
expectedBytes, err := json.Marshal(expected)
if err != nil {
return fmt.Errorf("Failed to marshal expected response: %v", err)
}
// Compare
opts := jsondiff.DefaultConsoleOptions()
diff, text := jsondiff.Compare(resp.Bytes(), expectedBytes, &opts)
if diff.String() != "FullMatch" && diff.String() != "SupersetMatch" {
fmt.Println(text)
return fmt.Errorf("Response: Expected \"%v\". Got \"%v\".",
"(FullMatch OR SupersetMatch)", diff.String())
}
return nil
}
// Authenticate a user for testing purposes
func AuthenticateForTest(router *gin.Engine, url string,
method string, credentials interface{}) (string, error) {
w := httptest.NewRecorder()
// Marshal credentials
body, err := json.Marshal(credentials)
if err != nil {
return "", fmt.Errorf("Failed to marshal credentials: %v", err)
}
req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
if err != nil {
return "", fmt.Errorf("Faile to create new request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
// Check that return HTTP Code is 200 (OK)
if w.Code != http.StatusOK {
return "", fmt.Errorf("HTTP Code: Expected \"%v\". Got \"%v\".",
http.StatusOK, w.Code)
}
// Get the response
var body_data map[string]interface{}
err = json.Unmarshal([]byte(w.Body.String()), &body_data)
if err != nil {
return "", err
}
// Check the response
success, ok := body_data["success"].(bool)
if !ok {
return "", fmt.Errorf("Type asssertion of response[\"success\"] failed")
}
if !success {
return "", fmt.Errorf("Authentication failed: %v", body_data["message"])
}
// Extract the token
token, ok := body_data["token"].(string)
if !ok {
return "", fmt.Errorf("Type assertion of response[\"token\"] failed")
}
// Return the token and nil error
return token, nil
}

View file

@ -1,213 +0,0 @@
package common
import (
"encoding/json"
"github.com/jinzhu/gorm/dialects/postgres"
"golang.org/x/crypto/bcrypt"
"time"
)
// Users
var StrPassword0 = "xyz789"
var StrPasswordA = "abc123"
var StrPasswordB = "bcd234"
// 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 User0 = User{Username: "User_0", Password: string(pw0),
Role: "Admin", Mail: "User_0@example.com"}
var UserA = User{Username: "User_A", Password: string(pwA),
Role: "User", Mail: "User_A@example.com"}
var UserB = User{Username: "User_B", Password: string(pwB),
Role: "User", Mail: "User_B@example.com"}
// Credentials
type Credentials struct {
Username string
Password string
}
var AdminCredentials = Credentials{
Username: User0.Username,
Password: StrPassword0,
}
var UserACredentials = Credentials{
Username: UserA.Username,
Password: StrPasswordA,
}
var UserBCredentials = Credentials{
Username: UserB.Username,
Password: StrPasswordB,
}
// Simulators
var propertiesA = json.RawMessage(`{"name" : "TestNameA", "category" : "CategoryA", "location" : "anywhere on earth", "type": "dummy"}`)
var propertiesB = json.RawMessage(`{"name" : "TestNameB", "category" : "CategoryB", "location" : "where ever you want", "type": "generic"}`)
var SimulatorA = Simulator{
UUID: "4854af30-325f-44a5-ad59-b67b2597de68",
Host: "Host_A",
Modeltype: "ModelTypeA",
Uptime: 0,
State: "running",
StateUpdateAt: time.Now().String(),
Properties: postgres.Jsonb{propertiesA},
RawProperties: postgres.Jsonb{propertiesA},
}
var SimulatorB = Simulator{
UUID: "7be0322d-354e-431e-84bd-ae4c9633138b",
Host: "Host_B",
Modeltype: "ModelTypeB",
Uptime: 0,
State: "idle",
StateUpdateAt: time.Now().String(),
Properties: postgres.Jsonb{propertiesB},
RawProperties: postgres.Jsonb{propertiesB},
}
// Scenarios
var startParametersA = json.RawMessage(`{"parameter1" : "testValue1A", "parameter2" : "testValue2A", "parameter3" : 42}`)
var startParametersB = json.RawMessage(`{"parameter1" : "testValue1B", "parameter2" : "testValue2B", "parameter3" : 43}`)
var ScenarioA = Scenario{
Name: "Scenario_A",
Running: true,
StartParameters: postgres.Jsonb{startParametersA},
}
var ScenarioB = Scenario{
Name: "Scenario_B",
Running: false,
StartParameters: postgres.Jsonb{startParametersB},
}
// Simulation Models
var SimulationModelA = SimulationModel{
Name: "SimulationModel_A",
StartParameters: postgres.Jsonb{startParametersA},
}
var SimulationModelB = SimulationModel{
Name: "SimulationModel_B",
StartParameters: postgres.Jsonb{startParametersB},
}
// Signals
var OutSignalA = Signal{
Name: "outSignal_A",
Direction: "out",
Index: 0,
Unit: "V",
}
var OutSignalB = Signal{
Name: "outSignal_B",
Direction: "out",
Index: 1,
Unit: "V",
}
var InSignalA = Signal{
Name: "inSignal_A",
Direction: "in",
Index: 0,
Unit: "A",
}
var InSignalB = Signal{
Name: "inSignal_B",
Direction: "in",
Index: 1,
Unit: "A",
}
// Dashboards
var DashboardA = Dashboard{
Name: "Dashboard_A",
Grid: 15,
}
var DashboardB = Dashboard{
Name: "Dashboard_B",
Grid: 10,
}
// Files
var FileA = File{
Name: "File_A",
Type: "text/plain",
Size: 42,
ImageHeight: 333,
ImageWidth: 111,
Date: time.Now().String(),
}
var FileB = File{
Name: "File_B",
Type: "text/plain",
Size: 1234,
ImageHeight: 55,
ImageWidth: 22,
Date: time.Now().String(),
}
var FileC = File{
Name: "File_C",
Type: "text/plain",
Size: 32,
ImageHeight: 10,
ImageWidth: 10,
Date: time.Now().String(),
}
var FileD = File{
Name: "File_D",
Type: "text/plain",
Size: 5000,
ImageHeight: 400,
ImageWidth: 800,
Date: time.Now().String(),
}
// Widgets
var customPropertiesA = json.RawMessage(`{"property1" : "testValue1A", "property2" : "testValue2A", "property3" : 42}`)
var customPropertiesB = json.RawMessage(`{"property1" : "testValue1B", "property2" : "testValue2B", "property3" : 43}`)
var WidgetA = Widget{
Name: "Widget_A",
Type: "graph",
Width: 100,
Height: 50,
MinHeight: 40,
MinWidth: 80,
X: 10,
Y: 10,
Z: 10,
IsLocked: false,
CustomProperties: postgres.Jsonb{customPropertiesA},
}
var WidgetB = Widget{
Name: "Widget_B",
Type: "slider",
Width: 200,
Height: 20,
MinHeight: 10,
MinWidth: 50,
X: 100,
Y: -40,
Z: -1,
IsLocked: false,
CustomProperties: postgres.Jsonb{customPropertiesB},
}

View file

@ -1,272 +0,0 @@
package common
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"github.com/nsf/jsondiff"
"github.com/stretchr/testify/assert"
)
const UserIDCtx = "user_id"
const UserRoleCtx = "user_role"
// used in testing
type KeyModels map[string]interface{}
func ProvideErrorResponse(c *gin.Context, err error) bool {
if err != nil {
if err == gorm.ErrRecordNotFound {
errormsg := "Record not Found in DB: " + err.Error()
c.JSON(http.StatusNotFound, gin.H{
"success": false,
"message": errormsg,
})
} else {
errormsg := "Error on DB Query or transaction: " + err.Error()
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
"message": errormsg,
})
}
return true // Error
}
return false // No error
}
func GetResponseID(resp *bytes.Buffer) (int, error) {
// Transform bytes buffer into byte slice
respBytes := []byte(resp.String())
// Map JSON response to a map[string]map[string]interface{}
var respRemapped map[string]map[string]interface{}
err := json.Unmarshal(respBytes, &respRemapped)
if err != nil {
return 0, fmt.Errorf("Unmarshal failed for respRemapped %v", err)
}
// Get an arbitrary key from tha map. The only key (entry) of
// course is the model's name. With that trick we do not have to
// pass the higher level key as argument.
for arbitrary_key := range respRemapped {
// The marshaler turns numerical values into float64 types so we
// first have to make a type assertion to the interface and then
// the conversion to integer before returning
id, ok := respRemapped[arbitrary_key]["id"].(float64)
if !ok {
return 0, fmt.Errorf("Cannot type assert respRemapped")
}
return int(id), nil
}
return 0, fmt.Errorf("GetResponse reached exit")
}
func LengthOfResponse(router *gin.Engine, token string, url string,
method string, body []byte) (int, error) {
w := httptest.NewRecorder()
req, err := http.NewRequest(method, url, nil)
if err != nil {
return 0, fmt.Errorf("Failed to create new request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
// HTTP Code of response must be 200
if w.Code != 200 {
return 0, fmt.Errorf("HTTP Code: Expected \"200\". Got \"%v\""+
".\nResponse message:\n%v", w.Code, w.Body.String())
}
// Convert the response in array of bytes
responseBytes := []byte(w.Body.String())
// First we are trying to unmarshal the response into an array of
// general type variables ([]interface{}). If this fails we will try
// to unmarshal into a single general type variable (interface{}).
// If that also fails we will return 0.
// Response might be array of objects
var arrayResponse map[string][]interface{}
err = json.Unmarshal(responseBytes, &arrayResponse)
if err == nil {
// Get an arbitrary key from tha map. The only key (entry) of
// course is the model's name. With that trick we do not have to
// pass the higher level key as argument.
for arbitrary_key := range arrayResponse {
return len(arrayResponse[arbitrary_key]), nil
}
}
// Response might be a single object
var singleResponse map[string]interface{}
err = json.Unmarshal(responseBytes, &singleResponse)
if err == nil {
return 1, nil
}
// Failed to identify response.
return 0, fmt.Errorf("Length of response cannot be detected")
}
func NewTestEndpoint(router *gin.Engine, token string, url string,
method string, requestBody interface{}) (int, *bytes.Buffer, error) {
w := httptest.NewRecorder()
// Marshal the HTTP request body
body, err := json.Marshal(requestBody)
if err != nil {
return 0, nil, fmt.Errorf("Failed to marshal request body: %v", err)
}
// Create the request
req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
if err != nil {
return 0, nil, fmt.Errorf("Failed to create new request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
return w.Code, w.Body, nil
}
func CompareResponse(resp *bytes.Buffer, expected interface{}) error {
// Serialize expected response
expectedBytes, err := json.Marshal(expected)
if err != nil {
return fmt.Errorf("Failed to marshal expected response: %v", err)
}
// Compare
opts := jsondiff.DefaultConsoleOptions()
diff, text := jsondiff.Compare(resp.Bytes(), expectedBytes, &opts)
if diff.String() != "FullMatch" && diff.String() != "SupersetMatch" {
fmt.Println(text)
return fmt.Errorf("Response: Expected \"%v\". Got \"%v\".",
"(FullMatch OR SupersetMatch)", diff.String())
}
return nil
}
func TestEndpoint(t *testing.T, router *gin.Engine, token string, url string, method string, body []byte, expected_code int, expected_response []byte) {
w := httptest.NewRecorder()
if body != nil {
req, _ := http.NewRequest(method, url, bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
} else {
req, _ := http.NewRequest(method, url, nil)
req.Header.Add("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
}
assert.Equal(t, expected_code, w.Code)
//fmt.Println("Actual:", w.Body.String())
//fmt.Println("Expected: ", string(expected_response))
opts := jsondiff.DefaultConsoleOptions()
diff, _ := jsondiff.Compare(w.Body.Bytes(), expected_response, &opts)
assert.Equal(t, "FullMatch", diff.String())
}
func NewAuthenticateForTest(router *gin.Engine, url string,
method string, credentials interface{}) (string, error) {
w := httptest.NewRecorder()
// Marshal credentials
body, err := json.Marshal(credentials)
if err != nil {
return "", fmt.Errorf("Failed to marshal credentials: %v", err)
}
req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
if err != nil {
return "", fmt.Errorf("Faile to create new request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
// Check that return HTTP Code is 200 (OK)
if w.Code != http.StatusOK {
return "", fmt.Errorf("HTTP Code: Expected \"%v\". Got \"%v\".",
http.StatusOK, w.Code)
}
// Get the response
var body_data map[string]interface{}
err = json.Unmarshal([]byte(w.Body.String()), &body_data)
if err != nil {
return "", err
}
// Check the response
success, ok := body_data["success"].(bool)
if !ok {
return "", fmt.Errorf("Type asssertion of response[\"success\"] failed")
}
if !success {
return "", fmt.Errorf("Authentication failed: %v", body_data["message"])
}
// Extract the token
token, ok := body_data["token"].(string)
if !ok {
return "", fmt.Errorf("Type assertion of response[\"token\"] failed")
}
// Return the token and nil error
return token, nil
}
func AuthenticateForTest(t *testing.T, router *gin.Engine, url string, method string, body []byte, expected_code int) string {
w := httptest.NewRecorder()
req, _ := http.NewRequest(method, url, bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
assert.Equal(t, expected_code, w.Code)
var body_data map[string]interface{}
err := json.Unmarshal([]byte(w.Body.String()), &body_data)
if err != nil {
panic(err)
}
success := body_data["success"].(bool)
if !success {
fmt.Println("Authentication not successful: ", body_data["message"])
panic(-1)
}
fmt.Println(w.Body.String())
return body_data["token"].(string)
}
// Read the parameter with name paramName from the gin Context and
// return it as uint variable
func UintParamFromCtx(c *gin.Context, paramName string) (uint, error) {
param, err := strconv.Atoi(c.Param(paramName))
return uint(param), err
}

View file

@ -40,7 +40,7 @@ func getDashboards(c *gin.Context) {
db := common.GetDB()
var dab []common.Dashboard
err := db.Order("ID asc").Model(sim).Related(&dab, "Dashboards").Error
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
@ -95,7 +95,7 @@ func addDashboard(c *gin.Context) {
// add dashboard to DB and add association to scenario
err := newDashboard.addToScenario()
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -156,7 +156,7 @@ func updateDashboard(c *gin.Context) {
// update the dashboard in the DB
err = oldDashboard.update(updatedDashboard)
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -209,7 +209,7 @@ func deleteDashboard(c *gin.Context) {
}
err := dab.delete()
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}

View file

@ -48,7 +48,7 @@ func CheckPermissions(c *gin.Context, operation common.CRUD, dabIDSource string,
}
err = dab.ByID(uint(dabID))
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return false, dab
}

View file

@ -36,7 +36,7 @@ func addScenario(token string) (scenarioID uint) {
Running: common.ScenarioA.Running,
StartParameters: common.ScenarioA.StartParameters,
}
_, resp, _ := common.NewTestEndpoint(router, token,
_, resp, _ := common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenario})
// Read newScenario's ID from the response
@ -69,7 +69,7 @@ func TestAddDashboard(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -81,7 +81,7 @@ func TestAddDashboard(t *testing.T) {
Grid: common.DashboardA.Grid,
ScenarioID: scenarioID,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/dashboards", "POST", common.KeyModels{"dashboard": newDashboard})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -95,7 +95,7 @@ func TestAddDashboard(t *testing.T) {
assert.NoError(t, err)
// Get the newDashboard
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/dashboards/%v", newDashboardID), "GET", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -110,7 +110,7 @@ func TestAddDashboard(t *testing.T) {
Name: "ThisIsAMalformedDashboard",
}
// this should NOT work and return a unprocessable entity 442 status code
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/dashboards", "POST", common.KeyModels{"dashboard": malformedNewDashboard})
assert.NoError(t, err)
assert.Equalf(t, 422, code, "Response body: \n%v\n", resp)
@ -123,7 +123,7 @@ func TestUpdateDashboard(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -135,7 +135,7 @@ func TestUpdateDashboard(t *testing.T) {
Grid: common.DashboardA.Grid,
ScenarioID: scenarioID,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/dashboards", "POST", common.KeyModels{"dashboard": newDashboard})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -149,7 +149,7 @@ func TestUpdateDashboard(t *testing.T) {
Grid: common.DashboardB.Grid,
}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/dashboards/%v", newDashboardID), "PUT", common.KeyModels{"dashboard": updatedDashboard})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -159,7 +159,7 @@ func TestUpdateDashboard(t *testing.T) {
assert.NoError(t, err)
// Get the updatedDashboard
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/dashboards/%v", newDashboardID), "GET", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -169,7 +169,7 @@ func TestUpdateDashboard(t *testing.T) {
assert.NoError(t, err)
// try to update a dashboard that does not exist (should return not found 404 status code)
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/dashboards/%v", newDashboardID+1), "PUT", common.KeyModels{"dashboard": updatedDashboard})
assert.NoError(t, err)
assert.Equalf(t, 404, code, "Response body: \n%v\n", resp)
@ -182,7 +182,7 @@ func TestDeleteDashboard(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -195,7 +195,7 @@ func TestDeleteDashboard(t *testing.T) {
Grid: common.DashboardA.Grid,
ScenarioID: scenarioID,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/dashboards", "POST", common.KeyModels{"dashboard": newDashboard})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -210,7 +210,7 @@ func TestDeleteDashboard(t *testing.T) {
assert.NoError(t, err)
// Delete the added newDashboard
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/dashboards/%v", newDashboardID), "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -234,7 +234,7 @@ func TestGetAllDashboardsOfScenario(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -252,7 +252,7 @@ func TestGetAllDashboardsOfScenario(t *testing.T) {
Grid: common.DashboardA.Grid,
ScenarioID: scenarioID,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/dashboards", "POST", common.KeyModels{"dashboard": newDashboardA})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -263,7 +263,7 @@ func TestGetAllDashboardsOfScenario(t *testing.T) {
Grid: common.DashboardB.Grid,
ScenarioID: scenarioID,
}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/dashboards", "POST", common.KeyModels{"dashboard": newDashboardB})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)

View file

@ -74,12 +74,12 @@ func getFiles(c *gin.Context) {
var files []common.File
if objectType == "model" {
err = db.Order("ID asc").Model(&m).Related(&files, "Files").Error
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
} else {
err = db.Order("ID asc").Model(&w).Related(&files, "Files").Error
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
}
@ -157,7 +157,7 @@ func addFile(c *gin.Context) {
var newFile File
err = newFile.register(file_header, objectType, uint(objectID))
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -193,7 +193,7 @@ func getFile(c *gin.Context) {
err := f.download(c)
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -251,7 +251,7 @@ func updateFile(c *gin.Context) {
err = f.update(file_header)
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -282,7 +282,7 @@ func deleteFile(c *gin.Context) {
err := f.delete()
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}

View file

@ -33,7 +33,7 @@ func checkPermissions(c *gin.Context, operation common.CRUD) (bool, File) {
}
err = f.byID(uint(fileID))
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return false, f
}

View file

@ -48,7 +48,7 @@ type ScenarioRequest struct {
func addScenarioAndSimulatorAndSimulationModel() (scenarioID uint, simulatorID uint, simulationModelID uint) {
// authenticate as admin
token, _ := common.NewAuthenticateForTest(router,
token, _ := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
// POST $newSimulatorA
@ -59,14 +59,14 @@ func addScenarioAndSimulatorAndSimulationModel() (scenarioID uint, simulatorID u
State: common.SimulatorA.State,
Properties: common.SimulatorA.Properties,
}
_, resp, _ := common.NewTestEndpoint(router, token,
_, resp, _ := common.TestEndpoint(router, token,
"/api/simulators", "POST", common.KeyModels{"simulator": newSimulatorA})
// Read newSimulator's ID from the response
newSimulatorID, _ := common.GetResponseID(resp)
// authenticate as normal user
token, _ = common.NewAuthenticateForTest(router,
token, _ = common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
// POST $newScenario
@ -75,7 +75,7 @@ func addScenarioAndSimulatorAndSimulationModel() (scenarioID uint, simulatorID u
Running: common.ScenarioA.Running,
StartParameters: common.ScenarioA.StartParameters,
}
_, resp, _ = common.NewTestEndpoint(router, token,
_, resp, _ = common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenario})
// Read newScenario's ID from the response
@ -88,7 +88,7 @@ func addScenarioAndSimulatorAndSimulationModel() (scenarioID uint, simulatorID u
SimulatorID: uint(newSimulatorID),
StartParameters: common.SimulationModelA.StartParameters,
}
_, resp, _ = common.NewTestEndpoint(router, token,
_, resp, _ = common.TestEndpoint(router, token,
"/api/models", "POST", common.KeyModels{"model": newSimulationModel})
// Read newSimulationModel's ID from the response
@ -132,7 +132,7 @@ func TestAddFile(t *testing.T) {
_, _, simulationModelID := addScenarioAndSimulatorAndSimulationModel()
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -176,7 +176,7 @@ func TestAddFile(t *testing.T) {
assert.NoError(t, err)
// Get the new file
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
fmt.Sprintf("/api/files/%v", newFileID), "GET", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -195,7 +195,7 @@ func TestUpdateFile(t *testing.T) {
_, _, simulationModelID := addScenarioAndSimulatorAndSimulationModel()
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -278,7 +278,7 @@ func TestUpdateFile(t *testing.T) {
assert.Equal(t, newFileID, newFileIDUpdated)
// Get the updated file
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
fmt.Sprintf("/api/files/%v", newFileIDUpdated), "GET", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -296,7 +296,7 @@ func TestDeleteFile(t *testing.T) {
_, _, simulationModelID := addScenarioAndSimulatorAndSimulationModel()
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -345,7 +345,7 @@ func TestDeleteFile(t *testing.T) {
assert.NoError(t, err)
// Delete the added file
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
fmt.Sprintf("/api/files/%v", newFileID), "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -370,7 +370,7 @@ func TestGetAllFilesOfSimulationModel(t *testing.T) {
_, _, simulationModelID := addScenarioAndSimulatorAndSimulationModel()
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)

View file

@ -44,7 +44,7 @@ func getScenarios(c *gin.Context) {
var u user.User
err := u.ByID(userID.(uint))
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
@ -53,13 +53,13 @@ func getScenarios(c *gin.Context) {
var scenarios []common.Scenario
if userRole == "Admin" { // Admin can see all scenarios
err = db.Order("ID asc").Find(&scenarios).Error
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
} else { // User or Guest roles see only their scenarios
err = db.Order("ID asc").Model(&u).Related(&scenarios, "Scenarios").Error
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
}
@ -93,7 +93,7 @@ func addScenario(c *gin.Context) {
var u user.User
err := u.ByID(userID.(uint))
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
@ -121,14 +121,14 @@ func addScenario(c *gin.Context) {
// Save the new scenario in the DB
err = newScenario.save()
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
// add user to new scenario
err = newScenario.addUser(&(u.User))
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -190,7 +190,7 @@ func updateScenario(c *gin.Context) {
// Finally update the scenario
err = oldScenario.update(updatedScenario)
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -243,7 +243,7 @@ func deleteScenario(c *gin.Context) {
err := so.delete()
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -272,7 +272,7 @@ func getUsersOfScenario(c *gin.Context) {
// Find all users of scenario
allUsers, _, err := so.getUsers()
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
@ -302,12 +302,12 @@ func addUserToScenario(c *gin.Context) {
var u user.User
err := u.ByUsername(username)
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
err = so.addUser(&(u.User))
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
@ -339,12 +339,12 @@ func deleteUserFromScenario(c *gin.Context) {
var u user.User
err := u.ByUsername(username)
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
err = so.deleteUser(username)
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}

View file

@ -61,7 +61,7 @@ func CheckPermissions(c *gin.Context, operation common.CRUD, screnarioIDSource s
userRole, _ := c.Get(common.UserRoleCtx)
err = so.ByID(uint(scenarioID))
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return false, so
}

View file

@ -44,7 +44,7 @@ func TestAddScenario(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -54,7 +54,7 @@ func TestAddScenario(t *testing.T) {
Running: common.ScenarioA.Running,
StartParameters: common.ScenarioA.StartParameters,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenario})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -68,7 +68,7 @@ func TestAddScenario(t *testing.T) {
assert.NoError(t, err)
// Get the newScenario
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/scenarios/%v", newScenarioID), "GET", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -83,7 +83,7 @@ func TestAddScenario(t *testing.T) {
Running: false,
}
// this should NOT work and return a unprocessable entity 442 status code
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": malformedNewScenario})
assert.NoError(t, err)
assert.Equalf(t, 422, code, "Response body: \n%v\n", resp)
@ -96,7 +96,7 @@ func TestUpdateScenario(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -106,7 +106,7 @@ func TestUpdateScenario(t *testing.T) {
Running: common.ScenarioA.Running,
StartParameters: common.ScenarioA.StartParameters,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenario})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -125,7 +125,7 @@ func TestUpdateScenario(t *testing.T) {
StartParameters: common.ScenarioA.StartParameters,
}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/scenarios/%v", newScenarioID), "PUT", common.KeyModels{"scenario": updatedScenario})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -135,7 +135,7 @@ func TestUpdateScenario(t *testing.T) {
assert.NoError(t, err)
// Get the updatedScenario
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/scenarios/%v", newScenarioID), "GET", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -145,7 +145,7 @@ func TestUpdateScenario(t *testing.T) {
assert.NoError(t, err)
// try to update a scenario that does not exist (should return not found 404 status code)
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/scenarios/%v", newScenarioID+1), "PUT", common.KeyModels{"scenario": updatedScenario})
assert.NoError(t, err)
assert.Equalf(t, 404, code, "Response body: \n%v\n", resp)
@ -159,7 +159,7 @@ func TestGetAllScenariosAsAdmin(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -169,7 +169,7 @@ func TestGetAllScenariosAsAdmin(t *testing.T) {
assert.NoError(t, err)
// authenticate as normal userB
token, err = common.NewAuthenticateForTest(router,
token, err = common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserBCredentials)
assert.NoError(t, err)
@ -179,13 +179,13 @@ func TestGetAllScenariosAsAdmin(t *testing.T) {
Running: common.ScenarioB.Running,
StartParameters: common.ScenarioB.StartParameters,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenarioB})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
// authenticate as normal userA
token, err = common.NewAuthenticateForTest(router,
token, err = common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -195,13 +195,13 @@ func TestGetAllScenariosAsAdmin(t *testing.T) {
Running: common.ScenarioA.Running,
StartParameters: common.ScenarioA.StartParameters,
}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenarioA})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
// authenticate as admin
token, err = common.NewAuthenticateForTest(router,
token, err = common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -220,7 +220,7 @@ func TestGetAllScenariosAsUser(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal userB
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserBCredentials)
assert.NoError(t, err)
@ -236,13 +236,13 @@ func TestGetAllScenariosAsUser(t *testing.T) {
StartParameters: common.ScenarioB.StartParameters,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenarioB})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
// authenticate as normal userA
token, err = common.NewAuthenticateForTest(router,
token, err = common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -252,13 +252,13 @@ func TestGetAllScenariosAsUser(t *testing.T) {
Running: common.ScenarioA.Running,
StartParameters: common.ScenarioA.StartParameters,
}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenarioA})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
// authenticate as normal userB
token, err = common.NewAuthenticateForTest(router,
token, err = common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserBCredentials)
assert.NoError(t, err)
@ -277,7 +277,7 @@ func TestDeleteScenario(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -287,7 +287,7 @@ func TestDeleteScenario(t *testing.T) {
Running: common.ScenarioA.Running,
StartParameters: common.ScenarioA.StartParameters,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenario})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -302,7 +302,7 @@ func TestDeleteScenario(t *testing.T) {
assert.NoError(t, err)
// Delete the added newScenario
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/scenarios/%v", newScenarioID), "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -326,7 +326,7 @@ func TestAddUserToScenario(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -336,7 +336,7 @@ func TestAddUserToScenario(t *testing.T) {
Running: common.ScenarioA.Running,
StartParameters: common.ScenarioA.StartParameters,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenario})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -352,7 +352,7 @@ func TestAddUserToScenario(t *testing.T) {
assert.Equal(t, initialNumber, 1)
// add userB to newScenario
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/scenarios/%v/user?username=User_B", newScenarioID), "PUT", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -368,7 +368,7 @@ func TestAddUserToScenario(t *testing.T) {
assert.Equal(t, finalNumber, initialNumber+1)
// try to add a non-existing user to newScenario, should return a not found 404
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/scenarios/%v/user?username=User_C", newScenarioID), "PUT", nil)
assert.NoError(t, err)
assert.Equalf(t, 404, code, "Response body: \n%v\n", resp)
@ -381,7 +381,7 @@ func TestGetAllUsersOfScenario(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -391,7 +391,7 @@ func TestGetAllUsersOfScenario(t *testing.T) {
Running: common.ScenarioA.Running,
StartParameters: common.ScenarioA.StartParameters,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenario})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -407,7 +407,7 @@ func TestGetAllUsersOfScenario(t *testing.T) {
assert.Equal(t, initialNumber, 1)
// add userB to newScenario
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/scenarios/%v/user?username=User_B", newScenarioID), "PUT", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -426,7 +426,7 @@ func TestRemoveUserFromScenario(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -436,7 +436,7 @@ func TestRemoveUserFromScenario(t *testing.T) {
Running: common.ScenarioA.Running,
StartParameters: common.ScenarioA.StartParameters,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenario})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -446,7 +446,7 @@ func TestRemoveUserFromScenario(t *testing.T) {
assert.NoError(t, err)
// add userB to newScenario
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/scenarios/%v/user?username=User_B", newScenarioID), "PUT", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -458,7 +458,7 @@ func TestRemoveUserFromScenario(t *testing.T) {
assert.Equal(t, 2, initialNumber)
// remove userB from newScenario
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/scenarios/%v/user?username=User_B", newScenarioID), "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -475,21 +475,21 @@ func TestRemoveUserFromScenario(t *testing.T) {
// Try to remove userA from new scenario
// This should fail since User_A is the last user of newScenario
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/scenarios/%v/user?username=User_A", newScenarioID), "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 500, code, "Response body: \n%v\n", resp)
// Try to remove a user that does not exist in DB
// This should fail with not found 404 status code
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/scenarios/%v/user?username=User_C", newScenarioID), "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 404, code, "Response body: \n%v\n", resp)
// Try to remove an admin user that is not explicitly a user of the scenario
// This should fail with not found 404 status code
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/scenarios/%v/user?username=User_0", newScenarioID), "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 404, code, "Response body: \n%v\n", resp)

View file

@ -54,7 +54,7 @@ func getSignals(c *gin.Context) {
db := common.GetDB()
var sigs []common.Signal
err := db.Order("ID asc").Model(m).Where("Direction = ?", direction).Related(&sigs, mapping).Error
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
@ -107,7 +107,7 @@ func addSignal(c *gin.Context) {
// Add signal to model
err := newSignal.addToSimulationModel()
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -166,7 +166,7 @@ func updateSignal(c *gin.Context) {
// Update the signal in the DB
err = oldSignal.update(updatedSignal)
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -219,7 +219,7 @@ func deleteSignal(c *gin.Context) {
err := sig.delete()
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}

View file

@ -34,7 +34,7 @@ func checkPermissions(c *gin.Context, operation common.CRUD) (bool, Signal) {
}
err = sig.byID(uint(signalID))
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return false, sig
}

View file

@ -50,7 +50,7 @@ type ScenarioRequest struct {
func addScenarioAndSimulatorAndSimulationModel() (scenarioID uint, simulatorID uint, simulationModelID uint) {
// authenticate as admin
token, _ := common.NewAuthenticateForTest(router,
token, _ := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
// POST $newSimulatorA
@ -61,14 +61,14 @@ func addScenarioAndSimulatorAndSimulationModel() (scenarioID uint, simulatorID u
State: common.SimulatorA.State,
Properties: common.SimulatorA.Properties,
}
_, resp, _ := common.NewTestEndpoint(router, token,
_, resp, _ := common.TestEndpoint(router, token,
"/api/simulators", "POST", common.KeyModels{"simulator": newSimulatorA})
// Read newSimulator's ID from the response
newSimulatorID, _ := common.GetResponseID(resp)
// authenticate as normal user
token, _ = common.NewAuthenticateForTest(router,
token, _ = common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
// POST $newScenario
@ -77,7 +77,7 @@ func addScenarioAndSimulatorAndSimulationModel() (scenarioID uint, simulatorID u
Running: common.ScenarioA.Running,
StartParameters: common.ScenarioA.StartParameters,
}
_, resp, _ = common.NewTestEndpoint(router, token,
_, resp, _ = common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenario})
// Read newScenario's ID from the response
@ -90,7 +90,7 @@ func addScenarioAndSimulatorAndSimulationModel() (scenarioID uint, simulatorID u
SimulatorID: uint(newSimulatorID),
StartParameters: common.SimulationModelA.StartParameters,
}
_, resp, _ = common.NewTestEndpoint(router, token,
_, resp, _ = common.TestEndpoint(router, token,
"/api/models", "POST", common.KeyModels{"model": newSimulationModel})
// Read newSimulationModel's ID from the response
@ -134,7 +134,7 @@ func TestAddSignal(t *testing.T) {
_, _, simulationModelID := addScenarioAndSimulatorAndSimulationModel()
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -146,7 +146,7 @@ func TestAddSignal(t *testing.T) {
Index: 1,
SimulationModelID: simulationModelID,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/signals", "POST", common.KeyModels{"signal": newSignal})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -160,7 +160,7 @@ func TestAddSignal(t *testing.T) {
assert.NoError(t, err)
// Get the newSignal
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/signals/%v", newSignalID), "GET", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -175,7 +175,7 @@ func TestAddSignal(t *testing.T) {
Name: "ThisIsAMalformedRequest",
}
// this should NOT work and return a unprocessable entity 442 status code
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/signals", "POST", common.KeyModels{"model": malformedNewSignal})
assert.NoError(t, err)
assert.Equalf(t, 422, code, "Response body: \n%v\n", resp)
@ -192,7 +192,7 @@ func TestUpdateSignal(t *testing.T) {
_, _, simulationModelID := addScenarioAndSimulatorAndSimulationModel()
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -204,7 +204,7 @@ func TestUpdateSignal(t *testing.T) {
Index: 1,
SimulationModelID: simulationModelID,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/signals", "POST", common.KeyModels{"signal": newSignal})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -218,7 +218,7 @@ func TestUpdateSignal(t *testing.T) {
Unit: common.InSignalB.Unit,
Index: 1,
}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/signals/%v", newSignalID), "PUT", common.KeyModels{"signal": updatedSignal})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -228,7 +228,7 @@ func TestUpdateSignal(t *testing.T) {
assert.NoError(t, err)
// Get the updatedSignal
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/signals/%v", newSignalID), "GET", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -238,7 +238,7 @@ func TestUpdateSignal(t *testing.T) {
assert.NoError(t, err)
// try to update a signal that does not exist (should return not found 404 status code)
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/signals/%v", newSignalID+1), "PUT", common.KeyModels{"signal": updatedSignal})
assert.NoError(t, err)
assert.Equalf(t, 404, code, "Response body: \n%v\n", resp)
@ -256,7 +256,7 @@ func TestDeleteSignal(t *testing.T) {
_, _, simulationModelID := addScenarioAndSimulatorAndSimulationModel()
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -268,7 +268,7 @@ func TestDeleteSignal(t *testing.T) {
Index: 1,
SimulationModelID: simulationModelID,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/signals", "POST", common.KeyModels{"signal": newSignal})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -290,13 +290,13 @@ func TestDeleteSignal(t *testing.T) {
Index: 1,
SimulationModelID: simulationModelID,
}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/signals", "POST", common.KeyModels{"signal": newSignalout})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
// Delete the added newSignal
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/signals/%v", newSignalID), "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -324,7 +324,7 @@ func TestGetAllInputSignalsOfSimulationModel(t *testing.T) {
_, _, simulationModelID := addScenarioAndSimulatorAndSimulationModel()
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -341,7 +341,7 @@ func TestGetAllInputSignalsOfSimulationModel(t *testing.T) {
Index: 1,
SimulationModelID: simulationModelID,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/signals", "POST", common.KeyModels{"signal": newSignalA})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -354,7 +354,7 @@ func TestGetAllInputSignalsOfSimulationModel(t *testing.T) {
Index: 2,
SimulationModelID: simulationModelID,
}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/signals", "POST", common.KeyModels{"signal": newSignalB})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -367,7 +367,7 @@ func TestGetAllInputSignalsOfSimulationModel(t *testing.T) {
Index: 1,
SimulationModelID: simulationModelID,
}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/signals", "POST", common.KeyModels{"signal": newSignalAout})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -380,7 +380,7 @@ func TestGetAllInputSignalsOfSimulationModel(t *testing.T) {
Index: 1,
SimulationModelID: simulationModelID,
}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/signals", "POST", common.KeyModels{"signal": newSignalBout})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)

View file

@ -39,7 +39,7 @@ func getSimulationModels(c *gin.Context) {
db := common.GetDB()
var models []common.SimulationModel
err := db.Order("ID asc").Model(so).Related(&models, "Models").Error
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
@ -95,7 +95,7 @@ func addSimulationModel(c *gin.Context) {
// add the new simulation model to the scenario
err = newSimulationModel.addToScenario()
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -157,7 +157,7 @@ func updateSimulationModel(c *gin.Context) {
// Finally, update the simulation model
err = oldSimulationModel.Update(updatedSimulationModel)
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -211,7 +211,7 @@ func deleteSimulationModel(c *gin.Context) {
}
err := m.delete()
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}

View file

@ -49,7 +49,7 @@ func CheckPermissions(c *gin.Context, operation common.CRUD, modelIDSource strin
}
err = m.ByID(uint(modelID))
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return false, m
}

View file

@ -41,7 +41,7 @@ type ScenarioRequest struct {
func addScenarioAndSimulator() (scenarioID uint, simulatorID uint) {
// authenticate as admin
token, _ := common.NewAuthenticateForTest(router,
token, _ := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
// POST $newSimulatorA
@ -52,14 +52,14 @@ func addScenarioAndSimulator() (scenarioID uint, simulatorID uint) {
State: common.SimulatorA.State,
Properties: common.SimulatorA.Properties,
}
_, resp, _ := common.NewTestEndpoint(router, token,
_, resp, _ := common.TestEndpoint(router, token,
"/api/simulators", "POST", common.KeyModels{"simulator": newSimulatorA})
// Read newSimulator's ID from the response
newSimulatorID, _ := common.GetResponseID(resp)
// authenticate as normal user
token, _ = common.NewAuthenticateForTest(router,
token, _ = common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
// POST $newScenario
@ -68,7 +68,7 @@ func addScenarioAndSimulator() (scenarioID uint, simulatorID uint) {
Running: common.ScenarioA.Running,
StartParameters: common.ScenarioA.StartParameters,
}
_, resp, _ = common.NewTestEndpoint(router, token,
_, resp, _ = common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenario})
// Read newScenario's ID from the response
@ -109,7 +109,7 @@ func TestAddSimulationModel(t *testing.T) {
scenarioID, simulatorID := addScenarioAndSimulator()
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -120,7 +120,7 @@ func TestAddSimulationModel(t *testing.T) {
SimulatorID: simulatorID,
StartParameters: common.SimulationModelA.StartParameters,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/models", "POST", common.KeyModels{"model": newSimulationModel})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -134,7 +134,7 @@ func TestAddSimulationModel(t *testing.T) {
assert.NoError(t, err)
// Get the newSimulationModel
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/models/%v", newSimulationModelID), "GET", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -149,7 +149,7 @@ func TestAddSimulationModel(t *testing.T) {
Name: "ThisIsAMalformedRequest",
}
// this should NOT work and return a unprocessable entity 442 status code
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/models", "POST", common.KeyModels{"model": malformedNewSimulationModel})
assert.NoError(t, err)
assert.Equalf(t, 422, code, "Response body: \n%v\n", resp)
@ -168,7 +168,7 @@ func TestUpdateSimulationModel(t *testing.T) {
scenarioID, simulatorID := addScenarioAndSimulator()
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -179,7 +179,7 @@ func TestUpdateSimulationModel(t *testing.T) {
SimulatorID: simulatorID,
StartParameters: common.SimulationModelA.StartParameters,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/models", "POST", common.KeyModels{"model": newSimulationModel})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -193,7 +193,7 @@ func TestUpdateSimulationModel(t *testing.T) {
StartParameters: common.SimulationModelB.StartParameters,
}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/models/%v", newSimulationModelID), "PUT", common.KeyModels{"model": updatedSimulationModel})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -203,7 +203,7 @@ func TestUpdateSimulationModel(t *testing.T) {
assert.NoError(t, err)
// Get the updatedSimulationModel
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/models/%v", newSimulationModelID), "GET", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -213,7 +213,7 @@ func TestUpdateSimulationModel(t *testing.T) {
assert.NoError(t, err)
// try to update a simulation model that does not exist (should return not found 404 status code)
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/models/%v", newSimulationModelID+1), "PUT", common.KeyModels{"model": updatedSimulationModel})
assert.NoError(t, err)
assert.Equalf(t, 404, code, "Response body: \n%v\n", resp)
@ -230,7 +230,7 @@ func TestDeleteSimulationModel(t *testing.T) {
scenarioID, simulatorID := addScenarioAndSimulator()
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -241,7 +241,7 @@ func TestDeleteSimulationModel(t *testing.T) {
SimulatorID: simulatorID,
StartParameters: common.SimulationModelA.StartParameters,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/models", "POST", common.KeyModels{"model": newSimulationModel})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -256,7 +256,7 @@ func TestDeleteSimulationModel(t *testing.T) {
assert.NoError(t, err)
// Delete the added newSimulationModel
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/models/%v", newSimulationModelID), "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -284,7 +284,7 @@ func TestGetAllSimulationModelsOfScenario(t *testing.T) {
scenarioID, simulatorID := addScenarioAndSimulator()
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -295,7 +295,7 @@ func TestGetAllSimulationModelsOfScenario(t *testing.T) {
SimulatorID: simulatorID,
StartParameters: common.SimulationModelA.StartParameters,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/models", "POST", common.KeyModels{"model": newSimulationModel})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)

View file

@ -43,7 +43,7 @@ func getSimulators(c *gin.Context) {
db := common.GetDB()
var simulators []common.Simulator
err := db.Order("ID asc").Find(&simulators).Error
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
@ -98,7 +98,7 @@ func addSimulator(c *gin.Context) {
// Save new simulator to DB
err = newSimulator.save()
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -160,7 +160,7 @@ func updateSimulator(c *gin.Context) {
// Finally update the simulator in the DB
err = oldSimulator.update(updatedSimulator)
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -215,7 +215,7 @@ func deleteSimulator(c *gin.Context) {
// Delete the simulator
err := s.delete()
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
@ -245,7 +245,7 @@ func getModelsOfSimulator(c *gin.Context) {
// get all associated simulation models
allModels, _, err := s.getModels()
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}

View file

@ -5,6 +5,7 @@ import (
"git.rwth-aachen.de/acs/public/villas/villasweb-backend-go/common"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
func checkPermissions(c *gin.Context, modeltype common.ModelName, operation common.CRUD, hasID bool) (bool, Simulator) {
@ -22,7 +23,7 @@ func checkPermissions(c *gin.Context, modeltype common.ModelName, operation comm
if hasID {
// Get the ID of the simulator from the context
simulatorID, err := common.UintParamFromCtx(c, "simulatorID")
simulatorID, err := strconv.Atoi(c.Param("simulatorID"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
@ -32,7 +33,7 @@ func checkPermissions(c *gin.Context, modeltype common.ModelName, operation comm
}
err = s.ByID(uint(simulatorID))
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return false, s
}

View file

@ -46,7 +46,7 @@ func TestAddSimulatorAsAdmin(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -58,7 +58,7 @@ func TestAddSimulatorAsAdmin(t *testing.T) {
State: common.SimulatorA.State,
Properties: common.SimulatorA.Properties,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/simulators", "POST", common.KeyModels{"simulator": newSimulator})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -72,7 +72,7 @@ func TestAddSimulatorAsAdmin(t *testing.T) {
assert.NoError(t, err)
// Get the newSimulator
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/simulators/%v", newSimulatorID), "GET", nil)
assert.NoError(t, err)
@ -89,7 +89,7 @@ func TestAddSimulatorAsUser(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -104,7 +104,7 @@ func TestAddSimulatorAsUser(t *testing.T) {
// This should fail with unprocessable entity 422 error code
// Normal users are not allowed to add simulators
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/simulators", "POST", common.KeyModels{"simulator": newSimulator})
assert.NoError(t, err)
assert.Equalf(t, 422, code, "Response body: \n%v\n", resp)
@ -116,7 +116,7 @@ func TestUpdateSimulatorAsAdmin(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -128,7 +128,7 @@ func TestUpdateSimulatorAsAdmin(t *testing.T) {
State: common.SimulatorA.State,
Properties: common.SimulatorA.Properties,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/simulators", "POST", common.KeyModels{"simulator": newSimulator})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -143,7 +143,7 @@ func TestUpdateSimulatorAsAdmin(t *testing.T) {
// Test PUT simulators
newSimulator.Host = "ThisIsMyNewHost"
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/simulators/%v", newSimulatorID), "PUT", common.KeyModels{"simulator": newSimulator})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -153,7 +153,7 @@ func TestUpdateSimulatorAsAdmin(t *testing.T) {
assert.NoError(t, err)
// Get the updated newSimulator
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/simulators/%v", newSimulatorID), "GET", nil)
assert.NoError(t, err)
@ -171,7 +171,7 @@ func TestUpdateSimulatorAsUser(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -183,7 +183,7 @@ func TestUpdateSimulatorAsUser(t *testing.T) {
State: common.SimulatorA.State,
Properties: common.SimulatorA.Properties,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/simulators", "POST", common.KeyModels{"simulator": newSimulator})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -193,14 +193,14 @@ func TestUpdateSimulatorAsUser(t *testing.T) {
assert.NoError(t, err)
// authenticate as user
token, err = common.NewAuthenticateForTest(router,
token, err = common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
// Test PUT simulators
// This should fail with unprocessable entity status code 422
newSimulator.Host = "ThisIsMyNewHost"
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/simulators/%v", newSimulatorID), "PUT", common.KeyModels{"simulator": newSimulator})
assert.NoError(t, err)
assert.Equalf(t, 422, code, "Response body: \n%v\n", resp)
@ -213,7 +213,7 @@ func TestDeleteSimulatorAsAdmin(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -225,7 +225,7 @@ func TestDeleteSimulatorAsAdmin(t *testing.T) {
State: common.SimulatorA.State,
Properties: common.SimulatorA.Properties,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/simulators", "POST", common.KeyModels{"simulator": newSimulator})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -240,7 +240,7 @@ func TestDeleteSimulatorAsAdmin(t *testing.T) {
assert.NoError(t, err)
// Delete the added newSimulator
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/simulators/%v", newSimulatorID), "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -263,7 +263,7 @@ func TestDeleteSimulatorAsUser(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -275,7 +275,7 @@ func TestDeleteSimulatorAsUser(t *testing.T) {
State: common.SimulatorA.State,
Properties: common.SimulatorA.Properties,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/simulators", "POST", common.KeyModels{"simulator": newSimulator})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -285,14 +285,14 @@ func TestDeleteSimulatorAsUser(t *testing.T) {
assert.NoError(t, err)
// authenticate as user
token, err = common.NewAuthenticateForTest(router,
token, err = common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
// Test DELETE simulators
// This should fail with unprocessable entity status code 422
newSimulator.Host = "ThisIsMyNewHost"
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/simulators/%v", newSimulatorID), "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 422, code, "Response body: \n%v\n", resp)
@ -304,7 +304,7 @@ func TestGetAllSimulators(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -321,7 +321,7 @@ func TestGetAllSimulators(t *testing.T) {
State: common.SimulatorA.State,
Properties: common.SimulatorA.Properties,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/simulators", "POST", common.KeyModels{"simulator": newSimulatorA})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -334,7 +334,7 @@ func TestGetAllSimulators(t *testing.T) {
State: common.SimulatorB.State,
Properties: common.SimulatorB.Properties,
}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/simulators", "POST", common.KeyModels{"simulator": newSimulatorB})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -347,7 +347,7 @@ func TestGetAllSimulators(t *testing.T) {
assert.Equal(t, finalNumber, initialNumber+2)
// authenticate as normal user
token, err = common.NewAuthenticateForTest(router,
token, err = common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -365,7 +365,7 @@ func TestGetSimulationModelsOfSimulator(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -377,7 +377,7 @@ func TestGetSimulationModelsOfSimulator(t *testing.T) {
State: common.SimulatorA.State,
Properties: common.SimulatorA.Properties,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/simulators", "POST", common.KeyModels{"simulator": newSimulatorA})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -396,7 +396,7 @@ func TestGetSimulationModelsOfSimulator(t *testing.T) {
assert.Equal(t, 0, numberOfModels)
// authenticate as normal user
token, err = common.NewAuthenticateForTest(router,
token, err = common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)

View file

@ -3,6 +3,7 @@ package user
import (
"fmt"
"net/http"
"strconv"
"strings"
"time"
@ -153,7 +154,7 @@ func getUsers(c *gin.Context) {
db := common.GetDB()
var users []common.User
err = db.Order("ID asc").Find(&users).Error
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
@ -230,7 +231,7 @@ func addUser(c *gin.Context) {
// Save the user in the DB
err = newUser.save()
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -267,7 +268,7 @@ func updateUser(c *gin.Context) {
// Get the user's (to be updated) ID from the context
var oldUser User
toBeUpdatedID, err := common.UintParamFromCtx(c, "userID")
toBeUpdatedID, err := strconv.Atoi("userID")
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"success": false,
@ -277,9 +278,9 @@ func updateUser(c *gin.Context) {
}
// Find the user
err = oldUser.ByID(toBeUpdatedID)
err = oldUser.ByID(uint(toBeUpdatedID))
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -361,7 +362,7 @@ func updateUser(c *gin.Context) {
// Finally update the user
err = oldUser.update(updatedUser)
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -393,7 +394,7 @@ func getUser(c *gin.Context) {
return
}
id, err := common.UintParamFromCtx(c, "userID")
id, err := strconv.Atoi("userID")
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"success": false,
@ -414,9 +415,9 @@ func getUser(c *gin.Context) {
}
var user User
err = user.ByID(id)
err = user.ByID(uint(id))
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -448,7 +449,7 @@ func deleteUser(c *gin.Context) {
}
var user User
id, err := common.UintParamFromCtx(c, "userID")
id, err := strconv.Atoi("userID")
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"success": false,
@ -460,14 +461,14 @@ func deleteUser(c *gin.Context) {
// Check that the user exist
err = user.ByID(uint(id))
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
// Try to remove user
err = user.remove()
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}

View file

@ -44,7 +44,7 @@ func TestAddGetUser(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -55,7 +55,7 @@ func TestAddGetUser(t *testing.T) {
Mail: "mail@domain.com",
Role: "User",
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/users", "POST", common.KeyModels{"user": newUser})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -75,7 +75,7 @@ func TestAddGetUser(t *testing.T) {
assert.NoError(t, err)
// Get the newUser
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "GET", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -92,7 +92,7 @@ func TestUsersNotAllowedActions(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -103,7 +103,7 @@ func TestUsersNotAllowedActions(t *testing.T) {
Mail: "not@allowed.ac",
Role: "User",
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/users", "POST", common.KeyModels{"user": newUser})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -112,7 +112,7 @@ func TestUsersNotAllowedActions(t *testing.T) {
assert.NoError(t, err)
// Authenticate as the added user
token, err = common.NewAuthenticateForTest(router,
token, err = common.AuthenticateForTest(router,
"/api/authenticate", "POST", UserRequest{
Username: newUser.Username,
Password: newUser.Password,
@ -120,25 +120,25 @@ func TestUsersNotAllowedActions(t *testing.T) {
assert.NoError(t, err)
// Try to get all the users (NOT ALLOWED)
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/users", "POST", common.KeyModels{"user": newUser})
assert.NoError(t, err)
assert.Equalf(t, 422, code, "Response body: \n%v\n", resp)
// Try to read another user than self (eg. Admin) (NOT ALLOWED)
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/users/0", "GET", nil)
assert.NoError(t, err)
assert.Equalf(t, 403, code, "Response body: \n%v\n", resp)
// Try to delete another user (eg. Admin) (NOT ALLOWED)
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/users/0", "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 422, code, "Response body: \n%v\n", resp)
// Try to delete self (NOT ALLOWED)
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 422, code, "Response body: \n%v\n", resp)
@ -152,7 +152,7 @@ func TestGetAllUsers(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -168,7 +168,7 @@ func TestGetAllUsers(t *testing.T) {
Mail: "get@all.users",
Role: "User",
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/users", "POST", common.KeyModels{"user": newUser})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -188,7 +188,7 @@ func TestModifyAddedUserAsUser(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -199,7 +199,7 @@ func TestModifyAddedUserAsUser(t *testing.T) {
Mail: "mod@my.self",
Role: "User",
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/users", "POST", common.KeyModels{"user": newUser})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -208,7 +208,7 @@ func TestModifyAddedUserAsUser(t *testing.T) {
assert.NoError(t, err)
// authenticate as the new user
token, err = common.NewAuthenticateForTest(router,
token, err = common.AuthenticateForTest(router,
"/api/authenticate", "POST", UserRequest{
Username: newUser.Username,
Password: newUser.Password,
@ -224,7 +224,7 @@ func TestModifyAddedUserAsUser(t *testing.T) {
// modify newUser's own name
modRequest := UserRequest{Username: "myNewName"}
newUser.Username = modRequest.Username
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "PUT",
common.KeyModels{"user": modRequest})
assert.NoError(t, err)
@ -235,7 +235,7 @@ func TestModifyAddedUserAsUser(t *testing.T) {
// modify Admin's name (ILLEGAL)
modRequest = UserRequest{Username: "myNewName"}
newUser.Username = modRequest.Username
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/users/1", "PUT", common.KeyModels{"user": modRequest})
assert.NoError(t, err)
assert.Equalf(t, 403, code, "Response body: \n%v\n", resp)
@ -243,7 +243,7 @@ func TestModifyAddedUserAsUser(t *testing.T) {
// modify newUser's own email
modRequest = UserRequest{Mail: "my@new.email"}
newUser.Mail = modRequest.Mail
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "PUT",
common.KeyModels{"user": modRequest})
assert.NoError(t, err)
@ -254,7 +254,7 @@ func TestModifyAddedUserAsUser(t *testing.T) {
// modify Admin's own email (ILLEGAL)
modRequest = UserRequest{Mail: "my@new.email"}
newUser.Mail = modRequest.Mail
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/users/1", "PUT", common.KeyModels{"user": modRequest})
assert.NoError(t, err)
assert.Equalf(t, 403, code, "Response body: \n%v\n", resp)
@ -262,7 +262,7 @@ func TestModifyAddedUserAsUser(t *testing.T) {
// modify newUser's role (ILLEGAL)
modRequest = UserRequest{Role: "Admin"}
newUser.Role = modRequest.Role
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "PUT",
common.KeyModels{"user": modRequest})
assert.NoError(t, err)
@ -270,14 +270,14 @@ func TestModifyAddedUserAsUser(t *testing.T) {
// modify newUser's password
modRequest = UserRequest{Password: "5tr0ng_pw!"}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "PUT",
common.KeyModels{"user": modRequest})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
// try to login as newUser with the modified username and password
token, err = common.NewAuthenticateForTest(router,
token, err = common.AuthenticateForTest(router,
"/api/authenticate", "POST", UserRequest{
Username: newUser.Username,
Password: modRequest.Password,
@ -286,7 +286,7 @@ func TestModifyAddedUserAsUser(t *testing.T) {
// modify Admin's password (ILLEGAL)
modRequest = UserRequest{Password: "4dm1ns_pw!"}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/users/1", "PUT", common.KeyModels{"user": modRequest})
assert.NoError(t, err)
assert.Equalf(t, 403, code, "Response body: \n%v\n", resp)
@ -299,7 +299,7 @@ func TestInvalidUserUpdate(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -310,7 +310,7 @@ func TestInvalidUserUpdate(t *testing.T) {
Mail: "inv@user.upd",
Role: "User",
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/users", "POST", common.KeyModels{"user": newUser})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -320,7 +320,7 @@ func TestInvalidUserUpdate(t *testing.T) {
// modify newUser's password with INVALID password
modRequest := UserRequest{Password: "short"}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "PUT",
common.KeyModels{"user": modRequest})
assert.NoError(t, err)
@ -328,7 +328,7 @@ func TestInvalidUserUpdate(t *testing.T) {
// modify newUser's email with INVALID email
modRequest = UserRequest{Mail: "notEmail"}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "PUT",
common.KeyModels{"user": modRequest})
assert.NoError(t, err)
@ -336,7 +336,7 @@ func TestInvalidUserUpdate(t *testing.T) {
// modify newUser's role with INVALID role
modRequest = UserRequest{Role: "noRole"}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "PUT",
common.KeyModels{"user": modRequest})
assert.NoError(t, err)
@ -350,7 +350,7 @@ func TestModifyAddedUserAsAdmin(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -361,7 +361,7 @@ func TestModifyAddedUserAsAdmin(t *testing.T) {
Mail: "mod@added.user",
Role: "User",
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/users", "POST", common.KeyModels{"user": newUser})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -378,7 +378,7 @@ func TestModifyAddedUserAsAdmin(t *testing.T) {
// modify newUser's name
modRequest := UserRequest{Username: "NewUsername"}
newUser.Username = modRequest.Username
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "PUT",
common.KeyModels{"user": modRequest})
assert.NoError(t, err)
@ -389,7 +389,7 @@ func TestModifyAddedUserAsAdmin(t *testing.T) {
// modify newUser's email
modRequest = UserRequest{Mail: "new@e.mail"}
newUser.Mail = modRequest.Mail
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "PUT",
common.KeyModels{"user": modRequest})
assert.NoError(t, err)
@ -400,7 +400,7 @@ func TestModifyAddedUserAsAdmin(t *testing.T) {
// modify newUser's role
modRequest = UserRequest{Role: "Admin"}
newUser.Role = modRequest.Role
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "PUT",
common.KeyModels{"user": modRequest})
assert.NoError(t, err)
@ -410,14 +410,14 @@ func TestModifyAddedUserAsAdmin(t *testing.T) {
// modify newUser's password
modRequest = UserRequest{Password: "4_g00d_pw!"}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "PUT",
common.KeyModels{"user": modRequest})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
// try to login as newUser with the modified username and password
_, err = common.NewAuthenticateForTest(router,
_, err = common.AuthenticateForTest(router,
"/api/authenticate", "POST", UserRequest{
Username: newUser.Username,
Password: modRequest.Password,
@ -432,7 +432,7 @@ func TestDeleteUser(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminDB(db)
// authenticate as admin
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.AdminCredentials)
assert.NoError(t, err)
@ -443,7 +443,7 @@ func TestDeleteUser(t *testing.T) {
Mail: "to@be.deleted",
Role: "User",
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/users", "POST", common.KeyModels{"user": newUser})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -457,7 +457,7 @@ func TestDeleteUser(t *testing.T) {
assert.NoError(t, err)
// Delete the added newUser
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/users/%v", newUserID), "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)

View file

@ -39,7 +39,7 @@ func getWidgets(c *gin.Context) {
db := common.GetDB()
var widgets []common.Widget
err := db.Order("ID asc").Model(dab).Related(&widgets, "Widgets").Error
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}
@ -92,7 +92,7 @@ func addWidget(c *gin.Context) {
err := newWidget.addToDashboard()
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -153,7 +153,7 @@ func updateWidget(c *gin.Context) {
// Update the widget in the DB
err = oldWidget.update(updatedWidget)
if err != nil {
common.ProvideErrorResponse(c, err)
common.DBError(c, err)
return
}
@ -207,7 +207,7 @@ func deleteWidget(c *gin.Context) {
}
err := w.delete()
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return
}

View file

@ -40,7 +40,7 @@ func CheckPermissions(c *gin.Context, operation common.CRUD, widgetIDBody int) (
}
err = w.ByID(uint(widgetID))
if common.ProvideErrorResponse(c, err) {
if common.DBError(c, err) {
return false, w
}

View file

@ -52,7 +52,7 @@ func addScenarioAndDashboard(token string) (scenarioID uint, dashboardID uint) {
Running: common.ScenarioA.Running,
StartParameters: common.ScenarioA.StartParameters,
}
_, resp, _ := common.NewTestEndpoint(router, token,
_, resp, _ := common.TestEndpoint(router, token,
"/api/scenarios", "POST", common.KeyModels{"scenario": newScenario})
// Read newScenario's ID from the response
@ -64,7 +64,7 @@ func addScenarioAndDashboard(token string) (scenarioID uint, dashboardID uint) {
Grid: common.DashboardA.Grid,
ScenarioID: uint(newScenarioID),
}
_, resp, _ = common.NewTestEndpoint(router, token,
_, resp, _ = common.TestEndpoint(router, token,
"/api/dashboards", "POST", common.KeyModels{"dashboard": newDashboard})
// Read newDashboard's ID from the response
@ -100,7 +100,7 @@ func TestAddWidget(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -121,7 +121,7 @@ func TestAddWidget(t *testing.T) {
CustomProperties: common.WidgetA.CustomProperties,
DashboardID: dashboardID,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/widgets", "POST", common.KeyModels{"widget": newWidget})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -135,7 +135,7 @@ func TestAddWidget(t *testing.T) {
assert.NoError(t, err)
// Get the newWidget
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/widgets/%v", newWidgetID), "GET", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -150,7 +150,7 @@ func TestAddWidget(t *testing.T) {
Name: "ThisIsAMalformedDashboard",
}
// this should NOT work and return a unprocessable entity 442 status code
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/widgets", "POST", common.KeyModels{"widget": malformedNewWidget})
assert.NoError(t, err)
assert.Equalf(t, 422, code, "Response body: \n%v\n", resp)
@ -162,7 +162,7 @@ func TestUpdateWidget(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -183,7 +183,7 @@ func TestUpdateWidget(t *testing.T) {
CustomProperties: common.WidgetA.CustomProperties,
DashboardID: dashboardID,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/widgets", "POST", common.KeyModels{"widget": newWidget})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -202,7 +202,7 @@ func TestUpdateWidget(t *testing.T) {
CustomProperties: common.WidgetA.CustomProperties,
}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/widgets/%v", newWidgetID), "PUT", common.KeyModels{"widget": updatedWidget})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -212,7 +212,7 @@ func TestUpdateWidget(t *testing.T) {
assert.NoError(t, err)
// Get the updatedWidget
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/widgets/%v", newWidgetID), "GET", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -222,7 +222,7 @@ func TestUpdateWidget(t *testing.T) {
assert.NoError(t, err)
// try to update a widget that does not exist (should return not found 404 status code)
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/widgets/%v", newWidgetID+1), "PUT", common.KeyModels{"widget": updatedWidget})
assert.NoError(t, err)
assert.Equalf(t, 404, code, "Response body: \n%v\n", resp)
@ -235,7 +235,7 @@ func TestDeleteWidget(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -256,7 +256,7 @@ func TestDeleteWidget(t *testing.T) {
CustomProperties: common.WidgetA.CustomProperties,
DashboardID: dashboardID,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/widgets", "POST", common.KeyModels{"widget": newWidget})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -271,7 +271,7 @@ func TestDeleteWidget(t *testing.T) {
assert.NoError(t, err)
// Delete the added newWidget
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
fmt.Sprintf("/api/widgets/%v", newWidgetID), "DELETE", nil)
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -294,7 +294,7 @@ func TestGetAllWidgetsOfDashboard(t *testing.T) {
common.DummyAddOnlyUserTableWithAdminAndUsersDB(db)
// authenticate as normal user
token, err := common.NewAuthenticateForTest(router,
token, err := common.AuthenticateForTest(router,
"/api/authenticate", "POST", common.UserACredentials)
assert.NoError(t, err)
@ -320,7 +320,7 @@ func TestGetAllWidgetsOfDashboard(t *testing.T) {
CustomProperties: common.WidgetA.CustomProperties,
DashboardID: dashboardID,
}
code, resp, err := common.NewTestEndpoint(router, token,
code, resp, err := common.TestEndpoint(router, token,
"/api/widgets", "POST", common.KeyModels{"widget": newWidgetA})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)
@ -339,7 +339,7 @@ func TestGetAllWidgetsOfDashboard(t *testing.T) {
CustomProperties: common.WidgetB.CustomProperties,
DashboardID: dashboardID,
}
code, resp, err = common.NewTestEndpoint(router, token,
code, resp, err = common.TestEndpoint(router, token,
"/api/widgets", "POST", common.KeyModels{"widget": newWidgetB})
assert.NoError(t, err)
assert.Equalf(t, 200, code, "Response body: \n%v\n", resp)