Skip to content

Commit

Permalink
feat: updated test cases for controllers
Browse files Browse the repository at this point in the history
  • Loading branch information
tikazyq committed Jun 10, 2024
1 parent 2f31572 commit e13b282
Show file tree
Hide file tree
Showing 12 changed files with 897 additions and 93 deletions.
48 changes: 39 additions & 9 deletions controllers/router_v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,35 @@ type RouterGroups struct {

func NewRouterGroups(app *gin.Engine) (groups *RouterGroups) {
return &RouterGroups{
AuthGroup: app.Group("/", middlewares.AuthorizationMiddleware()),
AuthGroup: app.Group("/", middlewares.AuthorizationMiddlewareV2()),
AnonymousGroup: app.Group("/"),
}
}

func RegisterController[T any](group *gin.RouterGroup, basePath string, ctr *BaseControllerV2[T]) {
group.GET(basePath, ctr.GetList)
group.GET(basePath+"/:id", ctr.GetById)
group.POST(basePath, ctr.Post)
group.PUT(basePath+"/:id", ctr.PutById)
group.PATCH(basePath, ctr.PatchList)
group.DELETE(basePath+"/:id", ctr.DeleteById)
actionPaths := make(map[string]bool)
for _, action := range ctr.actions {
group.Handle(action.Method, action.Path, action.HandlerFunc)
path := basePath + action.Path
key := action.Method + " - " + path
actionPaths[key] = true
}
registerBuiltinHandler(group, http.MethodGet, basePath+"", ctr.GetList, actionPaths)
registerBuiltinHandler(group, http.MethodGet, basePath+"/:id", ctr.GetById, actionPaths)
registerBuiltinHandler(group, http.MethodPost, basePath+"", ctr.Post, actionPaths)
registerBuiltinHandler(group, http.MethodPut, basePath+"/:id", ctr.PutById, actionPaths)
registerBuiltinHandler(group, http.MethodPatch, basePath+"", ctr.PatchList, actionPaths)
registerBuiltinHandler(group, http.MethodDelete, basePath+"/:id", ctr.DeleteById, actionPaths)
registerBuiltinHandler(group, http.MethodDelete, basePath+"", ctr.DeleteList, actionPaths)
}

func registerBuiltinHandler(group *gin.RouterGroup, method, path string, handlerFunc gin.HandlerFunc, existingActionPaths map[string]bool) {
key := method + " - " + path
_, ok := existingActionPaths[key]
if ok {
return
}
group.Handle(method, path, handlerFunc)
}

func InitRoutes(app *gin.Engine) {
Expand All @@ -42,7 +59,16 @@ func InitRoutes(app *gin.Engine) {
RegisterController(groups.AuthGroup, "/projects", NewControllerV2[models.ProjectV2]())
RegisterController(groups.AuthGroup, "/roles", NewControllerV2[models.RoleV2]())
RegisterController(groups.AuthGroup, "/schedules", NewControllerV2[models.ScheduleV2](
// TODO: implement actions
Action{
Method: http.MethodPost,
Path: "/:id/enable",
HandlerFunc: PostScheduleEnable,
},
Action{
Method: http.MethodPost,
Path: "/:id/disable",
HandlerFunc: PostScheduleDisable,
},
))
RegisterController(groups.AuthGroup, "/settings", NewControllerV2[models.SettingV2]())
RegisterController(groups.AuthGroup, "/spiders", NewControllerV2[models.SpiderV2](
Expand All @@ -52,7 +78,11 @@ func InitRoutes(app *gin.Engine) {
// TODO: implement actions
))
RegisterController(groups.AuthGroup, "/tokens", NewControllerV2[models.TokenV2](
// TODO: implement actions
Action{
Method: http.MethodPost,
Path: "",
HandlerFunc: PostToken,
},
))
RegisterController(groups.AuthGroup, "/users", NewControllerV2[models.UserV2](
Action{
Expand Down
93 changes: 54 additions & 39 deletions controllers/router_v2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,45 +2,59 @@ package controllers_test

import (
"github.com/crawlab-team/crawlab-core/controllers"
"github.com/crawlab-team/crawlab-core/models/models"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
)

func TestRouterGroups_AuthGroup(t *testing.T) {
func TestRouterGroups(t *testing.T) {
router := gin.Default()
groups := controllers.NewRouterGroups(router)

assert.NotNil(t, groups.AuthGroup)
}

func TestRouterGroups_AnonymousGroup(t *testing.T) {
router := gin.Default()
groups := controllers.NewRouterGroups(router)

assert.NotNil(t, groups.AnonymousGroup)
assertions := []struct {
group *gin.RouterGroup
name string
}{
{groups.AuthGroup, "AuthGroup"},
{groups.AnonymousGroup, "AnonymousGroup"},
}

for _, a := range assertions {
assert.NotNil(t, a.group, a.name+" should not be nil")
}
}

func TestRegisterController_Routes(t *testing.T) {
router := gin.Default()
groups := controllers.NewRouterGroups(router)
ctr := controllers.NewControllerV2[TestModel]()
ctr := controllers.NewControllerV2[models.TestModel]()
basePath := "/testmodels"

controllers.RegisterController(groups.AuthGroup, basePath, ctr)

// Check if all routes are registered
routes := router.Routes()

assert.Equal(t, 6, len(routes))
assert.Contains(t, routes, gin.RouteInfo{Method: "GET", Path: basePath})
assert.Contains(t, routes, gin.RouteInfo{Method: "GET", Path: basePath + "/:id"})
assert.Contains(t, routes, gin.RouteInfo{Method: "POST", Path: basePath})
assert.Contains(t, routes, gin.RouteInfo{Method: "PUT", Path: basePath + "/:id"})
assert.Contains(t, routes, gin.RouteInfo{Method: "PATCH", Path: basePath})
assert.Contains(t, routes, gin.RouteInfo{Method: "DELETE", Path: basePath + "/:id"})
var methodPaths []string
for _, route := range routes {
methodPaths = append(methodPaths, route.Method+" - "+route.Path)
}

expectedRoutes := []gin.RouteInfo{
{Method: "GET", Path: basePath},
{Method: "GET", Path: basePath + "/:id"},
{Method: "POST", Path: basePath},
{Method: "PUT", Path: basePath + "/:id"},
{Method: "PATCH", Path: basePath},
{Method: "DELETE", Path: basePath + "/:id"},
{Method: "DELETE", Path: basePath},
}

assert.Equal(t, len(expectedRoutes), len(routes))
for _, route := range expectedRoutes {
assert.Contains(t, methodPaths, route.Method+" - "+route.Path)
}
}

func TestInitRoutes_ProjectsRoute(t *testing.T) {
Expand All @@ -51,26 +65,27 @@ func TestInitRoutes_ProjectsRoute(t *testing.T) {
// Check if the projects route is registered
routes := router.Routes()

assert.Contains(t, routes, gin.RouteInfo{Method: "GET", Path: "/projects"})
assert.Contains(t, routes, gin.RouteInfo{Method: "GET", Path: "/projects/:id"})
assert.Contains(t, routes, gin.RouteInfo{Method: "POST", Path: "/projects"})
assert.Contains(t, routes, gin.RouteInfo{Method: "PUT", Path: "/projects/:id"})
assert.Contains(t, routes, gin.RouteInfo{Method: "PATCH", Path: "/projects"})
assert.Contains(t, routes, gin.RouteInfo{Method: "DELETE", Path: "/projects/:id"})
var methodPaths []string
for _, route := range routes {
methodPaths = append(methodPaths, route.Method+" - "+route.Path)
}

expectedRoutes := []gin.RouteInfo{
{Method: "GET", Path: "/projects"},
{Method: "GET", Path: "/projects/:id"},
{Method: "POST", Path: "/projects"},
{Method: "PUT", Path: "/projects/:id"},
{Method: "PATCH", Path: "/projects"},
{Method: "DELETE", Path: "/projects/:id"},
{Method: "DELETE", Path: "/projects"},
}

for _, route := range expectedRoutes {
assert.Contains(t, methodPaths, route.Method+" - "+route.Path)
}
}

func TestInitRoutes_UnauthorizedAccess(t *testing.T) {
router := gin.Default()

controllers.InitRoutes(router)

// Create a test request
req, _ := http.NewRequest("GET", "/projects", nil)
w := httptest.NewRecorder()

// Serve the request
router.ServeHTTP(w, req)

// Check the response
assert.Equal(t, http.StatusUnauthorized, w.Code)
func TestMain(m *testing.M) {
gin.SetMode(gin.TestMode)
m.Run()
}
47 changes: 47 additions & 0 deletions controllers/schedule_v2.go
Original file line number Diff line number Diff line change
@@ -1 +1,48 @@
package controllers

import (
"github.com/crawlab-team/crawlab-core/models/models"
"github.com/crawlab-team/crawlab-core/models/service"
"github.com/crawlab-team/crawlab-core/schedule"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson/primitive"
)

func postScheduleEnableDisableFunc(isEnable bool) func(c *gin.Context) {
return func(c *gin.Context) {
id, err := primitive.ObjectIDFromHex(c.Param("id"))
if err != nil {
HandleErrorBadRequest(c, err)
return
}
svc, err := schedule.GetScheduleServiceV2()
if err != nil {
HandleErrorInternalServerError(c, err)
return
}
s, err := service.NewModelServiceV2[models.ScheduleV2]().GetById(id)
if err != nil {
HandleErrorInternalServerError(c, err)
return
}
u := GetUserFromContextV2(c)
if isEnable {
err = svc.Enable(*s, u.Id)
} else {
err = svc.Disable(*s, u.Id)
}
if err != nil {
HandleErrorInternalServerError(c, err)
return
}
HandleSuccess(c)
}
}

func PostScheduleEnable(c *gin.Context) {
postScheduleEnableDisableFunc(true)(c)
}

func PostScheduleDisable(c *gin.Context) {
postScheduleEnableDisableFunc(false)(c)
}
35 changes: 35 additions & 0 deletions controllers/token_v2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package controllers

import (
"github.com/crawlab-team/crawlab-core/models/models"
"github.com/crawlab-team/crawlab-core/models/service"
"github.com/crawlab-team/crawlab-core/user"
"github.com/gin-gonic/gin"
)

func PostToken(c *gin.Context) {
var t models.TokenV2
if err := c.ShouldBindJSON(&t); err != nil {
HandleErrorBadRequest(c, err)
return
}
svc, err := user.GetUserServiceV2()
if err != nil {
HandleErrorInternalServerError(c, err)
return
}
u := GetUserFromContextV2(c)
t.SetCreated(u.Id)
t.SetUpdated(u.Id)
t.Token, err = svc.MakeToken(u)
if err != nil {
HandleErrorInternalServerError(c, err)
return
}
_, err = service.NewModelServiceV2[models.TokenV2]().InsertOne(t)
if err != nil {
HandleErrorInternalServerError(c, err)
return
}
HandleSuccess(c)
}
39 changes: 7 additions & 32 deletions controllers/user_v2.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package controllers

import (
"github.com/crawlab-team/crawlab-core/constants"
"github.com/crawlab-team/crawlab-core/errors"
"github.com/crawlab-team/crawlab-core/models/models"
"github.com/crawlab-team/crawlab-core/models/service"
"github.com/crawlab-team/crawlab-core/utils"
Expand All @@ -28,16 +26,7 @@ func PostUserChangePassword(c *gin.Context) {
}

// get user
res, ok := c.Get(constants.UserContextKey)
if !ok {
HandleErrorUnauthorized(c, errors.ErrorUserNotExists)
return
}
u, ok := res.(models.UserV2)
if !ok {
HandleErrorUnauthorized(c, errors.ErrorUserNotExists)
return
}
u := GetUserFromContextV2(c)
modelSvc := service.NewModelServiceV2[models.UserV2]()

// update password
Expand All @@ -58,16 +47,7 @@ func PostUserChangePassword(c *gin.Context) {
}

func GetUserMe(c *gin.Context) {
res, ok := c.Get(constants.UserContextKey)
if !ok {
HandleErrorUnauthorized(c, errors.ErrorUserNotExists)
return
}
u, ok := res.(models.UserV2)
if !ok {
HandleErrorUnauthorized(c, errors.ErrorUserNotExists)
return
}
u := GetUserFromContextV2(c)
HandleSuccessWithData(c, u)
}

Expand All @@ -80,16 +60,8 @@ func PutUserById(c *gin.Context) {
}

// get user
res, ok := c.Get(constants.UserContextKey)
if !ok {
HandleErrorUnauthorized(c, errors.ErrorUserNotExists)
return
}
u, ok := res.(models.UserV2)
if !ok {
HandleErrorUnauthorized(c, errors.ErrorUserNotExists)
return
}
u := GetUserFromContextV2(c)

modelSvc := service.NewModelServiceV2[models.UserV2]()

// update user
Expand All @@ -100,6 +72,9 @@ func PutUserById(c *gin.Context) {
}
user.Password = userDb.Password
user.SetUpdated(u.Id)
if user.Id.IsZero() {
user.Id = u.Id
}
if err := modelSvc.ReplaceById(u.Id, user); err != nil {
HandleErrorInternalServerError(c, err)
return
Expand Down
Loading

0 comments on commit e13b282

Please sign in to comment.