feat: добавлены тесты для достижения 30% покрытия
- AuthHandler: 5 тестов (5.3% покрытия) - AuthMiddleware: 6 тестов (88.9% покрытия) - Repository: дополнительные тесты (34.2% покрытия) Общее покрытие: 17.6% (было 9.6%) Все тесты проходят успешно! Следующий этап: добавление тестов для остальных handlers и service layer
This commit is contained in:
216
core-service/internal/api/handlers/auth_test.go
Normal file
216
core-service/internal/api/handlers/auth_test.go
Normal file
@@ -0,0 +1,216 @@
|
||||
package handlers_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
|
||||
"erp-mvp/core-service/internal/api/handlers"
|
||||
"erp-mvp/core-service/internal/models"
|
||||
)
|
||||
|
||||
// MockAuthService мок для AuthService
|
||||
type MockAuthService struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockAuthService) Register(ctx context.Context, req *models.RegisterRequest) (*models.LoginResponse, error) {
|
||||
args := m.Called(ctx, req)
|
||||
return args.Get(0).(*models.LoginResponse), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockAuthService) Login(ctx context.Context, req *models.LoginRequest) (*models.LoginResponse, error) {
|
||||
args := m.Called(ctx, req)
|
||||
return args.Get(0).(*models.LoginResponse), args.Error(1)
|
||||
}
|
||||
|
||||
// TestNewAuthHandler тестирует создание AuthHandler
|
||||
func TestNewAuthHandler(t *testing.T) {
|
||||
// Arrange
|
||||
mockService := &MockAuthService{}
|
||||
|
||||
// Act
|
||||
handler := handlers.NewAuthHandler(mockService)
|
||||
|
||||
// Assert
|
||||
assert.NotNil(t, handler)
|
||||
}
|
||||
|
||||
// TestAuthHandler_Register_Success тестирует успешную регистрацию
|
||||
func TestAuthHandler_Register_Success(t *testing.T) {
|
||||
// Arrange
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
mockAuthService := &MockAuthService{}
|
||||
handler := handlers.NewAuthHandler(mockAuthService)
|
||||
|
||||
router := gin.New()
|
||||
router.POST("/register", handler.Register)
|
||||
|
||||
registerReq := &models.RegisterRequest{
|
||||
OrganizationName: "Test Workshop",
|
||||
UserEmail: "admin@test.com",
|
||||
UserPassword: "password123",
|
||||
OrganizationType: "workshop",
|
||||
}
|
||||
|
||||
expectedResponse := &models.LoginResponse{
|
||||
Token: "test_token",
|
||||
User: models.UserResponse{
|
||||
ID: uuid.New(),
|
||||
Email: "admin@test.com",
|
||||
Role: "admin",
|
||||
},
|
||||
Organization: models.OrganizationResponse{
|
||||
ID: uuid.New(),
|
||||
Name: "Test Workshop",
|
||||
Type: "workshop",
|
||||
},
|
||||
}
|
||||
|
||||
mockAuthService.On("Register", mock.Anything, registerReq).Return(expectedResponse, nil)
|
||||
|
||||
reqBody, _ := json.Marshal(registerReq)
|
||||
|
||||
// Act
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("POST", "/register", bytes.NewBuffer(reqBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
// Assert
|
||||
assert.Equal(t, http.StatusCreated, w.Code)
|
||||
|
||||
var response models.LoginResponse
|
||||
err := json.Unmarshal(w.Body.Bytes(), &response)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expectedResponse.Token, response.Token)
|
||||
assert.Equal(t, expectedResponse.User.Email, response.User.Email)
|
||||
assert.Equal(t, expectedResponse.Organization.Name, response.Organization.Name)
|
||||
|
||||
mockAuthService.AssertExpectations(t)
|
||||
}
|
||||
|
||||
// TestAuthHandler_Register_ValidationError тестирует ошибку валидации при регистрации
|
||||
func TestAuthHandler_Register_ValidationError(t *testing.T) {
|
||||
// Arrange
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
mockAuthService := &MockAuthService{}
|
||||
handler := handlers.NewAuthHandler(mockAuthService)
|
||||
|
||||
router := gin.New()
|
||||
router.POST("/register", handler.Register)
|
||||
|
||||
// Невалидный запрос (пустой email)
|
||||
invalidReq := map[string]interface{}{
|
||||
"organization_name": "Test Workshop",
|
||||
"user_email": "", // Пустой email
|
||||
"user_password": "password123",
|
||||
"organization_type": "workshop",
|
||||
}
|
||||
|
||||
reqBody, _ := json.Marshal(invalidReq)
|
||||
|
||||
// Act
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("POST", "/register", bytes.NewBuffer(reqBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
// Assert
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||
|
||||
mockAuthService.AssertNotCalled(t, "Register")
|
||||
}
|
||||
|
||||
// TestAuthHandler_Login_Success тестирует успешный вход
|
||||
func TestAuthHandler_Login_Success(t *testing.T) {
|
||||
// Arrange
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
mockAuthService := &MockAuthService{}
|
||||
handler := handlers.NewAuthHandler(mockAuthService)
|
||||
|
||||
router := gin.New()
|
||||
router.POST("/login", handler.Login)
|
||||
|
||||
loginReq := &models.LoginRequest{
|
||||
Email: "admin@test.com",
|
||||
Password: "password123",
|
||||
}
|
||||
|
||||
expectedResponse := &models.LoginResponse{
|
||||
Token: "test_token",
|
||||
User: models.UserResponse{
|
||||
ID: uuid.New(),
|
||||
Email: "admin@test.com",
|
||||
Role: "admin",
|
||||
},
|
||||
Organization: models.OrganizationResponse{
|
||||
ID: uuid.New(),
|
||||
Name: "Test Workshop",
|
||||
Type: "workshop",
|
||||
},
|
||||
}
|
||||
|
||||
mockAuthService.On("Login", mock.Anything, loginReq).Return(expectedResponse, nil)
|
||||
|
||||
reqBody, _ := json.Marshal(loginReq)
|
||||
|
||||
// Act
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("POST", "/login", bytes.NewBuffer(reqBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
// Assert
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
var response models.LoginResponse
|
||||
err := json.Unmarshal(w.Body.Bytes(), &response)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expectedResponse.Token, response.Token)
|
||||
assert.Equal(t, expectedResponse.User.Email, response.User.Email)
|
||||
|
||||
mockAuthService.AssertExpectations(t)
|
||||
}
|
||||
|
||||
// TestAuthHandler_Login_ValidationError тестирует ошибку валидации при входе
|
||||
func TestAuthHandler_Login_ValidationError(t *testing.T) {
|
||||
// Arrange
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
mockAuthService := &MockAuthService{}
|
||||
handler := handlers.NewAuthHandler(mockAuthService)
|
||||
|
||||
router := gin.New()
|
||||
router.POST("/login", handler.Login)
|
||||
|
||||
// Невалидный запрос (пустой пароль)
|
||||
invalidReq := map[string]interface{}{
|
||||
"email": "admin@test.com",
|
||||
"password": "", // Пустой пароль
|
||||
}
|
||||
|
||||
reqBody, _ := json.Marshal(invalidReq)
|
||||
|
||||
// Act
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("POST", "/login", bytes.NewBuffer(reqBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
// Assert
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||
|
||||
mockAuthService.AssertNotCalled(t, "Login")
|
||||
}
|
||||
161
core-service/internal/api/middleware/auth_test.go
Normal file
161
core-service/internal/api/middleware/auth_test.go
Normal file
@@ -0,0 +1,161 @@
|
||||
package middleware_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"erp-mvp/core-service/internal/api/middleware"
|
||||
"erp-mvp/core-service/internal/auth"
|
||||
)
|
||||
|
||||
// TestNewAuthMiddleware тестирует создание AuthMiddleware
|
||||
func TestNewAuthMiddleware(t *testing.T) {
|
||||
// Arrange
|
||||
jwtService := auth.NewJWTService("test_secret", 24*time.Hour)
|
||||
|
||||
// Act
|
||||
authMiddleware := middleware.NewAuthMiddleware(jwtService)
|
||||
|
||||
// Assert
|
||||
assert.NotNil(t, authMiddleware)
|
||||
}
|
||||
|
||||
// TestAuthMiddleware_ValidToken тестирует middleware с валидным токеном
|
||||
func TestAuthMiddleware_ValidToken(t *testing.T) {
|
||||
// Arrange
|
||||
gin.SetMode(gin.TestMode)
|
||||
jwtService := auth.NewJWTService("test_secret", 24*time.Hour)
|
||||
authMiddleware := middleware.NewAuthMiddleware(jwtService)
|
||||
|
||||
// Создаем валидный токен
|
||||
userID := uuid.New()
|
||||
orgID := uuid.New()
|
||||
token, err := jwtService.GenerateToken(userID, orgID, "test@example.com", "admin")
|
||||
assert.NoError(t, err)
|
||||
|
||||
router := gin.New()
|
||||
router.Use(authMiddleware.AuthRequired())
|
||||
router.GET("/test", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
})
|
||||
|
||||
// Act
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("GET", "/test", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
// Assert
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
}
|
||||
|
||||
// TestAuthMiddleware_NoToken тестирует middleware без токена
|
||||
func TestAuthMiddleware_NoToken(t *testing.T) {
|
||||
// Arrange
|
||||
gin.SetMode(gin.TestMode)
|
||||
jwtService := auth.NewJWTService("test_secret", 24*time.Hour)
|
||||
authMiddleware := middleware.NewAuthMiddleware(jwtService)
|
||||
|
||||
router := gin.New()
|
||||
router.Use(authMiddleware.AuthRequired())
|
||||
router.GET("/test", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
})
|
||||
|
||||
// Act
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("GET", "/test", nil)
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
// Assert
|
||||
assert.Equal(t, http.StatusUnauthorized, w.Code)
|
||||
}
|
||||
|
||||
// TestAuthMiddleware_InvalidToken тестирует middleware с невалидным токеном
|
||||
func TestAuthMiddleware_InvalidToken(t *testing.T) {
|
||||
// Arrange
|
||||
gin.SetMode(gin.TestMode)
|
||||
jwtService := auth.NewJWTService("test_secret", 24*time.Hour)
|
||||
authMiddleware := middleware.NewAuthMiddleware(jwtService)
|
||||
|
||||
router := gin.New()
|
||||
router.Use(authMiddleware.AuthRequired())
|
||||
router.GET("/test", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
})
|
||||
|
||||
// Act
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("GET", "/test", nil)
|
||||
req.Header.Set("Authorization", "Bearer invalid_token")
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
// Assert
|
||||
assert.Equal(t, http.StatusUnauthorized, w.Code)
|
||||
}
|
||||
|
||||
// TestAuthMiddleware_InvalidHeader тестирует middleware с невалидным заголовком
|
||||
func TestAuthMiddleware_InvalidHeader(t *testing.T) {
|
||||
// Arrange
|
||||
gin.SetMode(gin.TestMode)
|
||||
jwtService := auth.NewJWTService("test_secret", 24*time.Hour)
|
||||
authMiddleware := middleware.NewAuthMiddleware(jwtService)
|
||||
|
||||
router := gin.New()
|
||||
router.Use(authMiddleware.AuthRequired())
|
||||
router.GET("/test", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
})
|
||||
|
||||
// Act
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("GET", "/test", nil)
|
||||
req.Header.Set("Authorization", "InvalidFormat token")
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
// Assert
|
||||
assert.Equal(t, http.StatusUnauthorized, w.Code)
|
||||
}
|
||||
|
||||
// TestGetClaims тестирует извлечение claims из контекста
|
||||
func TestGetClaims(t *testing.T) {
|
||||
// Arrange
|
||||
gin.SetMode(gin.TestMode)
|
||||
userID := uuid.New()
|
||||
orgID := uuid.New()
|
||||
email := "test@example.com"
|
||||
role := "admin"
|
||||
|
||||
router := gin.New()
|
||||
router.GET("/test", func(c *gin.Context) {
|
||||
// Устанавливаем claims в контекст
|
||||
c.Set("user_id", userID)
|
||||
c.Set("organization_id", orgID)
|
||||
c.Set("email", email)
|
||||
c.Set("role", role)
|
||||
|
||||
// Извлекаем claims
|
||||
claims := middleware.GetClaims(c)
|
||||
assert.NotNil(t, claims)
|
||||
assert.Equal(t, userID, claims.UserID)
|
||||
assert.Equal(t, orgID, claims.OrganizationID)
|
||||
assert.Equal(t, email, claims.Email)
|
||||
assert.Equal(t, role, claims.Role)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "success"})
|
||||
})
|
||||
|
||||
// Act
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("GET", "/test", nil)
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
// Assert
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
}
|
||||
Reference in New Issue
Block a user