Skip to content

Commit

Permalink
Merge pull request #427 from bruin-data/mysql-conn-test
Browse files Browse the repository at this point in the history
Mysql conn test
  • Loading branch information
terzioglub authored Jan 28, 2025
2 parents 6a70def + 155fef7 commit c41dfa2
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
13 changes: 13 additions & 0 deletions pkg/mysql/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,16 @@ func (c *Client) SelectWithSchema(ctx context.Context, queryObj *query.Query) (*

return result, nil
}

func (c *Client) Ping(ctx context.Context) error {
q := query.Query{
Query: "SELECT 1",
}

err := c.RunQueryWithoutResult(ctx, &q)
if err != nil {
return errors.Wrap(err, "failed to run test query on MySQL connection")
}

return nil
}
53 changes: 53 additions & 0 deletions pkg/mysql/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,56 @@ func TestClient_SelectWithSchema(t *testing.T) {
})
}
}

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

tests := []struct {
name string
mockConnection func(mock sqlmock.Sqlmock)
wantErr bool
errorMessage string
}{
{
name: "successful ping",
mockConnection: func(mock sqlmock.Sqlmock) {
mock.ExpectExec(`SELECT 1`).
WillReturnResult(sqlmock.NewResult(0, 0))
},
wantErr: false,
},
{
name: "failed ping",
mockConnection: func(mock sqlmock.Sqlmock) {
mock.ExpectExec(`SELECT 1`).
WillReturnError(errors.New("connection refused"))
},
wantErr: true,
errorMessage: "failed to run test query on MySQL connection: failed to execute query: connection refused",
},
}

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

mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
require.NoError(t, err)
defer mockDB.Close()
sqlxDB := sqlx.NewDb(mockDB, "sqlmock")

tt.mockConnection(mock)
client := Client{conn: sqlxDB}

err = client.Ping(context.Background())
if tt.wantErr {
require.Error(t, err)
assert.Equal(t, tt.errorMessage, err.Error())
} else {
require.NoError(t, err)
}

require.NoError(t, mock.ExpectationsWereMet())
})
}
}

0 comments on commit c41dfa2

Please sign in to comment.