vain/db_test.go

78 lines
1.8 KiB
Go

package vain
import (
"errors"
"fmt"
"strings"
"testing"
"github.com/lib/pq"
"github.com/pborman/uuid"
)
type TestDB struct {
DB
name string
}
func NewTestDB(name string) (*TestDB, error) {
pgdb, err := NewPGDB("localhost", "postgres", 64)
if err != nil {
return nil, fmt.Errorf("problem connecting to admin database: %v", err)
}
if _, err := pgdb.conn.Exec(fmt.Sprintf("CREATE DATABASE %s", pq.QuoteIdentifier(name))); err != nil {
return nil, fmt.Errorf("problem creating test database:: %v", err)
}
pgdb.conn.Close()
db, err := NewPGDB("localhost", name, 64)
if err != nil {
return nil, fmt.Errorf("couldn't connect to fresh db %q: %v", name, err)
}
if err := db.Init(); err != nil {
return nil, fmt.Errorf("couldn't initialize db: %v", err)
}
r := &TestDB{
name: name,
DB: DB{
conn: db.conn,
},
}
return r, nil
}
func (tdb *TestDB) Close() error {
errs := []string{}
if err := tdb.conn.Close(); err != nil {
errs = append(errs, fmt.Sprintf("problem closing connection to temp db: %v", err))
}
if err := tdb.Drop(); err != nil {
errs = append(errs, fmt.Sprintf("problem cleaning up temporary db %q: %v", tdb.name, err))
}
if len(errs) > 0 {
return errors.New(strings.Join(errs, " & "))
}
return nil
}
func (tdb *TestDB) Drop() error {
pgdb, err := NewPGDB("localhost", "postgres", 64)
if err != nil {
return fmt.Errorf("problem connecting to admin database: %v", err)
}
defer pgdb.conn.Close()
if _, err := pgdb.conn.Exec(fmt.Sprintf("DROP DATABASE %s", pq.QuoteIdentifier(tdb.name))); err != nil {
return fmt.Errorf("problem dropping test database:: %v", err)
}
return nil
}
func TestFoo(t *testing.T) {
db, err := NewTestDB(uuid.New())
if err != nil {
t.Errorf("couldn't connect to fresh db : %v", err)
}
defer db.Close()
}