diff --git a/internal/ads/controller/ads_controlle_test.go b/internal/ads/controller/ads_controller_test.go similarity index 67% rename from internal/ads/controller/ads_controlle_test.go rename to internal/ads/controller/ads_controller_test.go index 7f91e61..46bc430 100644 --- a/internal/ads/controller/ads_controlle_test.go +++ b/internal/ads/controller/ads_controller_test.go @@ -1,7 +1,6 @@ package controller import ( - "2024_2_FIGHT-CLUB/domain" "2024_2_FIGHT-CLUB/internal/service/logger" "2024_2_FIGHT-CLUB/microservices/ads_service/controller/gen" "2024_2_FIGHT-CLUB/microservices/ads_service/mocks" @@ -15,7 +14,6 @@ import ( "net/http" "net/http/httptest" "testing" - "time" ) func TestAdHandler_GetAllPlaces_Success(t *testing.T) { @@ -103,12 +101,13 @@ func TestAdHandler_GetAllPlaces_ConvertError(t *testing.T) { mockGrpcClient.On("GetAllPlaces", mock.Anything, mock.Anything, mock.Anything). Return(response, nil) - utilsMock := mocks.MockUtils{} + utilsMock := &mocks.MockUtils{} utilsMock.On("ConvertGetAllAdsResponseProtoToGo", response). Return(nil, errors.New("conversion error")) adHandler := &AdHandler{ client: mockGrpcClient, + utils: utilsMock, } req := httptest.NewRequest(http.MethodGet, "/housing", nil) @@ -119,62 +118,14 @@ func TestAdHandler_GetAllPlaces_ConvertError(t *testing.T) { // Проверка результата result := w.Result() - defer result.Body.Close() + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + return + } + }(result.Body) assert.Equal(t, http.StatusInternalServerError, result.StatusCode) mockGrpcClient.AssertExpectations(t) utilsMock.AssertExpectations(t) } - -func TestConvertGetAllAdsResponseProtoToGo_Error(t *testing.T) { - mockUtils := new(mocks.MockUtils) - - protoResponse := &gen.GetAllAdsResponseList{} - - mockUtils.On("ConvertGetAllAdsResponseProtoToGo", protoResponse). - Return(domain.GetAllAdsListResponse{}, errors.New("conversion error")) - - result, err := mockUtils.ConvertGetAllAdsResponseProtoToGo(protoResponse) - - assert.Error(t, err) - assert.Equal(t, "conversion error", err.Error()) - assert.Empty(t, result) - - mockUtils.AssertExpectations(t) -} - -func TestConvertAdProtoToGo_Error(t *testing.T) { - mockUtils := new(mocks.MockUtils) - - protoAd := &gen.GetAllAdsResponse{} - - mockUtils.On("ConvertAdProtoToGo", protoAd). - Return(domain.GetAllAdsResponse{}, errors.New("ad conversion error")) - - result, err := mockUtils.ConvertAdProtoToGo(protoAd) - - assert.Error(t, err) - assert.Equal(t, "ad conversion error", err.Error()) - assert.Empty(t, result) - - mockUtils.AssertExpectations(t) -} - -func TestParseDate_Error(t *testing.T) { - mockUtils := new(mocks.MockUtils) - - dateStr := "invalid-date" - adID := "123" - fieldName := "PublicationDate" - - mockUtils.On("ParseDate", dateStr, adID, fieldName). - Return(time.Time{}, errors.New("invalid date format")) - - parsedDate, err := mockUtils.ParseDate(dateStr, adID, fieldName) - - assert.Error(t, err) - assert.Equal(t, "invalid date format", err.Error()) - assert.Equal(t, time.Time{}, parsedDate) - - mockUtils.AssertExpectations(t) -} diff --git a/internal/auth/controller/auth_controller_test.go b/internal/auth/controller/auth_controller_test.go new file mode 100644 index 0000000..eb1540f --- /dev/null +++ b/internal/auth/controller/auth_controller_test.go @@ -0,0 +1,207 @@ +package controller + +import ( + "2024_2_FIGHT-CLUB/domain" + "2024_2_FIGHT-CLUB/internal/service/logger" + "2024_2_FIGHT-CLUB/internal/service/utils" + "2024_2_FIGHT-CLUB/microservices/auth_service/controller/gen" + "2024_2_FIGHT-CLUB/microservices/auth_service/mocks" + "bytes" + "errors" + "github.com/mailru/easyjson" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "io" + "net/http" + "net/http/httptest" + "testing" +) + +// Тест для успешного выполнения RegisterUser +func TestAuthHandler_RegisterUser_Success(t *testing.T) { + require.NoError(t, logger.InitLoggers()) + defer func() { + err := logger.SyncLoggers() + if err != nil { + return + } + }() + + // Мок gRPC клиента + mockGrpcClient := new(mocks.MockGrpcClient) + mockResponse := &gen.UserResponse{ + SessionId: "session123", + Jwttoken: "token123", + User: &gen.User{ + Id: "test_user_id", + Username: "test_user_name", + Email: "test@example.com", + }, + } + mockGrpcClient.On("RegisterUser", mock.Anything, mock.Anything, mock.Anything).Return(mockResponse, nil) + + // Инициализация обработчика + authHandler := AuthHandler{ + client: mockGrpcClient, + } + + // Создание тела запроса + user := domain.User{ + Username: "test_user_name", + Email: "test@example.com", + Name: "Test User", + Password: "password123", + } + body, _ := easyjson.Marshal(user) + + // Создание HTTP запроса + req := httptest.NewRequest(http.MethodPost, "/auth/register", bytes.NewBuffer(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Real-IP", "127.0.0.1") + + w := httptest.NewRecorder() + + // Вызов обработчика + authHandler.RegisterUser(w, req) + + // Проверка результата + result := w.Result() + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + return + } + }(result.Body) + + assert.Equal(t, http.StatusCreated, result.StatusCode) + mockGrpcClient.AssertExpectations(t) +} + +// Тест на ошибку при декодировании JSON +func TestAuthHandler_RegisterUser_DecodeError(t *testing.T) { + require.NoError(t, logger.InitLoggers()) + defer func() { + err := logger.SyncLoggers() + if err != nil { + return + } + }() + + authHandler := AuthHandler{} + + // Некорректное тело запроса + req := httptest.NewRequest(http.MethodPost, "/auth/register", bytes.NewBuffer([]byte("{invalid_json}"))) + w := httptest.NewRecorder() + + // Вызов обработчика + authHandler.RegisterUser(w, req) + + // Проверка результата + result := w.Result() + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + return + } + }(result.Body) + + assert.Equal(t, http.StatusBadRequest, result.StatusCode) +} + +// Тест на ошибку от gRPC клиента +func TestAuthHandler_RegisterUser_GrpcError(t *testing.T) { + require.NoError(t, logger.InitLoggers()) + defer func() { + err := logger.SyncLoggers() + if err != nil { + return + } + }() + grpcErr := status.Error(codes.Internal, "gRPC Error") + mockGrpcClient := new(mocks.MockGrpcClient) + mockGrpcClient.On("RegisterUser", mock.Anything, mock.Anything, mock.Anything).Return(nil, grpcErr) + + authHandler := AuthHandler{ + client: mockGrpcClient, + } + + user := domain.User{ + Username: "testuser", + Email: "test@example.com", + Name: "Test User", + Password: "password123", + } + body, _ := easyjson.Marshal(user) + + req := httptest.NewRequest(http.MethodPost, "/auth/register", bytes.NewBuffer(body)) + req.Header.Set("Content-Type", "application/json") + + w := httptest.NewRecorder() + authHandler.RegisterUser(w, req) + + result := w.Result() + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + return + } + }(result.Body) + + assert.Equal(t, http.StatusInternalServerError, result.StatusCode) + mockGrpcClient.AssertExpectations(t) +} + +// Тест на ошибку при конверсии ответа +func TestAuthHandler_RegisterUser_ConvertError(t *testing.T) { + require.NoError(t, logger.InitLoggers()) + defer func() { + err := logger.SyncLoggers() + if err != nil { + return + } + }() + + mockGrpcClient := new(mocks.MockGrpcClient) + mockResponse := &gen.UserResponse{ + SessionId: "session123", + Jwttoken: "token123", + User: &gen.User{ + Id: "test_user_id", + Username: "test_user_name", + Email: "test@example.com", + }, + } + mockGrpcClient.On("RegisterUser", mock.Anything, mock.Anything).Return(mockResponse, nil) + + // Переопределяем конвертацию ответа, чтобы она возвращала ошибку + utils.ConvertAuthResponseProtoToGo = func(protoResponse *gen.RegisterUserResponse, sessionID string) (interface{}, error) { + return nil, errors.New("conversion error") + } + + authHandler := AuthHandler{ + client: mockGrpcClient, + } + + user := domain.User{ + Username: "testuser", + Email: "test@example.com", + Name: "Test User", + Password: "password123", + } + body, _ := easyjson.Marshal(user) + + req := httptest.NewRequest(http.MethodPost, "/register", bytes.NewBuffer(body)) + req.Header.Set("Content-Type", "application/json") + + w := httptest.NewRecorder() + authHandler.RegisterUser(w, req) + + result := w.Result() + defer result.Body.Close() + + assert.Equal(t, http.StatusInternalServerError, result.StatusCode) + mockGrpcClient.AssertExpectations(t) +} diff --git a/microservices/ads_service/mocks/mocks.go b/microservices/ads_service/mocks/mocks.go index e12f44d..c7f4ae4 100644 --- a/microservices/ads_service/mocks/mocks.go +++ b/microservices/ads_service/mocks/mocks.go @@ -6,10 +6,9 @@ import ( "2024_2_FIGHT-CLUB/microservices/ads_service/controller/gen" "context" "github.com/golang-jwt/jwt" - "github.com/gorilla/sessions" "github.com/stretchr/testify/mock" "google.golang.org/grpc" - "net/http" + "time" ) type MockJwtTokenService struct { @@ -35,7 +34,6 @@ type MockServiceSession struct { MockLogoutSession func(ctx context.Context, sessionID string) error MockCreateSession func(ctx context.Context, user *domain.User) (string, error) MockGetSessionData func(ctx context.Context, sessionID string) (*domain.SessionData, error) - MockGetSession func(r *http.Request) (*sessions.Session, error) } func (m *MockServiceSession) GetUserID(ctx context.Context, sessionID string) (string, error) { @@ -54,12 +52,8 @@ func (m *MockServiceSession) GetSessionData(ctx context.Context, sessionID strin return m.MockGetSessionData(ctx, sessionID) } -func (m *MockServiceSession) GetSession(r *http.Request) (*sessions.Session, error) { - return m.MockGetSession(r) -} - type MockAdUseCase struct { - MockGetAllPlaces func(ctx context.Context, filter domain.AdFilter) ([]domain.GetAllAdsResponse, error) + MockGetAllPlaces func(ctx context.Context, filter domain.AdFilter, userId string) ([]domain.GetAllAdsResponse, error) MockGetOnePlace func(ctx context.Context, adId string, isAuthorized bool) (domain.GetAllAdsResponse, error) MockCreatePlace func(ctx context.Context, place *domain.Ad, fileHeader [][]byte, newPlace domain.CreateAdRequest, userId string) error MockUpdatePlace func(ctx context.Context, place *domain.Ad, adId string, userId string, fileHeader [][]byte, updatedPlace domain.UpdateAdRequest) error @@ -71,15 +65,15 @@ type MockAdUseCase struct { MockDeleteFromFavorites func(ctx context.Context, adId string, userId string) error MockGetUserFavorites func(ctx context.Context, userId string) ([]domain.GetAllAdsResponse, error) MockUpdatePriority func(ctx context.Context, adId string, userId string, amount int) error - MockStartPriorityResetWorker func(ctx context.Context) + MockStartPriorityResetWorker func(ctx context.Context, tickerInterval time.Duration) } func (m *MockAdUseCase) DeleteAdImage(ctx context.Context, adId string, imageId string, userId string) error { return m.MockDeleteAdImage(ctx, adId, imageId, userId) } -func (m *MockAdUseCase) GetAllPlaces(ctx context.Context, filter domain.AdFilter) ([]domain.GetAllAdsResponse, error) { - return m.MockGetAllPlaces(ctx, filter) +func (m *MockAdUseCase) GetAllPlaces(ctx context.Context, filter domain.AdFilter, userId string) ([]domain.GetAllAdsResponse, error) { + return m.MockGetAllPlaces(ctx, filter, userId) } func (m *MockAdUseCase) GetOnePlace(ctx context.Context, adId string, isAuthorized bool) (domain.GetAllAdsResponse, error) { @@ -122,8 +116,8 @@ func (m *MockAdUseCase) UpdatePriority(ctx context.Context, adId string, userId return m.MockUpdatePriority(ctx, adId, userId, amount) } -func (m *MockAdUseCase) StartPriorityResetWorker(ctx context.Context) { - m.MockStartPriorityResetWorker(ctx) +func (m *MockAdUseCase) StartPriorityResetWorker(ctx context.Context, tickerInterval time.Duration) { + m.MockStartPriorityResetWorker(ctx, tickerInterval) } type MockAdRepository struct { diff --git a/microservices/ads_service/mocks/mocks_convert.go b/microservices/ads_service/mocks/mocks_convert.go index ccbec1b..4919c72 100644 --- a/microservices/ads_service/mocks/mocks_convert.go +++ b/microservices/ads_service/mocks/mocks_convert.go @@ -3,8 +3,9 @@ package mocks import ( "2024_2_FIGHT-CLUB/domain" "2024_2_FIGHT-CLUB/microservices/ads_service/controller/gen" + authGen "2024_2_FIGHT-CLUB/microservices/auth_service/controller/gen" + cityGen "2024_2_FIGHT-CLUB/microservices/city_service/controller/gen" "github.com/stretchr/testify/mock" - "time" ) type MockUtils struct { @@ -27,10 +28,50 @@ func (m *MockUtils) ConvertAdProtoToGo(ad *gen.GetAllAdsResponse) (domain.GetAll return domain.GetAllAdsResponse{}, args.Error(1) } -func (m *MockUtils) ParseDate(dateStr, adID, fieldName string) (time.Time, error) { - args := m.Called(dateStr, adID, fieldName) - if res, ok := args.Get(0).(time.Time); ok { +func (m *MockUtils) ConvertAuthResponseProtoToGo(response *authGen.UserResponse, userSession string) (domain.AuthResponse, error) { + args := m.Called(response, userSession) + if res, ok := args.Get(0).(domain.AuthResponse); ok { return res, args.Error(1) } - return time.Time{}, args.Error(1) + return domain.AuthResponse{}, args.Error(1) +} + +func (m *MockUtils) ConvertUserResponseProtoToGo(user *authGen.MetadataOneUser) (domain.UserDataResponse, error) { + args := m.Called(user) + if res, ok := args.Get(0).(domain.UserDataResponse); ok { + return res, args.Error(1) + } + return domain.UserDataResponse{}, args.Error(1) +} + +func (m *MockUtils) ConvertUsersProtoToGo(users *authGen.AllUsersResponse) ([]*domain.UserDataResponse, error) { + args := m.Called(users) + if res, ok := args.Get(0).([]*domain.UserDataResponse); ok { + return res, args.Error(1) + } + return []*domain.UserDataResponse{}, args.Error(1) +} + +func (m *MockUtils) ConvertSessionDataProtoToGo(sessionData *authGen.SessionDataResponse) (domain.SessionData, error) { + args := m.Called(sessionData) + if res, ok := args.Get(0).(domain.SessionData); ok { + return res, args.Error(1) + } + return domain.SessionData{}, args.Error(1) +} + +func (m *MockUtils) ConvertAllCitiesProtoToGo(cities *cityGen.GetCitiesResponse) ([]*domain.City, error) { + args := m.Called(cities) + if res, ok := args.Get(0).([]*domain.City); ok { + return res, args.Error(1) + } + return []*domain.City{}, args.Error(1) +} + +func (m *MockUtils) ConvertOneCityProtoToGo(city *cityGen.City) (domain.City, error) { + args := m.Called(city) + if res, ok := args.Get(0).(domain.City); ok { + return res, args.Error(1) + } + return domain.City{}, args.Error(1) } diff --git a/microservices/auth_service/mocks/mocks.go b/microservices/auth_service/mocks/mocks.go index 655e59d..ef06ea4 100644 --- a/microservices/auth_service/mocks/mocks.go +++ b/microservices/auth_service/mocks/mocks.go @@ -3,25 +3,25 @@ package mocks import ( "2024_2_FIGHT-CLUB/domain" "2024_2_FIGHT-CLUB/internal/service/middleware" + "2024_2_FIGHT-CLUB/microservices/auth_service/controller/gen" "context" "github.com/golang-jwt/jwt" - "github.com/gorilla/sessions" - "mime/multipart" - "net/http" + "github.com/stretchr/testify/mock" + "google.golang.org/grpc" ) type MockJwtTokenService struct { - MockCreate func(s *sessions.Session, tokenExpTime int64) (string, error) - MockValidate func(tokenString string) (*middleware.JwtCsrfClaims, error) + MockCreate func(session_id string, tokenExpTime int64) (string, error) + MockValidate func(tokenString string, expectedSessionId string) (*middleware.JwtCsrfClaims, error) MockParseSecretGetter func(token *jwt.Token) (interface{}, error) } -func (m *MockJwtTokenService) Create(s *sessions.Session, tokenExpTime int64) (string, error) { - return m.MockCreate(s, tokenExpTime) +func (m *MockJwtTokenService) Create(session_id string, tokenExpTime int64) (string, error) { + return m.MockCreate(session_id, tokenExpTime) } -func (m *MockJwtTokenService) Validate(tokenString string) (*middleware.JwtCsrfClaims, error) { - return m.MockValidate(tokenString) +func (m *MockJwtTokenService) Validate(tokenString string, expectedSessionId string) (*middleware.JwtCsrfClaims, error) { + return m.MockValidate(tokenString, expectedSessionId) } func (m *MockJwtTokenService) ParseSecretGetter(token *jwt.Token) (interface{}, error) { @@ -29,37 +29,32 @@ func (m *MockJwtTokenService) ParseSecretGetter(token *jwt.Token) (interface{}, } type MockServiceSession struct { - MockGetUserID func(ctx context.Context, r *http.Request) (string, error) - MockLogoutSession func(ctx context.Context, r *http.Request, w http.ResponseWriter) error - MockCreateSession func(ctx context.Context, r *http.Request, w http.ResponseWriter, user *domain.User) (*sessions.Session, error) - MockGetSessionData func(ctx context.Context, r *http.Request) (*map[string]interface{}, error) - MockGetSession func(ctx context.Context, r *http.Request) (*sessions.Session, error) + MockGetUserID func(ctx context.Context, sessionID string) (string, error) + MockLogoutSession func(ctx context.Context, sessionID string) error + MockCreateSession func(ctx context.Context, user *domain.User) (string, error) + MockGetSessionData func(ctx context.Context, sessionID string) (*domain.SessionData, error) } -func (m *MockServiceSession) GetUserID(ctx context.Context, r *http.Request) (string, error) { - return m.MockGetUserID(ctx, r) +func (m *MockServiceSession) GetUserID(ctx context.Context, sessionID string) (string, error) { + return m.MockGetUserID(ctx, sessionID) } -func (m *MockServiceSession) LogoutSession(ctx context.Context, r *http.Request, w http.ResponseWriter) error { - return m.MockLogoutSession(ctx, r, w) +func (m *MockServiceSession) LogoutSession(ctx context.Context, sessionID string) error { + return m.MockLogoutSession(ctx, sessionID) } -func (m *MockServiceSession) CreateSession(ctx context.Context, r *http.Request, w http.ResponseWriter, user *domain.User) (*sessions.Session, error) { - return m.MockCreateSession(ctx, r, w, user) +func (m *MockServiceSession) CreateSession(ctx context.Context, user *domain.User) (string, error) { + return m.MockCreateSession(ctx, user) } -func (m *MockServiceSession) GetSessionData(ctx context.Context, r *http.Request) (*map[string]interface{}, error) { - return m.MockGetSessionData(ctx, r) -} - -func (m *MockServiceSession) GetSession(ctx context.Context, r *http.Request) (*sessions.Session, error) { - return m.MockGetSession(ctx, r) +func (m *MockServiceSession) GetSessionData(ctx context.Context, sessionID string) (*domain.SessionData, error) { + return m.MockGetSessionData(ctx, sessionID) } type MockAuthUseCase struct { MockRegisterUser func(ctx context.Context, creds *domain.User) error MockLoginUser func(ctx context.Context, creds *domain.User) (*domain.User, error) - MockPutUser func(ctx context.Context, creds *domain.User, userID string, avatar *multipart.FileHeader) error + MockPutUser func(ctx context.Context, creds *domain.User, userID string, avatar []byte) error MockGetAllUser func(ctx context.Context) ([]domain.User, error) MockGetUserById func(ctx context.Context, userID string) (*domain.User, error) } @@ -72,7 +67,7 @@ func (m *MockAuthUseCase) LoginUser(ctx context.Context, creds *domain.User) (*d return m.MockLoginUser(ctx, creds) } -func (m *MockAuthUseCase) PutUser(ctx context.Context, creds *domain.User, userID string, avatar *multipart.FileHeader) error { +func (m *MockAuthUseCase) PutUser(ctx context.Context, creds *domain.User, userID string, avatar []byte) error { return m.MockPutUser(ctx, creds, userID, avatar) } @@ -134,3 +129,52 @@ func (m *MockMinioService) UploadFile(file []byte, contentType string, id string func (m *MockMinioService) DeleteFile(path string) error { return m.DeleteFileFunc(path) } + +type MockGrpcClient struct { + mock.Mock +} + +func (m *MockGrpcClient) RegisterUser(ctx context.Context, in *gen.RegisterUserRequest, opts ...grpc.CallOption) (*gen.UserResponse, error) { + args := m.Called(ctx, in, opts) + return args.Get(0).(*gen.UserResponse), args.Error(1) +} +func (m *MockGrpcClient) LoginUser(ctx context.Context, in *gen.LoginUserRequest, opts ...grpc.CallOption) (*gen.UserResponse, error) { + args := m.Called(ctx, in, opts) + return args.Get(0).(*gen.UserResponse), args.Error(1) +} +func (m *MockGrpcClient) LogoutUser(ctx context.Context, in *gen.LogoutRequest, opts ...grpc.CallOption) (*gen.LogoutUserResponse, error) { + args := m.Called(ctx, in, opts) + return args.Get(0).(*gen.LogoutUserResponse), args.Error(1) +} +func (m *MockGrpcClient) PutUser(ctx context.Context, in *gen.PutUserRequest, opts ...grpc.CallOption) (*gen.UpdateResponse, error) { + args := m.Called(ctx, in, opts) + return args.Get(0).(*gen.UpdateResponse), args.Error(1) +} +func (m *MockGrpcClient) GetUserById(ctx context.Context, in *gen.GetUserByIdRequest, opts ...grpc.CallOption) (*gen.GetUserByIdResponse, error) { + args := m.Called(ctx, in, opts) + return args.Get(0).(*gen.GetUserByIdResponse), args.Error(1) +} +func (m *MockGrpcClient) GetAllUsers(ctx context.Context, in *gen.Empty, opts ...grpc.CallOption) (*gen.AllUsersResponse, error) { + args := m.Called(ctx, in, opts) + return args.Get(0).(*gen.AllUsersResponse), args.Error(1) +} +func (m *MockGrpcClient) GetSessionData(ctx context.Context, in *gen.GetSessionDataRequest, opts ...grpc.CallOption) (*gen.SessionDataResponse, error) { + args := m.Called(ctx, in, opts) + return args.Get(0).(*gen.SessionDataResponse), args.Error(1) +} +func (m *MockGrpcClient) RefreshCsrfToken(ctx context.Context, in *gen.RefreshCsrfTokenRequest, opts ...grpc.CallOption) (*gen.RefreshCsrfTokenResponse, error) { + args := m.Called(ctx, in, opts) + return args.Get(0).(*gen.RefreshCsrfTokenResponse), args.Error(1) +} + +type MockUtils struct { + mock.Mock +} + +func (m *MockUtils) ConvertAuthResponseProtoToGo(response *gen.UserResponse, userSession string) (domain.AuthResponse, error) { + args := m.Called(response, userSession) + if res, ok := args.Get(0).(domain.AuthResponse); ok { + return res, args.Error(1) + } + return domain.AuthResponse{}, args.Error(1) +} diff --git a/microservices/auth_service/repository/auth_repository_test.go b/microservices/auth_service/repository/auth_repository_test.go index e882142..83f42bf 100644 --- a/microservices/auth_service/repository/auth_repository_test.go +++ b/microservices/auth_service/repository/auth_repository_test.go @@ -587,6 +587,36 @@ func TestAuthRepository_PutUser(t *testing.T) { assert.Equal(t, "error updating user", err.Error()) }) + // Тест-кейс 3: Ошибка обновления пользователя + t.Run("Error on Update isHost", func(t *testing.T) { + mock.ExpectBegin() + mock.ExpectExec(regexp.QuoteMeta(`UPDATE "users" SET "username"=$1,"password"=$2,"email"=$3,"name"=$4,"score"=$5,"avatar"=$6,"sex"=$7,"guestCount"=$8,"birthDate"=$9,"isHost"=$10 WHERE UUID = $11`)). + WithArgs( + creds.Username, + creds.Password, + creds.Email, + creds.Name, + creds.Score, + creds.Avatar, + creds.Sex, + creds.GuestCount, + creds.Birthdate, + creds.IsHost, + userID, + ).WillReturnResult(sqlmock.NewResult(1, 1)) + mock.ExpectCommit() + mock.ExpectBegin() + mock.ExpectExec(regexp.QuoteMeta(`UPDATE "users" SET "isHost"=$1 WHERE UUID = $2`)). + WithArgs(creds.IsHost, userID). + WillReturnError(errors.New("error updating user")) + mock.ExpectRollback() + + err := repo.PutUser(ctx, creds, userID) + + assert.Error(t, err) + assert.Equal(t, "error updating user", err.Error()) + }) + // Проверяем, что все ожидания выполнены require.NoError(t, mock.ExpectationsWereMet()) }