diff --git a/routes/usergroup/usergroup_endpoints.go b/routes/usergroup/usergroup_endpoints.go index 2b29c72..68d1f13 100644 --- a/routes/usergroup/usergroup_endpoints.go +++ b/routes/usergroup/usergroup_endpoints.go @@ -18,6 +18,7 @@ package usergroup import ( + "errors" "fmt" "log" "net/http" @@ -27,6 +28,7 @@ import ( "git.rwth-aachen.de/acs/public/villas/web-backend-go/helper" "git.rwth-aachen.de/acs/public/villas/web-backend-go/routes/user" "github.com/gin-gonic/gin" + "github.com/jinzhu/gorm" ) func RegisterUserGroupEndpoints(r *gin.RouterGroup) { @@ -74,6 +76,15 @@ func addUserGroup(c *gin.Context) { // Create the new user group from the request newUserGroup := req.createUserGroup() + db := database.GetDB() + for _, sm := range newUserGroup.ScenarioMappings { + var sc database.Scenario + if err := db.Find(&sc, "ID = ?", sm.ScenarioID).Error; errors.Is(err, gorm.ErrRecordNotFound) { + helper.NotFoundError(c, + "Scenario mappings referencing inexistent scenario ID: "+strconv.Itoa(int(sm.ScenarioID))) + return + } + } // Save the new user group to the database err := newUserGroup.save() diff --git a/routes/usergroup/usergroup_test.go b/routes/usergroup/usergroup_test.go index 52b88a2..f295cba 100644 --- a/routes/usergroup/usergroup_test.go +++ b/routes/usergroup/usergroup_test.go @@ -119,7 +119,15 @@ func TestAddUserGroup(t *testing.T) { assert.NoError(t, err) assert.Equalf(t, 400, code, "Response body: \n%v\n", resp) + //Test with inexitent scenario + code, resp, err = helper.TestEndpoint(router, token, "/api/v2/usergroups", + "POST", helper.KeyModels{"usergroup": newUserGroupOneMapping}) + assert.NoError(t, err) + assert.Equalf(t, 404, code, "Response body: \n%v\n", resp) + // Test with valid user group with one scenario mapping + helper.TestEndpoint(router, token, "/api/v2/scenarios", "POST", helper.KeyModels{"scenario": database.Scenario{Name: "scenario1"}}) + helper.TestEndpoint(router, token, "/api/v2/scenarios", "POST", helper.KeyModels{"scenario": database.Scenario{Name: "scenario2"}}) code, resp, err = helper.TestEndpoint(router, token, "/api/v2/usergroups", "POST", helper.KeyModels{"usergroup": newUserGroupOneMapping}) assert.NoError(t, err)