|
1 | 1 | package sql |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "strings" |
4 | 5 | "testing" |
5 | 6 |
|
| 7 | + "go.uber.org/mock/gomock" |
| 8 | + |
6 | 9 | "github.com/stretchr/testify/assert" |
7 | 10 |
|
8 | 11 | "gofr.dev/pkg/gofr/testutil" |
9 | 12 | ) |
10 | 13 |
|
| 14 | +func TestNewSQL_ErrorCase(t *testing.T) { |
| 15 | + ctrl := gomock.NewController(t) |
| 16 | + |
| 17 | + expectedLog := "could not connect with 'testuser' user to database 'localhost:3306' error" |
| 18 | + |
| 19 | + mockConfig := testutil.NewMockConfig(map[string]string{ |
| 20 | + "DB_DIALECT": "mysql", |
| 21 | + "DB_HOST": "localhost", |
| 22 | + "DB_USER": "testuser", |
| 23 | + "DB_PASSWORD": "testpassword", |
| 24 | + "DB_PORT": "3306", |
| 25 | + "DB_NAME": "testdb", |
| 26 | + }) |
| 27 | + |
| 28 | + testLogs := testutil.StderrOutputForFunc(func() { |
| 29 | + mockLogger := testutil.NewMockLogger(testutil.ERRORLOG) |
| 30 | + mockMetrics := NewMockMetrics(ctrl) |
| 31 | + |
| 32 | + NewSQL(mockConfig, mockLogger, mockMetrics) |
| 33 | + }) |
| 34 | + |
| 35 | + if !strings.Contains(testLogs, expectedLog) { |
| 36 | + t.Errorf("TestNewSQL_ErrorCase Failed! Expcted error log doesn't match actual.") |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +func TestNewSQL_InvalidDialect(t *testing.T) { |
| 41 | + ctrl := gomock.NewController(t) |
| 42 | + |
| 43 | + mockConfig := testutil.NewMockConfig(map[string]string{ |
| 44 | + "DB_DIALECT": "abc", |
| 45 | + "DB_HOST": "localhost", |
| 46 | + }) |
| 47 | + |
| 48 | + testLogs := testutil.StderrOutputForFunc(func() { |
| 49 | + mockLogger := testutil.NewMockLogger(testutil.ERRORLOG) |
| 50 | + mockMetrics := NewMockMetrics(ctrl) |
| 51 | + |
| 52 | + NewSQL(mockConfig, mockLogger, mockMetrics) |
| 53 | + }) |
| 54 | + |
| 55 | + if !strings.Contains(testLogs, errUnsupportedDialect.Error()) { |
| 56 | + t.Errorf("TestNewSQL_ErrorCase Failed! Expcted error log doesn't match actual.") |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +func TestNewSQL_InvalidConfig(t *testing.T) { |
| 61 | + ctrl := gomock.NewController(t) |
| 62 | + |
| 63 | + mockConfig := testutil.NewMockConfig(map[string]string{ |
| 64 | + "DB_DIALECT": "", |
| 65 | + }) |
| 66 | + |
| 67 | + mockLogger := testutil.NewMockLogger(testutil.ERRORLOG) |
| 68 | + mockMetrics := NewMockMetrics(ctrl) |
| 69 | + |
| 70 | + db := NewSQL(mockConfig, mockLogger, mockMetrics) |
| 71 | + |
| 72 | + assert.Nil(t, db, "TestNewSQL_InvalidConfig. expected db to be nil.") |
| 73 | +} |
| 74 | + |
11 | 75 | func TestSQL_GetDBConfig(t *testing.T) { |
12 | 76 | mockConfig := testutil.NewMockConfig(map[string]string{ |
13 | 77 | "DB_DIALECT": "mysql", |
|
0 commit comments