Skip to content

Commit 514f231

Browse files
authored
updated test, logic changes (#54)
* updated test, logic changes * meh
1 parent 0458995 commit 514f231

File tree

8 files changed

+199
-68
lines changed

8 files changed

+199
-68
lines changed

MyMusicBoxApi/database/db.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package database
22

33
import (
4+
"context"
45
"database/sql"
56
"errors"
67
"fmt"
@@ -36,6 +37,7 @@ func NewBaseTableInstance() BaseTable {
3637
}
3738
}
3839

40+
// Base
3941
func CreateDatabasConnectionPool() error {
4042

4143
// Will throw an error if its missing a method implementation from interface
@@ -149,6 +151,18 @@ func (base *BaseTable) NonScalarQuery(query string, params ...any) (error error)
149151
return nil
150152
}
151153

154+
func (base *BaseTable) QueryRow(query string) *sql.Row {
155+
return base.DB.QueryRow(query)
156+
}
157+
158+
func (base *BaseTable) QueryRowsContex(ctx context.Context, query string, params ...any) (*sql.Rows, error) {
159+
return base.DB.QueryContext(ctx, query, params...)
160+
}
161+
162+
func (base *BaseTable) QueryRows(query string) (*sql.Rows, error) {
163+
return base.DB.QueryContext(context.Background(), query)
164+
}
165+
152166
func ApplyMigrations() {
153167
logging.Info("Applying migrations...")
154168
// files will be sorted by filename

MyMusicBoxApi/database/db_test.go

Lines changed: 149 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,16 @@ package database
22

33
import (
44
"database/sql"
5+
"fmt"
56
"musicboxapi/logging"
67
"regexp"
78
"testing"
89

910
"github.com/DATA-DOG/go-sqlmock"
1011
_ "github.com/lib/pq"
12+
"github.com/stretchr/testify/assert"
1113
)
1214

13-
var Mock sqlmock.Sqlmock
14-
1515
func CreateMockDb() (*sql.DB, sqlmock.Sqlmock, error) {
1616
db, mock, err := sqlmock.New()
1717

@@ -119,3 +119,150 @@ func TestNonScalarQueryShouldThrowErrt(t *testing.T) {
119119
t.Errorf("NonScalarQuery failed: %s", result)
120120
}
121121
}
122+
123+
func TestQueryRow(t *testing.T) {
124+
// Arrange
125+
query := "SELECT Id, Name, Online FROM data"
126+
db, mock, err := CreateMockDb()
127+
128+
if err != nil {
129+
logging.ErrorStackTrace(err)
130+
return
131+
}
132+
133+
base := NewBaseTableInstance()
134+
base.DB = db
135+
136+
mock.ExpectQuery(query).
137+
WillReturnRows(sqlmock.NewRows([]string{"Id", "Name", "Online"}).AddRow(1, "Test", false))
138+
139+
// Act
140+
rows := base.QueryRow(query)
141+
142+
// Assert
143+
err = mock.ExpectationsWereMet()
144+
145+
if err != nil {
146+
t.Errorf("Expectations failed: %s", err)
147+
}
148+
149+
var id int
150+
var name string
151+
var online bool
152+
153+
rows.Scan(&id, &name, &online)
154+
155+
assert.Equal(t, 1, id)
156+
assert.Equal(t, "Test", name)
157+
assert.Equal(t, false, online)
158+
}
159+
160+
func TestQueryRows(t *testing.T) {
161+
// Arrange
162+
query := "SELECT Id, Name, Online FROM data"
163+
db, mock, err := CreateMockDb()
164+
165+
if err != nil {
166+
logging.ErrorStackTrace(err)
167+
return
168+
}
169+
170+
base := NewBaseTableInstance()
171+
base.DB = db
172+
173+
mock.ExpectQuery(query).
174+
WillReturnRows(sqlmock.NewRows([]string{"Id", "Name", "Online"}).AddRow(1, "Test", false).AddRow(2, "Test2", true))
175+
176+
// Act
177+
rows, err := base.QueryRows(query)
178+
179+
assert.Nil(t, err)
180+
181+
defer rows.Close()
182+
183+
// Assert
184+
err = mock.ExpectationsWereMet()
185+
186+
if err != nil {
187+
t.Errorf("Expectations failed: %s", err)
188+
}
189+
190+
type Data struct {
191+
id int
192+
name string
193+
online bool
194+
}
195+
196+
var datas []Data
197+
var data Data
198+
199+
datas = make([]Data, 0)
200+
201+
for rows.Next() {
202+
scanError := rows.Scan(&data.id, &data.name, &data.online)
203+
204+
if scanError != nil {
205+
logging.Error(fmt.Sprintf("Scan error: %s", scanError.Error()))
206+
continue
207+
}
208+
209+
datas = append(datas, data)
210+
}
211+
212+
assert.Equal(t, 2, len(datas))
213+
}
214+
215+
func TestQueryRowsContext(t *testing.T) {
216+
// Arrange
217+
query := "SELECT Id, Name, Online FROM data"
218+
db, mock, err := CreateMockDb()
219+
220+
if err != nil {
221+
logging.ErrorStackTrace(err)
222+
return
223+
}
224+
225+
base := NewBaseTableInstance()
226+
base.DB = db
227+
228+
mock.ExpectQuery(query).
229+
WillReturnRows(sqlmock.NewRows([]string{"Id", "Name", "Online"}).AddRow(1, "Test", false).AddRow(2, "Test2", true))
230+
231+
// Act
232+
rows, err := base.QueryRowsContex(t.Context(), query)
233+
234+
assert.Nil(t, err)
235+
236+
defer rows.Close()
237+
238+
// Assert
239+
err = mock.ExpectationsWereMet()
240+
241+
if err != nil {
242+
t.Errorf("Expectations failed: %s", err)
243+
}
244+
245+
type Data struct {
246+
id int
247+
name string
248+
online bool
249+
}
250+
251+
var datas []Data
252+
var data Data
253+
254+
datas = make([]Data, 0)
255+
256+
for rows.Next() {
257+
scanError := rows.Scan(&data.id, &data.name, &data.online)
258+
259+
if scanError != nil {
260+
logging.Error(fmt.Sprintf("Scan error: %s", scanError.Error()))
261+
continue
262+
}
263+
264+
datas = append(datas, data)
265+
}
266+
267+
assert.Equal(t, 2, len(datas))
268+
}

MyMusicBoxApi/database/migrationtable.go

Lines changed: 6 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -21,44 +21,20 @@ func NewMigrationTableInstance() *MigrationTable {
2121
}
2222
}
2323

24-
func (mt *MigrationTable) Insert(filename string, contents string) (err error) {
25-
err = mt.NonScalarQuery("INSERT INTO Migration (filename, contents) VALUES($1, $2)", filename, contents)
24+
func (table *MigrationTable) Insert(filename string, contents string) (err error) {
25+
err = table.NonScalarQuery("INSERT INTO Migration (filename, contents) VALUES($1, $2)", filename, contents)
2626
if err != nil {
2727
logging.Error(fmt.Sprintf("Failed to insert new migration: %s", err.Error()))
2828
}
2929
return err
3030
}
3131

32-
func (mt *MigrationTable) ApplyMigration(query string) (err error) {
33-
transaction, err := mt.DB.Begin()
34-
35-
if err != nil {
36-
logging.Error(fmt.Sprintf("Failed to begin transaction: %s", err.Error()))
37-
logging.ErrorStackTrace(err)
38-
return err
39-
}
40-
41-
_, err = transaction.Exec(query)
42-
43-
if err != nil {
44-
logging.Error(fmt.Sprintf("Failed to execute migration, rolling back: %s", err.Error()))
45-
logging.ErrorStackTrace(err)
46-
return err
47-
}
48-
49-
err = transaction.Commit()
50-
51-
if err != nil {
52-
logging.Error(fmt.Sprintf("Failed to commit migration, rolling back: %s", err.Error()))
53-
logging.ErrorStackTrace(err)
54-
return err
55-
}
56-
57-
return err
32+
func (table *MigrationTable) ApplyMigration(query string) (err error) {
33+
return table.NonScalarQuery(query)
5834
}
5935

60-
func (mt *MigrationTable) GetCurrentAppliedMigrationFileName() (fileName string, err error) {
61-
row := mt.DB.QueryRow("SELECT filename FROM migration order by AppliedOn DESC LIMIT 1")
36+
func (table *MigrationTable) GetCurrentAppliedMigrationFileName() (fileName string, err error) {
37+
row := table.QueryRow("SELECT filename FROM migration order by AppliedOn DESC LIMIT 1")
6238
scanError := row.Scan(&fileName)
6339
return fileName, scanError
6440
}

MyMusicBoxApi/database/migrationtable_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ func TestApplyMigration(t *testing.T) {
6464
query := "DROP DATABSE migration"
6565

6666
mock.ExpectBegin()
67+
mock.ExpectPrepare(query)
6768
mock.ExpectExec(query).
6869
WillReturnResult(sqlmock.NewResult(1, 1))
6970
mock.ExpectCommit()

MyMusicBoxApi/database/playlistsongtable.go

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -24,20 +24,12 @@ func NewPlaylistsongTableInstance() IPlaylistsongTable {
2424
}
2525
}
2626

27-
func (pt *PlaylistsongTable) FetchPlaylistSongs(ctx context.Context, playlistId int, lastKnowPosition int) (songs []models.Song, error error) {
27+
func (table *PlaylistsongTable) FetchPlaylistSongs(ctx context.Context, playlistId int, lastKnowPosition int) (songs []models.Song, error error) {
2828
query := `SELECT s.Id, s.Name, s.Path, s.ThumbnailPath, s.Duration, s.SourceId, s.UpdatedAt, s.CreatedAt FROM playlistsong ps
2929
INNER JOIN song s ON s.id = ps.songid
3030
WHERE ps.playlistid = $1 AND ps.position >= $2`
3131

32-
statement, err := pt.DB.Prepare(query)
33-
34-
if err != nil {
35-
logging.Error(fmt.Sprintf("Prepared statement error: %s", err.Error()))
36-
return nil, err
37-
}
38-
defer statement.Close()
39-
40-
rows, err := statement.QueryContext(ctx, playlistId, lastKnowPosition)
32+
rows, err := table.QueryRowsContex(ctx, query, playlistId, lastKnowPosition)
4133

4234
if err != nil {
4335
logging.Error(fmt.Sprintf("QueryRow error: %s", err.Error()))
@@ -63,29 +55,29 @@ func (pt *PlaylistsongTable) FetchPlaylistSongs(ctx context.Context, playlistId
6355
return songs, nil
6456
}
6557

66-
func (pt *PlaylistsongTable) InsertPlaylistSong(playlistId int, songId int) (lastInsertedId int, error error) {
58+
func (table *PlaylistsongTable) InsertPlaylistSong(playlistId int, songId int) (lastInsertedId int, error error) {
6759
query := `INSERT INTO PlaylistSong (SongId, PlaylistId) VALUES($1, $2) RETURNING SongId`
6860

69-
lastInsertedId, err := pt.InsertWithReturningId(query,
61+
lastInsertedId, err := table.InsertWithReturningId(query,
7062
songId,
7163
playlistId,
7264
)
7365

7466
return lastInsertedId, err
7567
}
7668

77-
func (pt *PlaylistsongTable) DeleteAllPlaylistSongs(playlistId int) (error error) {
69+
func (table *PlaylistsongTable) DeleteAllPlaylistSongs(playlistId int) (error error) {
7870
query := `DELETE FROM PlaylistSong WHERE PlaylistId = $1`
7971

80-
err := pt.NonScalarQuery(query, playlistId)
72+
err := table.NonScalarQuery(query, playlistId)
8173

8274
return err
8375
}
8476

85-
func (pt *PlaylistsongTable) DeletePlaylistSong(playlistId int, songId int) (error error) {
77+
func (table *PlaylistsongTable) DeletePlaylistSong(playlistId int, songId int) (error error) {
8678
query := `DELETE FROM PlaylistSong WHERE PlaylistId = $1 and SongId = $2`
8779

88-
err := pt.NonScalarQuery(query, playlistId, songId)
80+
err := table.NonScalarQuery(query, playlistId, songId)
8981

9082
return err
9183
}

MyMusicBoxApi/database/playlisttable.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,14 @@ func NewPlaylistTableInstance() IPlaylistTable {
2323
}
2424
}
2525

26-
func (pt *PlaylistTable) FetchPlaylists(ctx context.Context, lastKnowPlaylistId int) (playlists []models.Playlist, error error) {
26+
func (table *PlaylistTable) FetchPlaylists(ctx context.Context, lastKnowPlaylistId int) (playlists []models.Playlist, error error) {
2727
query := "SELECT Id, Name, ThumbnailPath, Description, CreationDate FROM Playlist WHERE Id > $1 ORDER BY Id" // order by?
2828

29-
rows, err := pt.DB.QueryContext(ctx, query, lastKnowPlaylistId)
29+
rows, err := table.QueryRowsContex(ctx, query, lastKnowPlaylistId)
3030

3131
if err != nil {
3232
logging.Error(fmt.Sprintf("QueryRow error: %s", err.Error()))
33+
logging.ErrorStackTrace(err)
3334
return nil, err
3435
}
3536

@@ -53,10 +54,10 @@ func (pt *PlaylistTable) FetchPlaylists(ctx context.Context, lastKnowPlaylistId
5354
return playlists, nil
5455
}
5556

56-
func (pt *PlaylistTable) InsertPlaylist(playlist models.Playlist) (lastInsertedId int, error error) {
57+
func (table *PlaylistTable) InsertPlaylist(playlist models.Playlist) (lastInsertedId int, error error) {
5758
query := `INSERT INTO Playlist (name, description, thumbnailPath) VALUES ($1, $2, $3) RETURNING Id`
5859

59-
lastInsertedId, err := pt.InsertWithReturningId(query,
60+
lastInsertedId, err := table.InsertWithReturningId(query,
6061
playlist.Name,
6162
playlist.Description,
6263
playlist.ThumbnailPath,
@@ -65,10 +66,10 @@ func (pt *PlaylistTable) InsertPlaylist(playlist models.Playlist) (lastInsertedI
6566
return lastInsertedId, err
6667
}
6768

68-
func (pt *PlaylistTable) DeletePlaylist(playlistId int) (error error) {
69+
func (table *PlaylistTable) DeletePlaylist(playlistId int) (error error) {
6970
query := `DELETE FROM Playlist WHERE Id = $1`
7071

71-
err := pt.NonScalarQuery(query, playlistId)
72+
err := table.NonScalarQuery(query, playlistId)
7273

7374
if err != nil {
7475
logging.Error(fmt.Sprintf("Failed to delete playlist: %s", err.Error()))

MyMusicBoxApi/database/songtable.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,11 @@ func NewSongTableInstance() ISongTable {
2222
}
2323
}
2424

25-
func (st *SongTable) InsertSong(song *models.Song) (error error) {
25+
func (table *SongTable) InsertSong(song *models.Song) (error error) {
2626

2727
query := `INSERT INTO Song (name, sourceid, path, thumbnailPath, duration) VALUES ($1, $2, $3, $4, $5) RETURNING Id`
2828

29-
lastInsertedId, err := st.InsertWithReturningId(query,
29+
lastInsertedId, err := table.InsertWithReturningId(query,
3030
song.Name,
3131
song.SourceId,
3232
song.Path,
@@ -47,11 +47,11 @@ func (st *SongTable) InsertSong(song *models.Song) (error error) {
4747
return err
4848
}
4949

50-
func (st *SongTable) FetchSongs(ctx context.Context) (songs []models.Song, error error) {
50+
func (table *SongTable) FetchSongs(ctx context.Context) (songs []models.Song, error error) {
5151

5252
query := "SELECT Id, Name, Path, ThumbnailPath, Duration, SourceId, UpdatedAt, CreatedAt FROM Song" // order by?
5353

54-
rows, err := st.DB.QueryContext(ctx, query)
54+
rows, err := table.QueryRowsContex(ctx, query)
5555

5656
if err != nil {
5757
logging.Error(fmt.Sprintf("QueryRow error: %s", err.Error()))

0 commit comments

Comments
 (0)