Skip to content

Commit

Permalink
[ChaosCenter]: Add unit tests to rest_handlers and authorization pack…
Browse files Browse the repository at this point in the history
…age in GraphQL server (#3980)

* feat: add unit tests to rest_handlers

Signed-off-by: namkyu1999 <[email protected]>

* feat: add unit tests to authorization package

Signed-off-by: namkyu1999 <[email protected]>

* fix: chore

Signed-off-by: namkyu1999 <[email protected]>

---------

Signed-off-by: namkyu1999 <[email protected]>
  • Loading branch information
namkyu1999 authored May 22, 2023
1 parent cf86f7e commit 27d372b
Show file tree
Hide file tree
Showing 15 changed files with 671 additions and 11 deletions.
117 changes: 117 additions & 0 deletions litmus-portal/graphql-server/pkg/authorization/middleware_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package authorization_test

import (
"net/http"
"net/http/httptest"
"net/url"
"testing"

"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"github.com/google/uuid"
"github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/authorization"
"github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/rest_handlers"
"github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils"
"github.com/stretchr/testify/assert"
)

// GetTestGinContext returns a gin context for testing
func GetTestGinContext(w *httptest.ResponseRecorder) *gin.Context {
ctx, _ := gin.CreateTestContext(w)
ctx.Request = &http.Request{
Header: make(http.Header),
URL: &url.URL{},
}

return ctx
}

// TestMiddleware tests the middleware function
func TestMiddleware(t *testing.T) {
//given
w := httptest.NewRecorder()
ctx := GetTestGinContext(w)
ctx.Request.AddCookie(&http.Cookie{
Name: authorization.CookieName,
Value: "test",
})
handlerMock := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))

ts := httptest.NewServer(handlerMock)
defer ts.Close()

// when
authorization.Middleware(handlerMock)(ctx)

// then
assert.Equal(t, http.StatusOK, w.Code)
}

func TestRestMiddlewareWithRole(t *testing.T) {
//given
var (
w *httptest.ResponseRecorder
ctx *gin.Context
username = uuid.NewString()
)
testcases := []struct {
name string
given func() string
statusCode int
roles []string
}{
{
name: "success",
given: func() string {
w = httptest.NewRecorder()
ctx = GetTestGinContext(w)
claims := jwt.MapClaims{}
claims["username"] = username
token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
tokenString, _ := token.SignedString([]byte(utils.Config.JwtSecret))
return tokenString
},
statusCode: http.StatusOK,
},
{
name: "failure: invalid token",
given: func() string {
w = httptest.NewRecorder()
ctx = GetTestGinContext(w)
return "invalid-token"
},
statusCode: http.StatusUnauthorized,
},
{
name: "success",
given: func() string {
w = httptest.NewRecorder()
ctx = GetTestGinContext(w)
claims := jwt.MapClaims{}
claims["username"] = username
claims["role"] = "admin"
token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
tokenString, _ := token.SignedString([]byte(utils.Config.JwtSecret))
return tokenString
},
statusCode: http.StatusOK,
roles: []string{"admin"},
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
// given
tokenString := tc.given()
ctx.Request.AddCookie(&http.Cookie{
Name: authorization.CookieName,
Value: tokenString,
})
// when
authorization.RestMiddlewareWithRole(rest_handlers.PlaygroundHandler(), tc.roles)(ctx)
// then
assert.Equal(t, tc.statusCode, w.Code)
})
}
}
116 changes: 116 additions & 0 deletions litmus-portal/graphql-server/pkg/authorization/user_jwt_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package authorization_test

import (
"testing"

"github.com/golang-jwt/jwt"
"github.com/google/uuid"
"github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/authorization"
"github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils"
"github.com/stretchr/testify/assert"
)

// TestUserValidateJWT tests the UserValidateJWT function
func TestUserValidateJWT(t *testing.T) {
// given
username := uuid.NewString()
testcases := []struct {
name string
given func() string
wantErr bool
}{
{
name: "success",
given: func() string {
claims := jwt.MapClaims{}
claims["username"] = username
token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)

tokenString, _ := token.SignedString([]byte(utils.Config.JwtSecret))
return tokenString
},
wantErr: false,
},
{
name: "failure: parse err",
given: func() string {
return "invalid-jwt"
},
wantErr: true,
},
{
name: "failure: unexpected signing method",
given: func() string {
claims := jwt.MapClaims{}
claims["username"] = username
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

tokenString, _ := token.SignedString([]byte(utils.Config.JwtSecret))
return tokenString
},
wantErr: true,
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
// given
tokenString := tc.given()
// when
got, err := authorization.UserValidateJWT(tokenString)
// then
if tc.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, username, got["username"])
}
})
}
}

// TestGetUsername tests the GetUsername function
func TestGetUsername(t *testing.T) {
// given
username := uuid.NewString()

testcases := []struct {
name string
given func() string
wantErr bool
}{
{
name: "success",
given: func() string {
claims := jwt.MapClaims{}
claims["username"] = username
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

tokenString, _ := token.SignedString([]byte(utils.Config.JwtSecret))
return tokenString
},
wantErr: false,
},
{
name: "failure: parse err",
given: func() string {
return "invalid-jwt"
},
wantErr: true,
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
// given
tokenString := tc.given()
// when
got, err := authorization.GetUsername(tokenString)
// then
if tc.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, username, got)
}
})
}
}
23 changes: 23 additions & 0 deletions litmus-portal/graphql-server/pkg/authorization/validate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Package authorization_test contains tests for the authorization package
package authorization_test

import (
"io/ioutil"
"os"
"testing"

"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)

// TestMain is the entry point for testing
func TestMain(m *testing.M) {
gin.SetMode(gin.TestMode)
log.SetOutput(ioutil.Discard)
os.Exit(m.Run())
}

// TestValidateRole tests the ValidateRole function
func TestValidateRole(t *testing.T) {
// TODO: need to add test cases after mocking GRPC
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (

"github.com/gin-gonic/gin"
"github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils"
log "github.com/sirupsen/logrus"
)

type WorkflowHelperImageVersion struct {
Expand All @@ -20,11 +19,9 @@ func WorkflowHelperImageVersionHandler(c *gin.Context) {
version := WorkflowHelperImageVersion{Version: versionDetails}
versionByte, err := json.Marshal(version)
if err != nil {
log.Error(err)
utils.WriteHeaders(&c.Writer, http.StatusBadRequest)
return
}

utils.WriteHeaders(&c.Writer, http.StatusOK)
c.Writer.Write(versionByte)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package rest_handlers_test

import (
"encoding/json"
"net/http/httptest"
"testing"

"github.com/google/uuid"
"github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/rest_handlers"
"github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils"
"github.com/stretchr/testify/assert"
)

func TestWorkflowHelperImageVersionHandler(t *testing.T) {
// given
utils.Config.WorkflowHelperImageVersion = uuid.NewString()
w := httptest.NewRecorder()
ctx := GetTestGinContext(w)

// when
rest_handlers.WorkflowHelperImageVersionHandler(ctx)

// then
var version rest_handlers.WorkflowHelperImageVersion
err := json.Unmarshal(w.Body.Bytes(), &version)
assert.NoError(t, err)
assert.Equal(t, w.Code, 200)
assert.Equal(t, version.Version, utils.Config.WorkflowHelperImageVersion)
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ func FileHandler(mongodbOperator mongodb.MongoOperator) gin.HandlerFunc {
log.WithError(err).Error("error while generating manifest file")
utils.WriteHeaders(&c.Writer, statusCode)
c.Writer.Write([]byte(err.Error()))
return
}
utils.WriteHeaders(&c.Writer, statusCode)
c.Writer.Write(response)
Expand Down
Loading

0 comments on commit 27d372b

Please sign in to comment.