Documentation
¶
Index ¶
Examples ¶
Constants ¶
const ( CgoSqliteSuffix = "with_CGO" DBTypeSqliteCgo = "SqliteWithCgo" )
const ( LocalSqliteEnv = "LOCAL_SQLITE" RunAllDBsEnv = "TESTDBS_ALL" )
const (
DBTypeMariadb = "mariadb"
)
const (
DBTypeMysql = "mysql"
)
const (
DBTypePostgres = "postgres"
)
const (
DBTypeSqliteNOCgo = "SqliteNoCgo"
)
Variables ¶
This section is empty.
Functions ¶
func InitCustomDbs ¶ added in v0.2.0
func InitCustomDbs(fastDbs, longDBs []TargetDb)
InitCustomDbs initializes the given DBs and makes them available through DBs(). fastDbs always run; longDBs run only when the -alldbs flag or the TESTDBS_ALL env var is set. Call it once, from TestMain.
Example ¶
Run Postgres from another image, here with pgvector, as the only DB. It is a slow DB, so a plain `go test` selects none and DBs() is empty.
package main
import (
"os"
"testing"
"github.com/go-bumbu/testdbs"
)
func main() {
testMain := func(m *testing.M) {
testdbs.InitCustomDbs(nil, []testdbs.TargetDb{
testdbs.NewPostgres("pgvector/pgvector:pg18"),
})
code := m.Run()
if err := testdbs.Clean(); err != nil {
os.Exit(1)
}
os.Exit(code)
}
_ = testMain
}
Output:
func InitDBS ¶
func InitDBS()
InitDBS initializes the default DBs: SQLite without CGo always, and SQLite with CGo, MariaDB, and Postgres with -alldbs or TESTDBS_ALL. MySQL is not in the default set; pass NewMysql to InitCustomDbs to run it. Call it once, from TestMain.
Example ¶
Start the default DBs once per package, from TestMain: SQLite always, and SQLite with CGo, MariaDB, and Postgres with -alldbs or TESTDBS_ALL.
package main
import (
"os"
"testing"
"github.com/go-bumbu/testdbs"
)
func main() {
testMain := func(m *testing.M) {
testdbs.InitDBS()
code := m.Run()
// stop the containers and delete the SQLite files
if err := testdbs.Clean(); err != nil {
os.Exit(1)
}
os.Exit(code)
}
_ = testMain
}
Output:
Types ¶
type ConnParams ¶ added in v0.4.0
type ConnParams struct {
Host string
Port int
User string
Password string
DbName string
// SslMode is libpq's sslmode; "disable" for Postgres. Empty for MySQL,
// which has no such setting.
SslMode string
}
ConnParams holds what a caller needs to open its own connection to a test database, e.g. to test code that builds its own DSN or gorm.Config.
type ConnParamsProvider ¶ added in v0.4.0
type ConnParamsProvider interface {
// ConnParams returns the parameters of the default database, the one
// Conn() uses.
ConnParams() ConnParams
// ConnParamsDbName returns the parameters of the database ConnDbName(name)
// uses, creating it if needed.
ConnParamsDbName(name string) ConnParams
}
ConnParamsProvider is implemented by the targets that run a database server (Postgres and MySQL), not by SQLite. Type-assert a TargetDb from DBs() to get it:
if p, ok := dbt.(testdbs.ConnParamsProvider); ok {
params := p.ConnParamsDbName(t.Name())
}
It is a separate interface so that custom TargetDb implementations passed to InitCustomDbs do not have to implement it.
Example ¶
Open your own connection to the server DBs; SQLite has no connection parameters.
package main
import (
"fmt"
"github.com/go-bumbu/testdbs"
)
func main() {
incomplete := 0
for _, dbt := range testdbs.DBs() {
p, ok := dbt.(testdbs.ConnParamsProvider)
if !ok {
continue
}
params := p.ConnParamsDbName("ExampleConnParamsProvider")
// build your own DSN from params here
if params.Host == "" || params.Port == 0 || params.DbName == "" {
incomplete++
}
}
fmt.Println("incomplete params:", incomplete)
}
Output: incomplete params: 0
type SqliteCgo ¶ added in v0.2.0
type SqliteCgo struct {
// contains filtered or unexported fields
}
SqliteCgo is safe for concurrent use: mu guards pool, and ConnDbName holds it while creating a DB so parallel callers asking for one name share one pool.
type SqliteNoCgo ¶ added in v0.2.0
type SqliteNoCgo struct {
// contains filtered or unexported fields
}
SqliteNoCgo is safe for concurrent use: mu guards pool, and ConnDbName holds it while creating a DB so parallel callers asking for one name share one pool.
func (*SqliteNoCgo) Close ¶ added in v0.2.0
func (c *SqliteNoCgo) Close(name string) error
func (*SqliteNoCgo) CloseAll ¶ added in v0.2.0
func (c *SqliteNoCgo) CloseAll() error
CloseAll closes every DB and, outside local mode, deletes the temp dir.
func (*SqliteNoCgo) Conn ¶ added in v0.2.0
func (c *SqliteNoCgo) Conn() *gorm.DB
func (*SqliteNoCgo) ConnDbName ¶ added in v0.2.0
func (c *SqliteNoCgo) ConnDbName(name string) *gorm.DB
func (*SqliteNoCgo) DbType ¶ added in v0.2.0
func (c *SqliteNoCgo) DbType() string
func (*SqliteNoCgo) Init ¶ added in v0.2.0
func (c *SqliteNoCgo) Init(logger logger.Interface)
type TargetDb ¶ added in v0.2.0
type TargetDb interface {
DbType() string
Init(logger logger.Interface)
Conn() *gorm.DB
ConnDbName(name string) *gorm.DB
Close(name string) error
CloseAll() error
}
func DBs ¶ added in v0.2.0
func DBs() []TargetDb
DBs returns the DBs selected by InitDBS or InitCustomDbs. The list is empty when only slow DBs were registered and neither -alldbs nor TESTDBS_ALL is set, so tests should skip in that case. DBs panics if no init function ran.
Example ¶
Run the same code once per DB. In a test, wrap the loop body in t.Run(dbt.DbType(), ...).
package main
import (
"fmt"
"github.com/go-bumbu/testdbs"
)
type Note struct {
ID uint `gorm:"primaryKey"`
Text string
}
func main() {
failed := 0
for _, dbt := range testdbs.DBs() {
// an isolated database, created on first use; dbt.Conn() is the
// shared default one
db := dbt.ConnDbName("ExampleDBs")
if err := db.AutoMigrate(&Note{}); err != nil {
failed++
continue
}
db.Create(&Note{Text: "hello"})
var count int64
db.Model(&Note{}).Count(&count)
if count != 1 {
failed++
}
}
fmt.Println("DBs that failed:", failed)
}
Output: DBs that failed: 0
func DefaultDbs ¶ added in v0.5.0
func DefaultDbs() (fast, slow []TargetDb)
DefaultDbs returns new instances of the fast and slow DBs InitDBS runs, to extend them before calling InitCustomDbs, e.g. to also run MySQL:
fast, slow := testdbs.DefaultDbs()
testdbs.InitCustomDbs(fast, append(slow, testdbs.NewMysql("")))
Example ¶
Add MySQL, which InitDBS leaves out, to the default list.
package main
import (
"os"
"testing"
"github.com/go-bumbu/testdbs"
)
func main() {
testMain := func(m *testing.M) {
fast, slow := testdbs.DefaultDbs()
testdbs.InitCustomDbs(fast, append(slow, testdbs.NewMysql("")))
code := m.Run()
if err := testdbs.Clean(); err != nil {
os.Exit(1)
}
os.Exit(code)
}
_ = testMain
}
Output:
func NewMariadb ¶ added in v0.5.0
NewMariadb returns a MariaDB target, the one InitDBS runs. An empty image runs the default mariadb:11.8; give another, e.g. "mariadb:10.11", to run that. The image must start like the official mariadb image: it accepts the MYSQL_* env vars, takes server flags as the container command (set to turn durability off), and logs "mariadbd: ready for connections" with "port: 3306" once the real server is up.
MariaDB shares MySQL's protocol and GORM driver, so DbType() is the only way to tell the two apart: it returns DBTypeMariadb.
func NewMysql ¶ added in v0.5.0
NewMysql returns a MySQL target. InitDBS runs MariaDB instead, so pass this to InitCustomDbs to test on MySQL. An empty image runs the default mysql:9.7; give another, e.g. "mysql:8.4", to run that. The image must start like the official mysql image, 8.0.30 or later: same env vars, the same entrypoint (the container command is server flags only, to turn durability off), and the real server logging "mysqld: ready for connections" with "port: 3306". Use NewMariadb for MariaDB images.
func NewPostgres ¶ added in v0.3.0
NewPostgres returns a Postgres target that runs image instead of the default postgres:18, e.g. "pgvector/pgvector:pg18" for the vector extension. An empty image keeps the default. The image must start like the official postgres image: same env vars, the same entrypoint (the container command is set to "postgres -c ..." to turn durability off), and "database system is ready to accept connections" logged twice (initdb's temporary server, then the real one).