Skip to content

Commit

Permalink
auth repo test
Browse files Browse the repository at this point in the history
  • Loading branch information
source-Alexander-Rudenko committed Dec 18, 2024
1 parent bf6e3f6 commit b2d8f28
Show file tree
Hide file tree
Showing 10 changed files with 479 additions and 14 deletions.
4 changes: 2 additions & 2 deletions internal/auth/repository/auth/check_credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const checkCredentialsQuery = `

func (d UserDB) CheckCredentials(ctx context.Context, username, password string) (models.User, error) {
var userInfo UserInfo
err := d.pool.QueryRow(ctx, checkCredentialsQuery, username, password).Scan(
err := d.Pool.QueryRow(ctx, checkCredentialsQuery, username, password).Scan(
&userInfo.ID,
&userInfo.Username,
&userInfo.Email,
Expand All @@ -30,6 +30,6 @@ func (d UserDB) CheckCredentials(ctx context.Context, username, password string)
}
return models.User{}, fmt.Errorf("%s: %w", models.LevelDB, err)
}
user := toDomainUser(userInfo)
user := ToDomainUser(userInfo)
return user, nil
}
4 changes: 2 additions & 2 deletions internal/auth/repository/auth/create_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const createUserQuery = `

func (d *UserDB) CreateUser(ctx context.Context, user models.User) (models.User, error) {
var userInfo UserInfo
err := d.pool.QueryRow(ctx, createUserQuery,
err := d.Pool.QueryRow(ctx, createUserQuery,
user.Username,
user.Email,
user.Password,
Expand All @@ -31,6 +31,6 @@ func (d *UserDB) CreateUser(ctx context.Context, user models.User) (models.User,
userInfo.Email = user.Email
userInfo.ImageURL = &user.ImageURL

newUser := toDomainUser(userInfo)
newUser := ToDomainUser(userInfo)
return newUser, nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func (d *UserDB) UserExists(ctx context.Context, user models.User) (bool, error)
args = append(args, user.ID)
}

err := d.pool.QueryRow(ctx, query, args...).Scan(&exists)
err := d.Pool.QueryRow(ctx, query, args...).Scan(&exists)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
Expand Down
4 changes: 2 additions & 2 deletions internal/auth/repository/auth/get_user_by_id.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const getUserByIDQuery = `SELECT id, username, email, url_to_avatar FROM "USER"
func (d UserDB) GetUserByID(ctx context.Context, ID int) (models.User, error) {
var userInfo UserInfo

err := d.pool.QueryRow(ctx, getUserByIDQuery, ID).Scan(
err := d.Pool.QueryRow(ctx, getUserByIDQuery, ID).Scan(
&userInfo.ID,
&userInfo.Username,
&userInfo.Email,
Expand All @@ -25,6 +25,6 @@ func (d UserDB) GetUserByID(ctx context.Context, ID int) (models.User, error) {
return models.User{}, fmt.Errorf("%s: %w", models.LevelDB, models.ErrUserNotFound)
}

user := toDomainUser(userInfo)
user := ToDomainUser(userInfo)
return user, err
}
74 changes: 74 additions & 0 deletions internal/auth/repository/auth/tests/check_credentials_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package repository

import (
"context"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/pashagolub/pgxmock/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"kudago/internal/auth/repository/auth"
"testing"

"kudago/internal/models"
)

func TestUserDB_CheckCredentials(t *testing.T) {
t.Parallel()

ctx := context.Background()

tests := []struct {
name string
username string
password string
mockSetup func(m pgxmock.PgxConnIface)
expectedUser models.User
expectErr bool
}{
{
name: "Пользователь не найден",
username: "testuser",
password: "wrongpassword",
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectQuery(`SELECT id, username, email, created_at, url_to_avatar`).
WithArgs("testuser", "wrongpassword").
WillReturnError(pgx.ErrNoRows)
},
expectedUser: models.User{},
expectErr: true,
},
{
name: "Ошибка при выполнении запроса",
username: "testuser",
password: "password123",
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectQuery(`SELECT id, username, email, created_at, url_to_avatar`).
WithArgs("testuser", "password123").
WillReturnError(fmt.Errorf("database error"))
},
expectedUser: models.User{},
expectErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()

mockConn, err := pgxmock.NewConn()
require.NoError(t, err)
defer mockConn.Close(ctx)
tt.mockSetup(mockConn)
db := userRepository.UserDB{Pool: mockConn}
user, err := db.CheckCredentials(ctx, tt.username, tt.password)

if tt.expectErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.expectedUser, user)
}
})
}
}
98 changes: 98 additions & 0 deletions internal/auth/repository/auth/tests/create_user_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package repository

import (
"context"
"fmt"
"github.com/pashagolub/pgxmock/v4"
"kudago/internal/auth/repository/auth"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"kudago/internal/models"
)

func TestUserDB_CreateUser(t *testing.T) {
t.Parallel()

ctx := context.Background()

tests := []struct {
name string
user models.User
mockSetup func(m pgxmock.PgxConnIface)
expectedUser models.User
expectErr bool
}{
{
name: "Успешное создание пользователя",
user: models.User{
Username: "newuser",
Email: "[email protected]",
Password: "password123",
ImageURL: "http://example.com/avatar.jpg",
},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectQuery(`INSERT INTO "USER" \(username, email, password_hash, url_to_avatar\)`).
WithArgs("newuser", "[email protected]", "password123", "http://example.com/avatar.jpg").
WillReturnRows(pgxmock.NewRows([]string{"id", "created_at"}).
AddRow(1, time.Date(2024, time.January, 1, 0, 0, 0, 0, time.UTC)))
},
expectedUser: models.User{
ID: 1,
Username: "newuser",
Email: "[email protected]",
Password: "",
ImageURL: "http://example.com/avatar.jpg",
},
expectErr: false,
},
{
name: "Ошибка при создании пользователя",
user: models.User{
Username: "newuser",
Email: "[email protected]",
Password: "password123",
ImageURL: "http://example.com/avatar.jpg",
},
mockSetup: func(m pgxmock.PgxConnIface) {
// Мокируем ошибку при выполнении запроса
m.ExpectQuery(`INSERT INTO "USER" \(username, email, password_hash, url_to_avatar\)`).
WithArgs("newuser", "[email protected]", "password123", "http://example.com/avatar.jpg").
WillReturnError(fmt.Errorf("database error"))
},
expectedUser: models.User{},
expectErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()

// Создание мокированного соединения
mockConn, err := pgxmock.NewConn()
require.NoError(t, err)
defer mockConn.Close(ctx)

// Настройка моков
tt.mockSetup(mockConn)

// Инициализация репозитория с мокированным соединением
db := userRepository.UserDB{Pool: mockConn}

// Вызов функции
user, err := db.CreateUser(ctx, tt.user)

// Проверка ошибок
if tt.expectErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.expectedUser, user)
}
})
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package repository

import (
"context"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/pashagolub/pgxmock/v4"
"kudago/internal/auth/repository/auth"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"kudago/internal/models"
)

func TestUserDB_UserExists(t *testing.T) {
t.Parallel()

ctx := context.Background()

tests := []struct {
name string
user models.User
mockSetup func(m pgxmock.PgxConnIface)
expected bool
expectErr bool
}{
{
name: "Пользователь существует по username",
user: models.User{
Username: "existinguser",
Email: "[email protected]",
},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectQuery(`SELECT id FROM "USER" WHERE \(username = \$1 OR email = \$2\)`).
WithArgs("existinguser", "[email protected]").
WillReturnRows(pgxmock.NewRows([]string{"id"}).AddRow(1))
},
expected: true,
expectErr: false,
},
{
name: "Пользователь не существует",
user: models.User{
Username: "nonexistinguser",
Email: "[email protected]",
},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectQuery(`SELECT id FROM "USER" WHERE \(username = \$1 OR email = \$2\)`).
WithArgs("nonexistinguser", "[email protected]").
WillReturnError(pgx.ErrNoRows)
},
expected: false,
expectErr: false,
},
{
name: "Ошибка при выполнении запроса",
user: models.User{
Username: "user_with_error",
Email: "[email protected]",
},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectQuery(`SELECT id FROM "USER" WHERE \(username = \$1 OR email = \$2\)`).
WithArgs("user_with_error", "[email protected]").
WillReturnError(fmt.Errorf("database error"))
},
expected: false,
expectErr: true,
},
{
name: "Пользователь существует, но исключаем его по ID",
user: models.User{
ID: 2,
Username: "existinguser",
Email: "[email protected]",
},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectQuery(`SELECT id FROM "USER" WHERE \(username = \$1 OR email = \$2\) AND id != \$3`).
WithArgs("existinguser", "[email protected]", 2).
WillReturnRows(pgxmock.NewRows([]string{"id"}).AddRow(1))
},
expected: true,
expectErr: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()

mockConn, err := pgxmock.NewConn()
require.NoError(t, err)
defer mockConn.Close(ctx)

tt.mockSetup(mockConn)

db := userRepository.UserDB{Pool: mockConn}

exists, err := db.UserExists(ctx, tt.user)

if tt.expectErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.expected, exists)
}
})
}
}
Loading

0 comments on commit b2d8f28

Please sign in to comment.