testdb

package module
v0.0.0-...-5f32784 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 12, 2014 License: MIT Imports: 4 Imported by: 0

README

testdb

Build Status

testdb allows you to spin up temporary databases for testing purposes. Each instance uses a separate databases which is dropped when the database is closed.

For documentation, check godoc.

Documentation

Overview

Package testdb provides an easy way to, given a running database server, create temporary, isolated databases to use in testing.

Example
package main

import (
	"database/sql"
	"fmt"

	"github.com/codahale/testdb"
	_ "github.com/lib/pq"
)

func main() {
	baseDSN := testdb.Env("PG_DB", "sslmode=disable")

	tdb, err := testdb.Open("postgres", baseDSN+" dbname=postgres")
	if err != nil {
		panic(err)
	}
	defer tdb.Close()

	db, err := sql.Open("postgres", baseDSN+" dbname="+tdb.Name())
	if err != nil {
		panic(err)
	}
	defer db.Close()

	if _, err := db.Exec(`CREATE TABLE things(id SERIAL, PRIMARY KEY (id))`); err != nil {
		panic(err)
	}

	var count int
	if err := db.QueryRow(`SELECT COUNT(id) FROM things`).Scan(&count); err != nil {
		panic(err)
	}

	fmt.Println(count)

	if _, err := db.Exec(`INSERT INTO things DEFAULT VALUES`); err != nil {
		panic(err)
	}

	var newCount int
	if err := db.QueryRow(`SELECT COUNT(id) FROM things`).Scan(&newCount); err != nil {
		panic(err)
	}

	fmt.Println(newCount)

}
Output:
0
1

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Env

func Env(key, defaultValue string) string

Env returns an environment variable, or if the environment variable is not present, the default value.

Types

type TestDB

type TestDB struct {
	// contains filtered or unexported fields
}

TestDB is a temporary database for testing.

func Open

func Open(driverName, dataSourceName string) (*TestDB, error)

Open creates a new TestDB given the driver name and the data source name.

func (*TestDB) Close

func (tdb *TestDB) Close() error

Close drops the testing databases and disconnects from the server.

N.B.: Not calling this will result in your database server accumulating many databases.

func (*TestDB) Name

func (tdb *TestDB) Name() string

Name gets the name of the created test database

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL