From 2a36446a9ff1196307f240fa712d80abd19ed93a Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Mon, 13 Sep 2021 22:20:12 +0200 Subject: Rewrote database package tests for consistency --- pkg/database/database_test.go | 31 +++++++------------- pkg/database/error.go | 20 ++++++------- pkg/database/error_test.go | 11 ++++++- pkg/database/sessions_test.go | 28 +++++++----------- pkg/database/stop_test.go | 68 +++++++++++++------------------------------ pkg/database/users_test.go | 25 ++++++---------- 6 files changed, 71 insertions(+), 112 deletions(-) (limited to 'pkg') diff --git a/pkg/database/database_test.go b/pkg/database/database_test.go index aad7953..69f0012 100644 --- a/pkg/database/database_test.go +++ b/pkg/database/database_test.go @@ -3,11 +3,9 @@ package database import ( "database/sql" "os" - "reflect" "testing" "github.com/DATA-DOG/go-sqlmock" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -17,7 +15,7 @@ func TestInitDB(t *testing.T) { name string dbType string dsn string - expectedError interface{} + expectedError error }{ {"Invalid dbType", "non-existant", "test", &InitError{}}, {"Non existant path", "sqlite3", "/non-existant/non-existant", &InitError{}}, @@ -28,7 +26,7 @@ func TestInitDB(t *testing.T) { db, err := InitDB(tc.dbType, tc.dsn) if tc.expectedError != nil { require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) + requireErrorTypeMatch(t, err, tc.expectedError) require.Nil(t, db) } else { require.NoError(t, err) @@ -60,21 +58,18 @@ func TestMigrate(t *testing.T) { } os.Remove("testfile_notFromScratch.db") notFromScratchDB, err := InitDB("sqlite3", "file:testfile_notFromScratch.db?_foreign_keys=on") - if err != nil { - t.Fatalf("Failed to init testfile.db : %+v", err) - } + require.NoError(t, err, "Failed to init testfile.db : %+v", err) defer os.Remove("testfile_notFromScratch.db") migrations = onlyFirstMigration - if err := notFromScratchDB.Migrate(); err != nil { - t.Fatalf("Failed to migrate testfile.db to first schema version : %+v", err) - } + err = notFromScratchDB.Migrate() + require.NoError(t, err, "Failed to migrate testfile.db to first schema version : %+v", err) // Test cases testCases := []struct { name string dsn string migrs []func(tx *sql.Tx) error - expectedError interface{} + expectedError error }{ {"bad migration", "file::memory:?_foreign_keys=on", badMigration, &MigrationError{}}, {"no schema_version migration", "file::memory:?_foreign_keys=on", noSchemaVersionMigration, &MigrationError{}}, @@ -89,7 +84,7 @@ func TestMigrate(t *testing.T) { err = db.Migrate() if tc.expectedError != nil { require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) + requireErrorTypeMatch(t, err, tc.expectedError) } else { require.NoError(t, err) } @@ -105,15 +100,11 @@ func TestMigrateWithSQLMock(t *testing.T) { } // Transaction begin error dbBeginError, _, err := sqlmock.New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } + require.NoError(t, err, "an error '%s' was not expected when opening a stub database connection", err) defer dbBeginError.Close() // Transaction commit error dbCommitError, mockCommitError, err := sqlmock.New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } + require.NoError(t, err, "an error '%s' was not expected when opening a stub database connection", err) defer dbCommitError.Close() mockCommitError.ExpectBegin() mockCommitError.ExpectExec(`DELETE FROM schema_version`).WillReturnResult(sqlmock.NewResult(1, 1)) @@ -122,7 +113,7 @@ func TestMigrateWithSQLMock(t *testing.T) { name string db *DBEnv migrs []func(tx *sql.Tx) error - expectedError interface{} + expectedError error }{ {"begin transaction error", &DBEnv{db: dbBeginError}, fakeMigration, &TransactionError{}}, {"commit transaction error", &DBEnv{db: dbCommitError}, fakeMigration, &TransactionError{}}, @@ -134,7 +125,7 @@ func TestMigrateWithSQLMock(t *testing.T) { migrations = allMigrations if tc.expectedError != nil { require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) + requireErrorTypeMatch(t, err, tc.expectedError) } else { require.NoError(t, err) } diff --git a/pkg/database/error.go b/pkg/database/error.go index 0c19752..bbf4d69 100644 --- a/pkg/database/error.go +++ b/pkg/database/error.go @@ -8,10 +8,10 @@ type InitError struct { err error } -func (e *InitError) Error() string { +func (e InitError) Error() string { return fmt.Sprintf("Failed to open database : %s", e.path) } -func (e *InitError) Unwrap() error { return e.err } +func (e InitError) Unwrap() error { return e.err } func newInitError(path string, err error) error { return &InitError{ @@ -26,10 +26,10 @@ type MigrationError struct { err error } -func (e *MigrationError) Error() string { +func (e MigrationError) Error() string { return fmt.Sprintf("Failed to migrate database to version %d : %s", e.version, e.err) } -func (e *MigrationError) Unwrap() error { return e.err } +func (e MigrationError) Unwrap() error { return e.err } func newMigrationError(version int, err error) error { return &MigrationError{ @@ -43,10 +43,10 @@ type PasswordError struct { err error } -func (e *PasswordError) Error() string { +func (e PasswordError) Error() string { return fmt.Sprintf("Failed to hash password : %+v", e.err) } -func (e *PasswordError) Unwrap() error { return e.err } +func (e PasswordError) Unwrap() error { return e.err } func newPasswordError(err error) error { return &PasswordError{ @@ -60,10 +60,10 @@ type QueryError struct { err error } -func (e *QueryError) Error() string { +func (e QueryError) Error() string { return fmt.Sprintf("Failed to perform query : %s", e.msg) } -func (e *QueryError) Unwrap() error { return e.err } +func (e QueryError) Unwrap() error { return e.err } func newQueryError(msg string, err error) error { return &QueryError{ @@ -78,10 +78,10 @@ type TransactionError struct { err error } -func (e *TransactionError) Error() string { +func (e TransactionError) Error() string { return fmt.Sprintf("Failed to perform query : %s", e.msg) } -func (e *TransactionError) Unwrap() error { return e.err } +func (e TransactionError) Unwrap() error { return e.err } func newTransactionError(msg string, err error) error { return &TransactionError{ diff --git a/pkg/database/error_test.go b/pkg/database/error_test.go index fca19d5..f6f8692 100644 --- a/pkg/database/error_test.go +++ b/pkg/database/error_test.go @@ -1,6 +1,15 @@ package database -import "testing" +import ( + "reflect" + "testing" + + "github.com/stretchr/testify/require" +) + +func requireErrorTypeMatch(t *testing.T, err error, expected error) { + require.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(expected), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(expected)) +} func TestErrorsCoverage(t *testing.T) { initErr := InitError{} diff --git a/pkg/database/sessions_test.go b/pkg/database/sessions_test.go index c7820ee..b6c65e2 100644 --- a/pkg/database/sessions_test.go +++ b/pkg/database/sessions_test.go @@ -1,12 +1,10 @@ package database import ( - "reflect" "testing" "git.adyxax.org/adyxax/trains/pkg/model" "github.com/DATA-DOG/go-sqlmock" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -29,7 +27,7 @@ func TestCreateSession(t *testing.T) { testCases := []struct { name string input *model.User - expectedError interface{} + expectedError error }{ {"Normal user", user1, nil}, {"A normal user can request multiple tokens", user1, nil}, @@ -40,11 +38,11 @@ func TestCreateSession(t *testing.T) { valid, err := db.CreateSession(tc.input) if tc.expectedError != nil { require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) + requireErrorTypeMatch(t, err, tc.expectedError) require.Nil(t, valid) } else { require.NoError(t, err) - assert.NotNil(t, valid) + require.NotNil(t, valid) } }) } @@ -53,15 +51,11 @@ func TestCreateSession(t *testing.T) { func TestCreateSessionWithSQLMock(t *testing.T) { // Transaction begin error dbBeginError, _, err := sqlmock.New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } + require.NoError(t, err, "an error '%s' was not expected when opening a stub database connection", err) defer dbBeginError.Close() // Transaction commit error dbCommitError, mockCommitError, err := sqlmock.New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } + require.NoError(t, err, "an error '%s' was not expected when opening a stub database connection", err) defer dbCommitError.Close() mockCommitError.ExpectBegin() mockCommitError.ExpectExec(`INSERT INTO`).WillReturnResult(sqlmock.NewResult(1, 1)) @@ -69,7 +63,7 @@ func TestCreateSessionWithSQLMock(t *testing.T) { testCases := []struct { name string db *DBEnv - expectedError interface{} + expectedError error }{ {"begin transaction error", &DBEnv{db: dbBeginError}, &TransactionError{}}, {"commit transaction error", &DBEnv{db: dbCommitError}, &TransactionError{}}, @@ -79,7 +73,7 @@ func TestCreateSessionWithSQLMock(t *testing.T) { valid, err := tc.db.CreateSession(&model.User{}) if tc.expectedError != nil { require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) + requireErrorTypeMatch(t, err, tc.expectedError) require.Nil(t, valid) } else { require.NoError(t, err) @@ -126,7 +120,7 @@ func TestResumeSession(t *testing.T) { name string input string expected *model.User - expectedError interface{} + expectedError error }{ {"Normal user resume", *token1, user1, nil}, {"Normal user resume 1bis", *token1bis, user1, nil}, @@ -138,12 +132,12 @@ func TestResumeSession(t *testing.T) { valid, err := db.ResumeSession(tc.input) if tc.expectedError != nil { require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) require.Nil(t, valid) + requireErrorTypeMatch(t, err, tc.expectedError) } else { require.NoError(t, err) - assert.NotNil(t, valid) - assert.Equal(t, valid.Id, tc.expected.Id) + require.NotNil(t, valid) + require.Equal(t, valid.Id, tc.expected.Id) } }) } diff --git a/pkg/database/stop_test.go b/pkg/database/stop_test.go index a670393..1779930 100644 --- a/pkg/database/stop_test.go +++ b/pkg/database/stop_test.go @@ -2,12 +2,10 @@ package database import ( "fmt" - "reflect" "testing" "git.adyxax.org/adyxax/trains/pkg/model" "github.com/DATA-DOG/go-sqlmock" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -22,14 +20,14 @@ func TestCountStops(t *testing.T) { // check sql error i, err := db.CountStops() require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(&QueryError{}), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(&QueryError{})) + requireErrorTypeMatch(t, err, &QueryError{}) // normal check err = db.Migrate() require.NoError(t, err) err = db.ReplaceAndImportStops(stops) i, err = db.CountStops() require.NoError(t, err) - assert.Equal(t, i, len(stops)) + require.Equal(t, i, len(stops)) } func TestGetStop(t *testing.T) { @@ -46,11 +44,11 @@ func TestGetStop(t *testing.T) { // normal check stop, err := db.GetStop("id1") require.NoError(t, err) - assert.Equal(t, stop, &stops[0]) + require.Equal(t, stop, &stops[0]) // error check stop, err = db.GetStop("non_existent") require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(&QueryError{}), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(&QueryError{})) + requireErrorTypeMatch(t, err, &QueryError{}) } func TestGetStops(t *testing.T) { @@ -64,42 +62,24 @@ func TestGetStops(t *testing.T) { // error check res, err := db.GetStops() require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(&QueryError{}), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(&QueryError{})) + requireErrorTypeMatch(t, err, &QueryError{}) // normal check err = db.Migrate() require.NoError(t, err) err = db.ReplaceAndImportStops(stops) res, err = db.GetStops() require.NoError(t, err) - assert.Equal(t, res, stops) + require.Equal(t, res, stops) } func TestGetStopsWithSQLMock(t *testing.T) { // Transaction commit error - dbScanError, mockScanError, err := sqlmock.New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } - mockScanError.ExpectQuery(`SELECT id, name FROM stops;`).WillReturnRows(sqlmock.NewRows([]string{"id", "name"}).AddRow(nil, "b").RowError(1, fmt.Errorf("row error"))) - // Test cases - testCases := []struct { - name string - db *DBEnv - expectedError interface{} - }{ - {"query error when scanning row", &DBEnv{db: dbScanError}, &QueryError{}}, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - _, err := tc.db.GetStops() - if tc.expectedError != nil { - require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) - } else { - require.NoError(t, err) - } - }) - } + db, mock, err := sqlmock.New() + require.NoError(t, err, "an error '%s' was not expected when opening a stub database connection", err) + mock.ExpectQuery(`SELECT id, name FROM stops;`).WillReturnRows(sqlmock.NewRows([]string{"id", "name"}).AddRow(nil, "b").RowError(1, fmt.Errorf("row error"))) + _, err = (&DBEnv{db: db}).GetStops() + require.Error(t, err) + requireErrorTypeMatch(t, err, &QueryError{}) } func TestReplaceAndImportStops(t *testing.T) { @@ -121,7 +101,7 @@ func TestReplaceAndImportStops(t *testing.T) { testCases := []struct { name string input []model.Stop - expectedError interface{} + expectedError error }{ {"Normal insert", data1, nil}, {"Normal insert overwrite", data2, nil}, @@ -131,7 +111,7 @@ func TestReplaceAndImportStops(t *testing.T) { err := db.ReplaceAndImportStops(tc.input) if tc.expectedError != nil { require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) + requireErrorTypeMatch(t, err, tc.expectedError) } else { require.NoError(t, err) } @@ -147,30 +127,22 @@ func TestReplaceAndImportStopsWithSQLMock(t *testing.T) { } // Transaction begin error dbBeginError, _, err := sqlmock.New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } + require.NoError(t, err, "an error '%s' was not expected when opening a stub database connection", err) defer dbBeginError.Close() // Query error cannot delete from dbCannotDeleteFrom, mockCannotDeleteFrom, err := sqlmock.New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } + require.NoError(t, err, "an error '%s' was not expected when opening a stub database connection", err) defer dbCannotDeleteFrom.Close() mockCannotDeleteFrom.ExpectBegin() // Transaction commit error dbCannotInsertError, mockCannotInsertError, err := sqlmock.New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } + require.NoError(t, err, "an error '%s' was not expected when opening a stub database connection", err) defer dbCannotInsertError.Close() mockCannotInsertError.ExpectBegin() mockCannotInsertError.ExpectExec(`DELETE FROM`).WillReturnResult(sqlmock.NewResult(1, 1)) // Transaction commit error dbCommitError, mockCommitError, err := sqlmock.New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } + require.NoError(t, err, "an error '%s' was not expected when opening a stub database connection", err) defer dbCommitError.Close() mockCommitError.ExpectBegin() mockCommitError.ExpectExec(`DELETE FROM`).WillReturnResult(sqlmock.NewResult(1, 1)) @@ -180,7 +152,7 @@ func TestReplaceAndImportStopsWithSQLMock(t *testing.T) { testCases := []struct { name string db *DBEnv - expectedError interface{} + expectedError error }{ {"begin transaction error", &DBEnv{db: dbBeginError}, &TransactionError{}}, {"query error cannot delete from", &DBEnv{db: dbCannotDeleteFrom}, &QueryError{}}, @@ -192,7 +164,7 @@ func TestReplaceAndImportStopsWithSQLMock(t *testing.T) { err := tc.db.ReplaceAndImportStops(data1) if tc.expectedError != nil { require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) + requireErrorTypeMatch(t, err, tc.expectedError) } else { require.NoError(t, err) } diff --git a/pkg/database/users_test.go b/pkg/database/users_test.go index b1197db..f34f7be 100644 --- a/pkg/database/users_test.go +++ b/pkg/database/users_test.go @@ -6,7 +6,6 @@ import ( "git.adyxax.org/adyxax/trains/pkg/model" "github.com/DATA-DOG/go-sqlmock" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/crypto/bcrypt" ) @@ -45,11 +44,11 @@ func TestCreateUser(t *testing.T) { valid, err := db.CreateUser(tc.input) if tc.expectedError != nil { require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) + require.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) require.Nil(t, valid) } else { require.NoError(t, err) - assert.Equal(t, tc.expected, valid.Id) + require.Equal(t, tc.expected, valid.Id) } }) } @@ -59,29 +58,23 @@ func TestCreateUser(t *testing.T) { passwordFunction = bcrypt.GenerateFromPassword require.Error(t, err) require.Nil(t, valid) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(&PasswordError{}), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(&PasswordError{})) + require.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(&PasswordError{}), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(&PasswordError{})) } func TestCreateUserWithSQLMock(t *testing.T) { // Transaction begin error dbBeginError, _, err := sqlmock.New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } + require.NoError(t, err, "an error '%s' was not expected when opening a stub database connection", err) defer dbBeginError.Close() // Transaction LastInsertId not supported dbLastInsertIdError, mockLastInsertIdError, err := sqlmock.New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } + require.NoError(t, err, "an error '%s' was not expected when opening a stub database connection", err) defer dbLastInsertIdError.Close() mockLastInsertIdError.ExpectBegin() mockLastInsertIdError.ExpectExec(`INSERT INTO`).WillReturnResult(sqlmock.NewErrorResult(&TransactionError{"test", nil})) // Transaction commit error dbCommitError, mockCommitError, err := sqlmock.New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } + require.NoError(t, err, "an error '%s' was not expected when opening a stub database connection", err) defer dbCommitError.Close() mockCommitError.ExpectBegin() mockCommitError.ExpectExec(`INSERT INTO`).WillReturnResult(sqlmock.NewResult(1, 1)) @@ -100,7 +93,7 @@ func TestCreateUserWithSQLMock(t *testing.T) { valid, err := tc.db.CreateUser(&model.UserRegistration{}) if tc.expectedError != nil { require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) + require.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) require.Nil(t, valid) } else { require.NoError(t, err) @@ -163,11 +156,11 @@ func TestLogin(t *testing.T) { valid, err := db.Login(tc.input) if tc.expectedError != nil { require.Error(t, err) - assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) + require.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError)) require.Nil(t, valid) } else { require.NoError(t, err) - assert.Equal(t, tc.input.Username, valid.Username) + require.Equal(t, tc.input.Username, valid.Username) } }) } -- cgit v1.2.3