diff --git a/litmus-portal/graphql-server/pkg/authorization/middleware_test.go b/litmus-portal/graphql-server/pkg/authorization/middleware_test.go new file mode 100644 index 00000000000..42a45cd25d2 --- /dev/null +++ b/litmus-portal/graphql-server/pkg/authorization/middleware_test.go @@ -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) + }) + } +} diff --git a/litmus-portal/graphql-server/pkg/authorization/user_jwt_test.go b/litmus-portal/graphql-server/pkg/authorization/user_jwt_test.go new file mode 100644 index 00000000000..af8e2cc5c29 --- /dev/null +++ b/litmus-portal/graphql-server/pkg/authorization/user_jwt_test.go @@ -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) + } + }) + } +} diff --git a/litmus-portal/graphql-server/pkg/authorization/validate_test.go b/litmus-portal/graphql-server/pkg/authorization/validate_test.go new file mode 100644 index 00000000000..c3519c28fdb --- /dev/null +++ b/litmus-portal/graphql-server/pkg/authorization/validate_test.go @@ -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 +} diff --git a/litmus-portal/graphql-server/pkg/rest_handlers/core_version_handler.go b/litmus-portal/graphql-server/pkg/rest_handlers/core_version_handler.go index bb6e0f14646..c859ec6bffb 100644 --- a/litmus-portal/graphql-server/pkg/rest_handlers/core_version_handler.go +++ b/litmus-portal/graphql-server/pkg/rest_handlers/core_version_handler.go @@ -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 { @@ -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) } diff --git a/litmus-portal/graphql-server/pkg/rest_handlers/core_vision_handler_test.go b/litmus-portal/graphql-server/pkg/rest_handlers/core_vision_handler_test.go new file mode 100644 index 00000000000..286054905fd --- /dev/null +++ b/litmus-portal/graphql-server/pkg/rest_handlers/core_vision_handler_test.go @@ -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) +} diff --git a/litmus-portal/graphql-server/pkg/rest_handlers/file_handler.go b/litmus-portal/graphql-server/pkg/rest_handlers/file_handler.go index 40c56faa447..5ca2b2d1f7f 100644 --- a/litmus-portal/graphql-server/pkg/rest_handlers/file_handler.go +++ b/litmus-portal/graphql-server/pkg/rest_handlers/file_handler.go @@ -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) diff --git a/litmus-portal/graphql-server/pkg/rest_handlers/file_handler_test.go b/litmus-portal/graphql-server/pkg/rest_handlers/file_handler_test.go new file mode 100644 index 00000000000..7a4fbdb5574 --- /dev/null +++ b/litmus-portal/graphql-server/pkg/rest_handlers/file_handler_test.go @@ -0,0 +1,116 @@ +package rest_handlers_test + +import ( + "net/http/httptest" + "os" + "testing" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/cluster" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb/model/mocks" + "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" + "github.com/stretchr/testify/mock" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" +) + +func TestFileHandler(t *testing.T) { + // given + var ( + w *httptest.ResponseRecorder + ctx *gin.Context + mongoOperator = new(mocks.MongoOperator) + ) + testcases := []struct { + name string + statusCode int + given func() + }{ + { + name: "success", + statusCode: 200, + given: func() { + w = httptest.NewRecorder() + clusterID := uuid.NewString() + accessKey, _ := cluster.ClusterCreateJWT(clusterID) + ctx, _ = gin.CreateTestContext(w) + ctx.Params = []gin.Param{ + { + Key: "key", + Value: accessKey, + }, + } + + findResult := bson.D{{"project_id", uuid.NewString()}, {"cluster_id", clusterID}, {"access_key", accessKey}, {"agent_scope", "cluster"}} + singleResult := mongo.NewSingleResultFromDocument(findResult, nil, nil) + mongoOperator.On("Get", mock.Anything, mongodb.ClusterCollection, mock.Anything).Return(singleResult, nil).Once() + utils.Config.ChaosCenterUiEndpoint = "http://1.2.3.4" + utils.Config.ChaosCenterScope = "cluster" + t.Cleanup(func() { + utils.Config.ChaosCenterUiEndpoint = "" + utils.Config.ChaosCenterScope = "" + }) + + manifest := ` +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: argo + namespace: #{AGENT_NAMESPACE} +` + // not using filepath. see Dockerfile + err := os.MkdirAll("manifests/cluster", 0755) + if err != nil { + t.FailNow() + } + temp, err := os.Create("manifests/cluster/1b_argo_rbac.yaml") + if err != nil { + t.FailNow() + } + defer func(temp *os.File) { + err := temp.Close() + if err != nil { + t.FailNow() + } + }(temp) + _, err = temp.WriteString(manifest) + if err != nil { + t.FailNow() + } + t.Cleanup(func() { + _ = os.RemoveAll("manifests") + }) + }, + }, + { + name: "failure: should return 404 when cluster is not found", + statusCode: 404, + given: func() { + w = httptest.NewRecorder() + accessKey := "invalid-token" + ctx, _ = gin.CreateTestContext(w) + ctx.Params = []gin.Param{ + { + Key: "key", + Value: accessKey, + }, + } + }, + }, + } + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + tc.given() + // when + rest_handlers.FileHandler(mongoOperator)(ctx) + + // then + assert.Equal(t, w.Code, tc.statusCode) + }) + } +} diff --git a/litmus-portal/graphql-server/pkg/rest_handlers/get_icon_handler_test.go b/litmus-portal/graphql-server/pkg/rest_handlers/get_icon_handler_test.go new file mode 100644 index 00000000000..bad801a25db --- /dev/null +++ b/litmus-portal/graphql-server/pkg/rest_handlers/get_icon_handler_test.go @@ -0,0 +1,55 @@ +package rest_handlers_test + +import ( + "fmt" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/rest_handlers" + "github.com/stretchr/testify/assert" +) + +func TestGetIconHandler(t *testing.T) { + // given + w := httptest.NewRecorder() + ctx := GetTestGinContext(w) + projectID, hubName, chartName, iconName := uuid.NewString(), uuid.NewString(), uuid.NewString(), uuid.NewString() + ctx.Params = []gin.Param{ + { + Key: "ProjectID", + Value: projectID, + }, + { + Key: "HubName", + Value: hubName, + }, + { + Key: "ChartName", + Value: chartName, + }, + { + Key: "IconName", + Value: iconName, + }, + } + + err := os.MkdirAll(fmt.Sprintf("/tmp/version/%s/%s/charts/%s/icons", projectID, hubName, chartName), 0777) + if err != nil { + t.FailNow() + } + _, err = os.Create(fmt.Sprintf("/tmp/version/%s/%s/charts/%s/icons/%s", projectID, hubName, chartName, iconName)) + if err != nil { + t.FailNow() + } + t.Cleanup(func() { _ = os.RemoveAll("/tmp/version/" + projectID) }) + // when + rest_handlers.GetIconHandler(ctx) + + // then + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "image/png", w.Header().Get("Content-Type")) +} diff --git a/litmus-portal/graphql-server/pkg/rest_handlers/playground_handler_test.go b/litmus-portal/graphql-server/pkg/rest_handlers/playground_handler_test.go new file mode 100644 index 00000000000..ba28a88695a --- /dev/null +++ b/litmus-portal/graphql-server/pkg/rest_handlers/playground_handler_test.go @@ -0,0 +1,21 @@ +package rest_handlers_test + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/rest_handlers" + "github.com/stretchr/testify/assert" +) + +func TestPlaygroundHandler(t *testing.T) { + // given + w := httptest.NewRecorder() + ctx := GetTestGinContext(w) + // when + rest_handlers.PlaygroundHandler()(ctx) + // then + assert.Equal(t, 200, w.Code) + assert.NotEqual(t, -1, strings.Index(w.Body.String(), "GraphQL playground")) +} diff --git a/litmus-portal/graphql-server/pkg/rest_handlers/readiness_handler.go b/litmus-portal/graphql-server/pkg/rest_handlers/readiness_handler.go index 7c0607e8289..f5e13b988c4 100644 --- a/litmus-portal/graphql-server/pkg/rest_handlers/readiness_handler.go +++ b/litmus-portal/graphql-server/pkg/rest_handlers/readiness_handler.go @@ -26,14 +26,15 @@ func contains(s []string, str string) bool { return false } -func ReadinessHandler(handler http.Handler, mclient *mongo.Client, mongodbOperator mongodb.MongoOperator) gin.HandlerFunc { +// ReadinessHandler returns current status of this application +func ReadinessHandler(mongoClient *mongo.Client, mongodbOperator mongodb.MongoOperator) gin.HandlerFunc { return func(c *gin.Context) { var ( dbFlag = "up" colFlag = "up" ) - dbs, err := mongodbOperator.ListDataBase(context.Background(), mclient) + dbs, err := mongodbOperator.ListDataBase(context.Background(), mongoClient) if err != nil { log.Error(err) dbFlag = "down" @@ -43,7 +44,7 @@ func ReadinessHandler(handler http.Handler, mclient *mongo.Client, mongodbOperat dbFlag = "down" } - cols, err := mongodbOperator.ListCollection(context.Background(), mclient) + cols, err := mongodbOperator.ListCollection(context.Background(), mongoClient) if err != nil { log.Error(err) colFlag = "down" @@ -58,6 +59,7 @@ func ReadinessHandler(handler http.Handler, mclient *mongo.Client, mongodbOperat if err != nil { log.Error(err) utils.WriteHeaders(&c.Writer, http.StatusBadRequest) + return } utils.WriteHeaders(&c.Writer, http.StatusOK) diff --git a/litmus-portal/graphql-server/pkg/rest_handlers/readiness_handler_test.go b/litmus-portal/graphql-server/pkg/rest_handlers/readiness_handler_test.go new file mode 100644 index 00000000000..652ddae6138 --- /dev/null +++ b/litmus-portal/graphql-server/pkg/rest_handlers/readiness_handler_test.go @@ -0,0 +1,113 @@ +package rest_handlers_test + +import ( + "encoding/json" + "errors" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb/model/mocks" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/rest_handlers" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "go.mongodb.org/mongo-driver/mongo" +) + +func TestReadinessHandler(t *testing.T) { + // given + var ( + readinessStatus rest_handlers.ReadinessAPIStatus + w *httptest.ResponseRecorder + ctx *gin.Context + ) + mongoClient := &mongo.Client{} + mongoOperator := new(mocks.MongoOperator) + testcases := []struct { + name string + given func() + want rest_handlers.ReadinessAPIStatus + }{ + { + name: "success", + given: func() { + w = httptest.NewRecorder() + ctx = GetTestGinContext(w) + mongoOperator.On("ListDataBase", mock.Anything, mongoClient).Return([]string{"litmus"}, nil).Once() + mongoOperator.On("ListCollection", mock.Anything, mongoClient).Return([]string{"gitops-collection", "server-config-collection", "workflow-collection"}, nil).Once() + }, + want: rest_handlers.ReadinessAPIStatus{ + DataBase: "up", + Collections: "up", + }, + }, + { + name: "failure: mongo list database error", + given: func() { + w = httptest.NewRecorder() + ctx = GetTestGinContext(w) + mongoOperator.On("ListDataBase", mock.Anything, mongoClient).Return([]string{}, errors.New("")).Once() + mongoOperator.On("ListCollection", mock.Anything, mongoClient).Return([]string{"gitops-collection", "server-config-collection", "workflow-collection"}, nil).Once() + }, + want: rest_handlers.ReadinessAPIStatus{ + DataBase: "down", + Collections: "up", + }, + }, + { + name: "failure: cannot find litmus database", + given: func() { + w = httptest.NewRecorder() + ctx = GetTestGinContext(w) + mongoOperator.On("ListDataBase", mock.Anything, mongoClient).Return([]string{}, nil).Once() + mongoOperator.On("ListCollection", mock.Anything, mongoClient).Return([]string{"gitops-collection", "server-config-collection", "workflow-collection"}, nil).Once() + }, + want: rest_handlers.ReadinessAPIStatus{ + DataBase: "down", + Collections: "up", + }, + }, + { + name: "failure: mongo list collection error", + given: func() { + w = httptest.NewRecorder() + ctx = GetTestGinContext(w) + mongoOperator.On("ListDataBase", mock.Anything, mongoClient).Return([]string{"litmus"}, nil).Once() + mongoOperator.On("ListCollection", mock.Anything, mongoClient).Return([]string{}, errors.New("")).Once() + }, + want: rest_handlers.ReadinessAPIStatus{ + DataBase: "up", + Collections: "down", + }, + }, + { + name: "failure: cannot find gitops collection", + given: func() { + w = httptest.NewRecorder() + ctx = GetTestGinContext(w) + mongoOperator.On("ListDataBase", mock.Anything, mongoClient).Return([]string{"litmus"}, nil).Once() + mongoOperator.On("ListCollection", mock.Anything, mongoClient).Return([]string{"server-config-collection", "workflow-collection"}, nil).Once() + }, + want: rest_handlers.ReadinessAPIStatus{ + DataBase: "up", + Collections: "down", + }, + }, + } + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + // given + tc.given() + // when + handler := rest_handlers.ReadinessHandler(mongoClient, mongoOperator) + handler(ctx) + + // then + err := json.Unmarshal(w.Body.Bytes(), &readinessStatus) + assert.NoError(t, err) + assert.Equal(t, tc.want.DataBase, readinessStatus.DataBase) + assert.Equal(t, tc.want.Collections, readinessStatus.Collections) + assert.Equal(t, 200, w.Code) + }) + } +} diff --git a/litmus-portal/graphql-server/pkg/rest_handlers/request_logger_test.go b/litmus-portal/graphql-server/pkg/rest_handlers/request_logger_test.go new file mode 100644 index 00000000000..67f2551469c --- /dev/null +++ b/litmus-portal/graphql-server/pkg/rest_handlers/request_logger_test.go @@ -0,0 +1,19 @@ +package rest_handlers_test + +import ( + "net/http/httptest" + "testing" + + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/rest_handlers" + "github.com/stretchr/testify/assert" +) + +func TestLoggingMiddleware(t *testing.T) { + // given + w := httptest.NewRecorder() + ctx := GetTestGinContext(w) + // when + rest_handlers.LoggingMiddleware()(ctx) + // then + assert.Equal(t, 200, w.Code) +} diff --git a/litmus-portal/graphql-server/pkg/rest_handlers/status_handler.go b/litmus-portal/graphql-server/pkg/rest_handlers/status_handler.go index 5ae2608fd35..6da09200046 100644 --- a/litmus-portal/graphql-server/pkg/rest_handlers/status_handler.go +++ b/litmus-portal/graphql-server/pkg/rest_handlers/status_handler.go @@ -6,7 +6,6 @@ import ( "github.com/gin-gonic/gin" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils" - log "github.com/sirupsen/logrus" ) type APIStatus struct { @@ -18,10 +17,9 @@ func StatusHandler(c *gin.Context) { var status = APIStatus{Status: "up"} statusByte, err := json.Marshal(status) if err != nil { - log.Error(err) - utils.WriteHeaders(&c.Writer, http.StatusBadRequest) + utils.WriteHeaders(&c.Writer, http.StatusInternalServerError) + return } - utils.WriteHeaders(&c.Writer, http.StatusOK) c.Writer.Write(statusByte) } diff --git a/litmus-portal/graphql-server/pkg/rest_handlers/status_handler_test.go b/litmus-portal/graphql-server/pkg/rest_handlers/status_handler_test.go new file mode 100644 index 00000000000..1139ec25f89 --- /dev/null +++ b/litmus-portal/graphql-server/pkg/rest_handlers/status_handler_test.go @@ -0,0 +1,53 @@ +// Package rest_handlers_test contains tests for rest_handlers package. +package rest_handlers_test + +import ( + "encoding/json" + "io/ioutil" + "net/http" + "net/http/httptest" + "net/url" + "os" + "testing" + + "github.com/gin-gonic/gin" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/rest_handlers" + log "github.com/sirupsen/logrus" + "github.com/stretchr/testify/assert" +) + +// TestMain is the entry point for testing +func TestMain(m *testing.M) { + gin.SetMode(gin.TestMode) + log.SetOutput(ioutil.Discard) + os.Exit(m.Run()) +} + +// 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 +} + +// TestStatusHandler tests the StatusHandler function +func TestStatusHandler(t *testing.T) { + // given + var status rest_handlers.APIStatus + + w := httptest.NewRecorder() + ctx := GetTestGinContext(w) + + // when + rest_handlers.StatusHandler(ctx) + + // then + err := json.Unmarshal(w.Body.Bytes(), &status) + assert.NoError(t, err) + assert.Equal(t, "up", status.Status) + assert.EqualValues(t, http.StatusOK, w.Code) +} diff --git a/litmus-portal/graphql-server/server.go b/litmus-portal/graphql-server/server.go index 2898a706727..3de2a3f6d8f 100644 --- a/litmus-portal/graphql-server/server.go +++ b/litmus-portal/graphql-server/server.go @@ -134,7 +134,7 @@ func main() { // routers router.GET("/", rest_handlers.PlaygroundHandler()) router.Any("/query", authorization.Middleware(srv)) - router.GET("/readiness", rest_handlers.ReadinessHandler(srv, client, mongodbOperator)) + router.GET("/readiness", rest_handlers.ReadinessHandler(client, mongodbOperator)) router.GET("/icon/:ProjectID/:HubName/:ChartName/:IconName", authorization.RestMiddlewareWithRole(rest_handlers.GetIconHandler, nil)) router.Any("/file/:key", rest_handlers.FileHandler(mongodbOperator)) router.GET("/status", rest_handlers.StatusHandler)