PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FEATURE (storages): Add tests for storages controller
Rostislav Dugine356d48e6370
diff --git a/backend/README.md b/backend/README.mdindex 2c66fa7f..f17f0b86 100644--- a/backend/README.md+++ b/backend/README.md@@ -16,6 +16,10 @@ To run:> go run /cmd/main.go+To run tests:++> go test ./internal/...+Before commit (make sure `golangci-lint` is installed):> golangci-lint fmtdiff --git a/backend/internal/features/storages/controller_test.go b/backend/internal/features/storages/controller_test.gonew file mode 100644index 00000000..fce0b938--- /dev/null+++ b/backend/internal/features/storages/controller_test.go@@ -0,0 +1,223 @@+package storages++import (+ "net/http"+ local_storage "postgresus-backend/internal/features/storages/storages/local"+ "postgresus-backend/internal/features/users"+ test_utils "postgresus-backend/internal/util/testing"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+)++func Test_SaveNewStorage_StorageReturnedViaGet(t *testing.T) {+ user := users.GetUser()+ router := createRouter()+ storage := createTestStorage(user.UserID)++ var savedStorage Storage+ test_utils.MakePostRequestAndUnmarshal(+ t, router, "/api/v1/storages", user.Token, storage, http.StatusOK, &savedStorage,+ )++ verifyStorageData(t, storage, &savedStorage)+ assert.NotEmpty(t, savedStorage.ID)++ // Verify storage is returned via GET+ var retrievedStorage Storage+ test_utils.MakeGetRequestAndUnmarshal(+ t,+ router,+ "/api/v1/storages/"+savedStorage.ID.String(),+ user.Token,+ http.StatusOK,+ &retrievedStorage,+ )++ verifyStorageData(t, &savedStorage, &retrievedStorage)++ // Verify storage is returned via GET all storages+ var storages []Storage+ test_utils.MakeGetRequestAndUnmarshal(+ t, router, "/api/v1/storages", user.Token, http.StatusOK, &storages,+ )++ assert.Contains(t, storages, savedStorage)+}++func Test_UpdateExistingStorage_UpdatedStorageReturnedViaGet(t *testing.T) {+ user := users.GetUser()+ router := createRouter()+ storage := createTestStorage(user.UserID)++ // Save initial storage+ var savedStorage Storage+ test_utils.MakePostRequestAndUnmarshal(+ t, router, "/api/v1/storages", user.Token, storage, http.StatusOK, &savedStorage,+ )++ // Modify storage name+ updatedName := "Updated Storage " + uuid.New().String()+ savedStorage.Name = updatedName++ // Update storage+ var updatedStorage Storage+ test_utils.MakePostRequestAndUnmarshal(+ t, router, "/api/v1/storages", user.Token, savedStorage, http.StatusOK, &updatedStorage,+ )++ // Verify updated data+ assert.Equal(t, updatedName, updatedStorage.Name)+ assert.Equal(t, savedStorage.ID, updatedStorage.ID)++ // Verify through GET+ var retrievedStorage Storage+ test_utils.MakeGetRequestAndUnmarshal(+ t,+ router,+ "/api/v1/storages/"+updatedStorage.ID.String(),+ user.Token,+ http.StatusOK,+ &retrievedStorage,+ )++ verifyStorageData(t, &updatedStorage, &retrievedStorage)++ // Verify storage is returned via GET all storages+ var storages []Storage+ test_utils.MakeGetRequestAndUnmarshal(+ t, router, "/api/v1/storages", user.Token, http.StatusOK, &storages,+ )++ assert.Contains(t, storages, updatedStorage)+}++func Test_DeleteStorage_StorageNotReturnedViaGet(t *testing.T) {+ user := users.GetUser()+ router := createRouter()+ storage := createTestStorage(user.UserID)++ // Save initial storage+ var savedStorage Storage+ test_utils.MakePostRequestAndUnmarshal(+ t, router, "/api/v1/storages", user.Token, storage, http.StatusOK, &savedStorage,+ )++ // Delete storage+ test_utils.MakeDeleteRequest(+ t, router, "/api/v1/storages/"+savedStorage.ID.String(), user.Token, http.StatusOK,+ )++ // Try to get deleted storage, should return error+ response := test_utils.MakeGetRequest(+ t, router, "/api/v1/storages/"+savedStorage.ID.String(), user.Token, http.StatusBadRequest,+ )++ assert.Contains(t, string(response.Body), "error")++ // Verify storage is not returned via GET all storages+ var storages []Storage+ test_utils.MakeGetRequestAndUnmarshal(+ t, router, "/api/v1/storages", user.Token, http.StatusOK, &storages,+ )++ assert.NotContains(t, storages, savedStorage)+}++func Test_TestDirectStorageConnection_ConnectionEstablished(t *testing.T) {+ user := users.GetUser()+ router := createRouter()+ storage := createTestStorage(user.UserID)++ response := test_utils.MakePostRequest(+ t, router, "/api/v1/storages/direct-test", user.Token, storage, http.StatusOK,+ )++ assert.Contains(t, string(response.Body), "successful")+}++func Test_TestExistingStorageConnection_ConnectionEstablished(t *testing.T) {+ user := users.GetUser()+ router := createRouter()+ storage := createTestStorage(user.UserID)++ var savedStorage Storage+ test_utils.MakePostRequestAndUnmarshal(+ t, router, "/api/v1/storages", user.Token, storage, http.StatusOK, &savedStorage,+ )++ // Test connection to existing storage+ response := test_utils.MakePostRequest(+ t,+ router,+ "/api/v1/storages/"+savedStorage.ID.String()+"/test",+ user.Token,+ nil,+ http.StatusOK,+ )++ assert.Contains(t, string(response.Body), "successful")+}++func Test_CallAllMethodsWithoutAuth_UnauthorizedErrorReturned(t *testing.T) {+ router := createRouter()+ storage := createTestStorage(uuid.New())++ // Test endpoints without auth+ endpoints := []struct {+ method string+ url string+ body interface{}+ }{+ {"GET", "/api/v1/storages", nil},+ {"GET", "/api/v1/storages/" + uuid.New().String(), nil},+ {"POST", "/api/v1/storages", storage},+ {"DELETE", "/api/v1/storages/" + uuid.New().String(), nil},+ {"POST", "/api/v1/storages/" + uuid.New().String() + "/test", nil},+ {"POST", "/api/v1/storages/direct-test", storage},+ }++ for _, endpoint := range endpoints {+ testUnauthorizedEndpoint(t, router, endpoint.method, endpoint.url, endpoint.body)+ }+}++func testUnauthorizedEndpoint(+ t *testing.T,+ router *gin.Engine,+ method, url string,+ body interface{},+) {+ test_utils.MakeRequest(t, router, test_utils.RequestOptions{+ Method: method,+ URL: url,+ Body: body,+ ExpectedStatus: http.StatusUnauthorized,+ })+}++func createRouter() *gin.Engine {+ gin.SetMode(gin.TestMode)+ router := gin.New()+ controller := GetStorageController()+ v1 := router.Group("/api/v1")+ controller.RegisterRoutes(v1)+ return router+}++func createTestStorage(userID uuid.UUID) *Storage {+ return &Storage{+ UserID: userID,+ Type: StorageTypeLocal,+ Name: "Test Storage " + uuid.New().String(),+ LocalStorage: &local_storage.LocalStorage{},+ }+}++func verifyStorageData(t *testing.T, expected *Storage, actual *Storage) {+ assert.Equal(t, expected.Name, actual.Name)+ assert.Equal(t, expected.Type, actual.Type)+ assert.Equal(t, expected.UserID, actual.UserID)+}diff --git a/backend/internal/features/users/service.go b/backend/internal/features/users/service.goindex 7263eafa..4f3ec36d 100644--- a/backend/internal/features/users/service.go+++ b/backend/internal/features/users/service.go@@ -70,29 +70,7 @@ func (s *UserService) SignIn(request *SignInRequest) (*SignInResponse, error) {return nil, errors.New("password is incorrect")}- secretKey, err := s.secretKeyRepository.GetSecretKey()- if err != nil {- return nil, fmt.Errorf("failed to get secret key: %w", err)- }-- tenYearsExpiration := time.Now().UTC().Add(time.Hour * 24 * 365 * 10)-- token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{- "sub": user.ID,- "exp": tenYearsExpiration.Unix(),- "iat": time.Now().UTC().Unix(),- "role": string(user.Role),- })-- tokenString, err := token.SignedString([]byte(secretKey))- if err != nil {- return nil, fmt.Errorf("failed to generate token: %w", err)- }-- return &SignInResponse{- UserID: user.ID,- Token: tokenString,- }, nil+ return s.GenerateAccessToken(user)}func (s *UserService) GetUserFromToken(token string) (*user_models.User, error) {@@ -151,3 +129,33 @@ func (s *UserService) ChangePassword(newPassword string) error {return nil}++func (s *UserService) GetFirstUser() (*user_models.User, error) {+ return s.userRepository.GetFirstUser()+}++func (s *UserService) GenerateAccessToken(user *user_models.User) (*SignInResponse, error) {+ secretKey, err := s.secretKeyRepository.GetSecretKey()+ if err != nil {+ return nil, fmt.Errorf("failed to get secret key: %w", err)+ }++ tenYearsExpiration := time.Now().UTC().Add(time.Hour * 24 * 365 * 10)++ token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{+ "sub": user.ID,+ "exp": tenYearsExpiration.Unix(),+ "iat": time.Now().UTC().Unix(),+ "role": string(user.Role),+ })++ tokenString, err := token.SignedString([]byte(secretKey))+ if err != nil {+ return nil, fmt.Errorf("failed to generate token: %w", err)+ }++ return &SignInResponse{+ UserID: user.ID,+ Token: tokenString,+ }, nil+}diff --git a/backend/internal/features/users/testing.go b/backend/internal/features/users/testing.gonew file mode 100644index 00000000..5b9af3e6--- /dev/null+++ b/backend/internal/features/users/testing.go@@ -0,0 +1,31 @@+package users++func GetUser() *SignInResponse {+ isAnyUserExists, err := userService.IsAnyUserExist()+ if err != nil {+ panic(err)+ }++ if !isAnyUserExists {+ err = userService.SignUp(&SignUpRequest{+ Email: "[email protected]",+ Password: "test",+ })++ if err != nil {+ panic(err)+ }+ }++ user, err := userService.GetFirstUser()+ if err != nil {+ panic(err)+ }++ signInResponse, err := userService.GenerateAccessToken(user)+ if err != nil {+ panic(err)+ }++ return signInResponse+}diff --git a/backend/internal/util/testing/requests.go b/backend/internal/util/testing/requests.gonew file mode 100644index 00000000..c3d69d6e--- /dev/null+++ b/backend/internal/util/testing/requests.go@@ -0,0 +1,213 @@+package testing++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/stretchr/testify/assert"+)++type RequestOptions struct {+ Method string+ URL string+ Body interface{}+ Headers map[string]string+ AuthToken string+ ExpectedStatus int+}++type TestResponse struct {+ StatusCode int+ Body []byte+ Headers http.Header+}++func MakeGetRequest(+ t *testing.T,+ router *gin.Engine,+ url, authToken string,+ expectedStatus int,+) *TestResponse {+ return makeAuthenticatedRequest(t, router, "GET", url, authToken, nil, expectedStatus)+}++func MakeGetRequestAndUnmarshal(+ t *testing.T,+ router *gin.Engine,+ url, authToken string,+ expectedStatus int,+ responseStruct interface{},+) *TestResponse {+ return makeAuthenticatedRequestAndUnmarshal(+ t,+ router,+ "GET",+ url,+ authToken,+ nil,+ expectedStatus,+ responseStruct,+ )+}++func MakePostRequest(+ t *testing.T,+ router *gin.Engine,+ url, authToken string,+ body interface{},+ expectedStatus int,+) *TestResponse {+ return makeAuthenticatedRequest(t, router, "POST", url, authToken, body, expectedStatus)+}++func MakePostRequestAndUnmarshal(+ t *testing.T,+ router *gin.Engine,+ url, authToken string,+ body interface{},+ expectedStatus int,+ responseStruct interface{},+) *TestResponse {+ return makeAuthenticatedRequestAndUnmarshal(+ t,+ router,+ "POST",+ url,+ authToken,+ body,+ expectedStatus,+ responseStruct,+ )+}++func MakePutRequest(+ t *testing.T,+ router *gin.Engine,+ url, authToken string,+ body interface{},+ expectedStatus int,+) *TestResponse {+ return makeAuthenticatedRequest(t, router, "PUT", url, authToken, body, expectedStatus)+}++func MakePutRequestAndUnmarshal(+ t *testing.T,+ router *gin.Engine,+ url, authToken string,+ body interface{},+ expectedStatus int,+ responseStruct interface{},+) *TestResponse {+ return makeAuthenticatedRequestAndUnmarshal(+ t,+ router,+ "PUT",+ url,+ authToken,+ body,+ expectedStatus,+ responseStruct,+ )+}++func MakeDeleteRequest(+ t *testing.T,+ router *gin.Engine,+ url, authToken string,+ expectedStatus int,+) *TestResponse {+ return makeAuthenticatedRequest(t, router, "DELETE", url, authToken, nil, expectedStatus)+}++func MakeRequest(t *testing.T, router *gin.Engine, options RequestOptions) *TestResponse {+ var requestBody *bytes.Buffer++ if options.Body != nil {+ bodyJSON, err := json.Marshal(options.Body)+ assert.NoError(t, err, "Failed to marshal request body")+ requestBody = bytes.NewBuffer(bodyJSON)+ } else {+ requestBody = bytes.NewBuffer(nil)+ }++ req, err := http.NewRequest(options.Method, options.URL, requestBody)+ assert.NoError(t, err, "Failed to create HTTP request")++ if options.Body != nil {+ req.Header.Set("Content-Type", "application/json")+ }++ if options.AuthToken != "" {+ req.Header.Set("Authorization", options.AuthToken)+ }++ for key, value := range options.Headers {+ req.Header.Set(key, value)+ }++ w := httptest.NewRecorder()+ router.ServeHTTP(w, req)++ if options.ExpectedStatus != 0 {+ assert.Equal(t, options.ExpectedStatus, w.Code, "Unexpected status code")+ }++ return &TestResponse{+ StatusCode: w.Code,+ Body: w.Body.Bytes(),+ Headers: w.Header(),+ }+}++func makeRequestAndUnmarshal(+ t *testing.T,+ router *gin.Engine,+ options RequestOptions,+ responseStruct interface{},+) *TestResponse {+ response := MakeRequest(t, router, options)++ if responseStruct != nil && len(response.Body) > 0 {+ err := json.Unmarshal(response.Body, responseStruct)+ assert.NoError(t, err, "Failed to unmarshal response body")+ }++ return response+}++func makeAuthenticatedRequest(+ t *testing.T,+ router *gin.Engine,+ method, url, authToken string,+ body interface{},+ expectedStatus int,+) *TestResponse {+ return MakeRequest(t, router, RequestOptions{+ Method: method,+ URL: url,+ Body: body,+ AuthToken: authToken,+ ExpectedStatus: expectedStatus,+ })+}++func makeAuthenticatedRequestAndUnmarshal(+ t *testing.T,+ router *gin.Engine,+ method, url, authToken string,+ body interface{},+ expectedStatus int,+ responseStruct interface{},+) *TestResponse {+ return makeRequestAndUnmarshal(t, router, RequestOptions{+ Method: method,+ URL: url,+ Body: body,+ AuthToken: authToken,+ ExpectedStatus: expectedStatus,+ }, responseStruct)+}