Instantly share code, notes, and snippets.

@clairew clairew/example_test.go Secret
Last active Aug 9, 2018

What would you like to do?
DB Connection Helper Function Example
//GetTestDBConnection returns DB pointer to be used in test suite
func GetTestDBConnection() *sql.DB, error {
testDbName, sqlDriver := GenerateTestDB() // wrapped logic that generates test db and tables
dbUser, dbPass, dbHost, dbPort := GetDBCredsFromConfig() // get necessary db credentials
log.Info("Initializing test database connection")
connectionString := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", dbUser, dbPass, dbHost, dbPort, testDbName)
db, err := sql.Open(sqlDriver, connectionString)
if err != nil {
log.WithFields(log.Fields{ // use logrus logging package to specify error and scenario
"err": err,
"dbName": testDbName,
}).Warn("Unable to establish test database connection")
return nil, err
return db, nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment