Skip to content

Commit

Permalink
event 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 2547ab7 commit 10ff0b3
Show file tree
Hide file tree
Showing 4 changed files with 362 additions and 0 deletions.
88 changes: 88 additions & 0 deletions internal/event/repository/add_to_favorites_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package eventRepository

import (
"context"
"github.com/jackc/pgx/v5/pgconn"
"kudago/internal/models"
"testing"

"github.com/pashagolub/pgxmock/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

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

ctx := context.Background()

tests := []struct {
name string
newFavorite models.FavoriteEvent
mockSetup func(m pgxmock.PgxConnIface)
expectedError error
}{
{
name: "Успешное добавление",
newFavorite: models.FavoriteEvent{
UserID: 1,
EventID: 100,
},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectExec(`INSERT INTO FAVORITE_EVENT \(user_id, event_id\) VALUES \(\$1, \$2\) ON CONFLICT DO NOTHING`).
WithArgs(1, 100).
WillReturnResult(pgxmock.NewResult("INSERT", 1))
},
expectedError: nil,
},
{
name: "Конфликт записи (ничего не вставлено)",
newFavorite: models.FavoriteEvent{
UserID: 2,
EventID: 200,
},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectExec(`INSERT INTO FAVORITE_EVENT \(user_id, event_id\) VALUES \(\$1, \$2\) ON CONFLICT DO NOTHING`).
WithArgs(2, 200).
WillReturnResult(pgxmock.NewResult("INSERT", 0))
},
expectedError: models.ErrNothingToInsert,
},
{
name: "Ошибка внешнего ключа",
newFavorite: models.FavoriteEvent{
UserID: 3,
EventID: 300,
},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectExec(`INSERT INTO FAVORITE_EVENT \(user_id, event_id\) VALUES \(\$1, \$2\) ON CONFLICT DO NOTHING`).
WithArgs(3, 300).
WillReturnError(&pgconn.PgError{Code: "23503"}) // Код ошибки внешнего ключа
},
expectedError: models.ErrForeignKeyViolation,
},
}

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 := EventDB{pool: mockConn}

err = db.AddEventToFavorites(ctx, tt.newFavorite)

if tt.expectedError != nil {
assert.Error(t, err)
assert.Contains(t, err.Error(), tt.expectedError.Error())
} else {
assert.NoError(t, err)
}
})
}
}
107 changes: 107 additions & 0 deletions internal/event/repository/create_event_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package eventRepository

import (
"context"
"fmt"
"github.com/pashagolub/pgxmock/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"testing"

"kudago/internal/models"
)

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

ctx := context.Background()

tests := []struct {
name string
event models.Event
mockSetup func(m pgxmock.PgxConnIface)
expectErr bool
}{
{
name: "ошибочное создание",
event: models.Event{
Title: "Test Event",
Description: "A test event",
EventStart: "2024-01-01T10:00:00Z",
EventEnd: "2024-01-01T12:00:00Z",
Location: "Test Location",
Capacity: 100,
AuthorID: 1,
CategoryID: 2,
Latitude: 10.0,
Longitude: 20.0,
Tag: []string{"tag1", "tag2"},
ImageURL: "http://example.com/image.jpg",
},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectBegin()
m.ExpectQuery(createEventQuery).
WithArgs("Test Event", "A test event", "2024-01-01T10:00:00Z", "2024-01-01T12:00:00Z", "Test Location", 100, 1, 2, 10.0, 20.0).
WillReturnRows(pgxmock.NewRows([]string{"id"}).AddRow(1))
m.ExpectExec("INSERT INTO event_tag").
WithArgs(1, "tag1").
WillReturnResult(pgxmock.NewResult("INSERT", 1))
m.ExpectExec("INSERT INTO event_tag").
WithArgs(1, "tag2").
WillReturnResult(pgxmock.NewResult("INSERT", 1))
m.ExpectExec("INSERT INTO event_media").
WithArgs(1, "http://example.com/image.jpg").
WillReturnResult(pgxmock.NewResult("INSERT", 1))
m.ExpectCommit()
},
expectErr: true,
},
{
name: "Ошибка при выполнении запроса",
event: models.Event{
Title: "Test Event",
Description: "A test event",
EventStart: "2024-01-01T10:00:00Z",
EventEnd: "2024-01-01T12:00:00Z",
Location: "Test Location",
Capacity: 100,
AuthorID: 1,
CategoryID: 2,
Latitude: 10.0,
Longitude: 20.0,
},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectBegin()
m.ExpectQuery(createEventQuery).
WithArgs("Test Event", "A test event", "2024-01-01T10:00:00Z", "2024-01-01T12:00:00Z", "Test Location", 100, 1, 2, 10.0, 20.0).
WillReturnError(fmt.Errorf("database error"))
m.ExpectRollback()
},
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 := NewDB(mockConn)

createdEvent, err := db.CreateEvent(context.Background(), tt.event)

if tt.expectErr {
assert.Error(t, err)
assert.Contains(t, err.Error(), models.LevelDB)
} else {
assert.NoError(t, err)
assert.NotZero(t, createdEvent.ID)
}
})
}
}
89 changes: 89 additions & 0 deletions internal/event/repository/delete_event_from_favorites_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package eventRepository

import (
"context"
"fmt"
"testing"

"github.com/pashagolub/pgxmock/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"kudago/internal/models"
)

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

ctx := context.Background()

tests := []struct {
name string
favorite models.FavoriteEvent
mockSetup func(m pgxmock.PgxConnIface)
expectErr error
}{
{
name: "Успешное удаление из избранного",
favorite: models.FavoriteEvent{
UserID: 1,
EventID: 2,
},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectExec(`DELETE FROM FAVORITE_EVENT WHERE user_id=\$1 AND event_id=\$2`).
WithArgs(1, 2).
WillReturnResult(pgxmock.NewResult("DELETE", 1))
},
expectErr: nil,
},
{
name: "Событие не найдено в избранном",
favorite: models.FavoriteEvent{
UserID: 1,
EventID: 3,
},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectExec(`DELETE FROM FAVORITE_EVENT WHERE user_id=\$1 AND event_id=\$2`).
WithArgs(1, 3).
WillReturnResult(pgxmock.NewResult("DELETE", 0))
},
expectErr: models.ErrNotFound,
},
{
name: "Ошибка базы данных",
favorite: models.FavoriteEvent{
UserID: 1,
EventID: 4,
},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectExec(`DELETE FROM FAVORITE_EVENT WHERE user_id=\$1 AND event_id=\$2`).
WithArgs(1, 4).
WillReturnError(fmt.Errorf("database error"))
},
expectErr: fmt.Errorf("%s: database error", models.LevelDB),
},
}

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 := NewDB(mockConn)

err = db.DeleteEventFromFavorites(ctx, tt.favorite)

if tt.expectErr != nil {
assert.Error(t, err)
assert.Equal(t, tt.expectErr.Error(), err.Error())
} else {
assert.NoError(t, err)
}
})
}
}
78 changes: 78 additions & 0 deletions internal/event/repository/get_events_by_ids_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package eventRepository

import (
"context"
"testing"

"github.com/pashagolub/pgxmock/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

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

ctx := context.Background()

tests := []struct {
name string
IDs []int
mockSetup func(m pgxmock.PgxConnIface)
expectErr error
}{
{
name: "Успешное получение событий по ID",
IDs: []int{1, 2},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectQuery(`SELECT event.id, event.title, event.description, event.event_start, event.event_finish,
event.location, event.capacity, event.created_at, event.user_id, event.category_id, event.lat, event.lon,
COALESCE\(array_agg\(COALESCE\(tag.name, ''\), \{\}\)\) AS tags, media_url.url AS media_link`).
WithArgs([]int{1, 2}).
WillReturnRows(pgxmock.NewRows([]string{
"id", "title", "description", "event_start", "event_finish", "location", "capacity",
"created_at", "user_id", "category_id", "lat", "lon", "tags", "media_link",
}).
AddRow(1, "Event 1", "Description 1", "2024-01-01", "2024-01-02", "Location 1", 100,
"2024-01-01", 1, 1, 55.7558, 37.6173, "{tag1, tag2}", "url1").
AddRow(2, "Event 2", "Description 2", "2024-02-01", "2024-02-02", "Location 2", 200,
"2024-02-01", 2, 2, 40.7128, -74.0060, "{tag3, tag4}", "url2"))
},
expectErr: nil,
},
{
name: "События не найдены",
IDs: []int{999},
mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectQuery(`SELECT event.id, event.title, event.description, event.event_start, event.event_finish,
event.location, event.capacity, event.created_at, event.user_id, event.category_id, event.lat, event.lon,
COALESCE\(array_agg\(COALESCE\(tag.name, ''\), \{\}\)\) AS tags, media_url.url AS media_link`).
WithArgs([]int{999}).
WillReturnRows(pgxmock.NewRows([]string{
"id", "title", "description", "event_start", "event_finish", "location", "capacity",
"created_at", "user_id", "category_id", "lat", "lon", "tags", "media_link",
}))
},
expectErr: nil,
},
}

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)

if tt.expectErr != nil {
assert.Error(t, err)
assert.Equal(t, tt.expectErr.Error(), err.Error())
} else {
assert.NoError(t, err)
}

})
}
}

0 comments on commit 10ff0b3

Please sign in to comment.