Skip to content

Commit

Permalink
test additin to new funcs
Browse files Browse the repository at this point in the history
  • Loading branch information
CodeMaster482 committed Dec 20, 2023
1 parent 1675991 commit 1bb4595
Show file tree
Hide file tree
Showing 2 changed files with 239 additions and 0 deletions.
126 changes: 126 additions & 0 deletions internal/microservices/auth/repository/postgresql/postgres_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,129 @@ func TestCreateUser(t *testing.T) {
})
}
}

func TestGetByID(t *testing.T) {
staticUUID := uuid.New()
tests := []struct {
name string
userID uuid.UUID
rows *pgxmock.Rows
expected *models.User
expectedErr error
err error
}{
{
name: "ValidUser",
userID: staticUUID,
rows: pgxmock.NewRows([]string{
"id", "login", "username", "password", "planned_budget", "avatar_url",
}).AddRow(
staticUUID, "testuser", "Test User", "password", 1000.0, staticUUID,
),
expected: &models.User{
ID: staticUUID,
Login: "testuser",
Username: "Test User",
Password: "password",
PlannedBudget: 1000.0,
AvatarURL: staticUUID,
},
expectedErr: nil,
err: nil,
},
{
name: "NoSuchUser",
userID: staticUUID,
rows: pgxmock.NewRows([]string{}).RowError(0, sql.ErrNoRows),
expected: nil,
expectedErr: fmt.Errorf("[repo] %w: %v", &models.NoSuchUserError{UserID: staticUUID}, sql.ErrNoRows),
err: sql.ErrNoRows,
},

{
name: "DatabaseError",
userID: uuid.New(),
rows: pgxmock.NewRows([]string{}).RowError(0, errors.New("database error")),
expected: nil,
expectedErr: fmt.Errorf("failed request db %s, %w", UserIDGetByID, errors.New("database error")),
err: errors.New("database error"),
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
mock, _ := pgxmock.NewPool()
ctl := gomock.NewController(t)
defer ctl.Finish()

logger := *logger.NewLogger(context.TODO())
repo := NewRepository(mock, logger)

escapedQuery := regexp.QuoteMeta(UserIDGetByID)

mock.ExpectQuery(escapedQuery).
WithArgs(staticUUID).
WillReturnRows(test.rows).
WillReturnError(test.err)

user, err := repo.GetByID(context.Background(), staticUUID)

assert.Equal(t, test.expected, user)
if !reflect.DeepEqual(test.expectedErr, err) {
t.Errorf("Expected error: %v, but got: %v", test.expectedErr, err)
}
})
}
}

func TestChangePassword(t *testing.T) {
staticUUID := uuid.New()
newPassword := "newpassword"

tests := []struct {
name string
userID uuid.UUID
newPassword string
execError error
expectedErr error
}{
{
name: "Success",
userID: staticUUID,
newPassword: newPassword,
execError: nil,
expectedErr: nil,
},
{
name: "DatabaseError",
userID: staticUUID,
newPassword: newPassword,
execError: errors.New("database error"),
expectedErr: fmt.Errorf("[repo] failed to update password: %w", errors.New("database error")),
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
mock, _ := pgxmock.NewPool()
ctl := gomock.NewController(t)
defer ctl.Finish()

logger := *logger.NewLogger(context.TODO())
repo := NewRepository(mock, logger)

escapedQuery := regexp.QuoteMeta(UserChangePassword)

mock.ExpectExec(escapedQuery).
WithArgs(newPassword, test.userID).
WillReturnResult(pgxmock.NewResult("0", 1)).
WillReturnError(test.execError)

err := repo.ChangePassword(context.Background(), test.userID, test.newPassword)

if !reflect.DeepEqual(test.expectedErr, err) {
t.Errorf("Expected error: %v, but got: %v", test.expectedErr, err)
}
})
}
}
113 changes: 113 additions & 0 deletions internal/microservices/auth/usecase/auth_usecase_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,116 @@ func TestUsecase_CheckLoginUnique(t *testing.T) {
})
}
}

func TestUsecase_GetByID(t *testing.T) {
userIdTest := uuid.New()
testCases := []struct {
name string
inputUserID uuid.UUID
expectedUser *models.User
expectedErr error
mockRepoFn func(*mock.MockRepository)
}{
{
name: "Successful GetByID",
inputUserID: userIdTest,
expectedUser: &models.User{
ID: userIdTest,
// Add other expected user fields here
},
expectedErr: nil,
mockRepoFn: func(mockRepository *mock.MockRepository) {
mockRepository.EXPECT().GetByID(gomock.Any(), userIdTest).Return(&models.User{
ID: userIdTest,
// Add other mocked user fields here
}, nil)
},
},
{
name: "Error in GetByID",
inputUserID: userIdTest,
expectedUser: nil,
expectedErr: fmt.Errorf("[usecase] can't get user from repository some error"),
mockRepoFn: func(mockRepository *mock.MockRepository) {
mockRepository.EXPECT().GetByID(gomock.Any(), userIdTest).Return(nil, errors.New("some error"))
},
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()

mockRepo := mock.NewMockRepository(ctrl)
tc.mockRepoFn(mockRepo)

mockUsecase := NewUsecase(mockRepo, *logger.NewLogger(context.TODO()))

user, err := mockUsecase.GetByID(context.Background(), tc.inputUserID)

assert.Equal(t, tc.expectedUser, user)
if (tc.expectedErr == nil && err != nil) || (tc.expectedErr != nil && err == nil) || (tc.expectedErr != nil && err != nil && tc.expectedErr.Error() != err.Error()) {
t.Errorf("Expected error: %v, but got: %v", tc.expectedErr, err)
}
})
}
}

func TestUsecase_ChangePassword(t *testing.T) {
userIdTest := uuid.New()
testCases := []struct {
name string
input auth.ChangePasswordInput
expectedErr error
mockRepoFn func(*mock.MockRepository)
}{
{
name: "Successful ChangePassword",
input: auth.ChangePasswordInput{
Login: "testLogin",
OldPassword: "testPassword",
NewPassword: "newPassword",
},
expectedErr: nil,
mockRepoFn: func(mockRepository *mock.MockRepository) {
mockRepository.EXPECT().GetUserByLogin(gomock.Any(), "testLogin").Return(&models.User{
ID: userIdTest,
Password: "$argon2id$v=19$m=65536,t=1,p=4$YcsUni+F/VK3Vsjuw7Hb/Q$eZwr1GdO2/bkDRa2PGfTw5l6LPymywRdE9St5ot2Gv8", // Replace with actual hashed password
}, nil)
mockRepository.EXPECT().ChangePassword(gomock.Any(), userIdTest, gomock.Any()).Return(nil)
},
},
{
name: "Error in GetUserByLogin",
input: auth.ChangePasswordInput{
Login: "testLogin",
OldPassword: "oldPassword",
NewPassword: "newPassword",
},
expectedErr: fmt.Errorf("[usecase] can't find user: some error"),
mockRepoFn: func(mockRepository *mock.MockRepository) {
mockRepository.EXPECT().GetUserByLogin(gomock.Any(), "testLogin").Return(nil, errors.New("some error"))
},
},
// Add more test cases for different scenarios (e.g., incorrect old password, hasher errors, repo errors)
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()

mockRepo := mock.NewMockRepository(ctrl)
tc.mockRepoFn(mockRepo)

mockUsecase := NewUsecase(mockRepo, *logger.NewLogger(context.TODO()))

err := mockUsecase.ChangePassword(context.Background(), tc.input)

if (tc.expectedErr == nil && err != nil) || (tc.expectedErr != nil && err == nil) || (tc.expectedErr != nil && err != nil && tc.expectedErr.Error() != err.Error()) {
t.Errorf("Expected error: %v, but got: %v", tc.expectedErr, err)
}
})
}
}

0 comments on commit 1bb4595

Please sign in to comment.