Skip to content

Commit

Permalink
test pipidodo
Browse files Browse the repository at this point in the history
  • Loading branch information
JolyBI3ll committed Dec 17, 2024
1 parent a2c32a8 commit f68dbe9
Show file tree
Hide file tree
Showing 6 changed files with 370 additions and 103 deletions.
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -15,7 +14,6 @@ import (
"net/http"
"net/http/httptest"
"testing"
"time"
)

func TestAdHandler_GetAllPlaces_Success(t *testing.T) {
Expand Down Expand Up @@ -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)
Expand All @@ -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)
}
207 changes: 207 additions & 0 deletions internal/auth/controller/auth_controller_test.go
Original file line number Diff line number Diff line change
@@ -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: "[email protected]",
},
}
mockGrpcClient.On("RegisterUser", mock.Anything, mock.Anything, mock.Anything).Return(mockResponse, nil)

// Инициализация обработчика
authHandler := AuthHandler{
client: mockGrpcClient,
}

// Создание тела запроса
user := domain.User{
Username: "test_user_name",
Email: "[email protected]",
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: "[email protected]",
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: "[email protected]",
},
}
mockGrpcClient.On("RegisterUser", mock.Anything, mock.Anything).Return(mockResponse, nil)

// Переопределяем конвертацию ответа, чтобы она возвращала ошибку
utils.ConvertAuthResponseProtoToGo = func(protoResponse *gen.RegisterUserResponse, sessionID string) (interface{}, error) {

Check failure on line 180 in internal/auth/controller/auth_controller_test.go

View workflow job for this annotation

GitHub Actions / Lint

undefined: utils.ConvertAuthResponseProtoToGo

Check failure on line 180 in internal/auth/controller/auth_controller_test.go

View workflow job for this annotation

GitHub Actions / Lint

undefined: gen.RegisterUserResponse (typecheck)

Check failure on line 180 in internal/auth/controller/auth_controller_test.go

View workflow job for this annotation

GitHub Actions / build-test-and-push

undefined: utils.ConvertAuthResponseProtoToGo

Check failure on line 180 in internal/auth/controller/auth_controller_test.go

View workflow job for this annotation

GitHub Actions / build-test-and-push

undefined: gen.RegisterUserResponse
return nil, errors.New("conversion error")
}

authHandler := AuthHandler{
client: mockGrpcClient,
}

user := domain.User{
Username: "testuser",
Email: "[email protected]",
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)
}
20 changes: 7 additions & 13 deletions microservices/ads_service/mocks/mocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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) {
Expand All @@ -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
Expand All @@ -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) {
Expand Down Expand Up @@ -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 {
Expand Down
Loading

0 comments on commit f68dbe9

Please sign in to comment.