Skip to content
Rails-like test fixtures for Go. Write tests against a real database
Branch: master
Clone or download
Type Name Latest commit message Commit time
Failed to load latest commit information.
testdata Fixed by review comment. Jul 2, 2018
.travis.yml Update Go version on CI Nov 18, 2018
LICENSE README and LICENSE fixes. Apr 22, 2016
Taskfile.yml Fix CI Oct 27, 2018
appveyor.yml Update Go version on CI Nov 18, 2018
benchmark_test.go Write benchmark Oct 15, 2016
deprecated.go Fix golint May 11, 2017
generate.go add GenerateFixturesForTables func (#20) Oct 30, 2017
go.mod Switch to Go Modules Nov 18, 2018
mocks_for_test.go resolve approved andreynering's review issues Sep 5, 2018
mysql.go Fixed an issue with foreign key constraints in `Load()` function Dec 10, 2018
options.go Refactor how we handle sequences: Apr 30, 2016
oracle.go Modify databaseName to surface database errors (#19) Sep 4, 2017
oracle_test.go Refactoring helpers name Oct 12, 2016
postgresql.go Documentation improvements Nov 4, 2018
sqlite.go Improve syntax of some queries Jul 7, 2018
sqlserver_test.go Refactoring helpers name Oct 12, 2016
time.go Fix fixture generation on Oracle + refactoring of time conversion Mar 18, 2017

Go Test Fixtures

GoDoc Go Report Card Build Status Build status

Warning: this package will wipe the database data before loading the fixtures! It is supposed to be used on a test database. Please, double check if you are running it against the correct database.

Writing tests is hard, even more when you have to deal with an SQL database. This package aims to make writing functional tests for web apps written in Go easier.

Basically this package mimics the "Rails' way" of writing tests for database applications, where sample data is kept in fixtures files. Before the execution of every test, the test database is cleaned and the fixture data is loaded into the database.

The idea is running tests against a real database, instead of relying in mocks, which is boring to setup and may lead to production bugs not being caught in the tests.


First, get it:

go get -u -v


Create a folder for the fixture files. Each file should contain data for a single table and have the name <table_name>.yml:


The file would look like this (it can have as many record you want):

# comments.yml
- id: 1
  post_id: 1
  content: A comment...
  author_name: John Doe
  created_at: 2016-01-01 12:30:12
  updated_at: 2016-01-01 12:30:12

- id: 2
  post_id: 2
  content: Another comment...
  author_name: John Doe
  created_at: 2016-01-01 12:30:12
  updated_at: 2016-01-01 12:30:12

# ...

An YAML object or array will be converted to JSON. It can be stored on a native JSON type like JSONB on PostgreSQL or as a TEXT or VARCHAR column on other databases.

- id: 1
    author: John Due
    title: "..."
      - programming
      - go
      - testing
    post: "..."

If you need to write raw SQL, probably to call a function, prefix the value of the column with RAW=:

- id: 1
  uuid_column: RAW=uuid_generate_v4()
  postgis_type_column: RAW=ST_GeomFromText('params...')
  created_at: RAW=NOW()
  updated_at: RAW=NOW()

Your tests would look like this:

package myapp

import (

    _ ""

var (
    db *sql.DB
    fixtures *testfixtures.Context

func TestMain(m *testing.M) {
    var err error

    // Open connection with the test database.
    // Do NOT import fixtures in a production database!
    // Existing data would be deleted
    db, err = sql.Open("postgres", "dbname=myapp_test")
    if err != nil {

    // creating the context that hold the fixtures
    // see about all compatible databases in this page below
    fixtures, err = testfixtures.NewFolder(db, &testfixtures.PostgreSQL{}, "testdata/fixtures")
    if err != nil {


func prepareTestDatabase() {
    if err := fixtures.Load(); err != nil {

func TestX(t *testing.T) {
    // your test here ...

func TestY(t *testing.T) {
    // your test here ...

func TestZ(t *testing.T) {
    // your test here ...

Alternatively, you can use the NewFiles function, to specify which files you want to load into the database:

fixtures, err := testfixtures.NewFiles(db, &testfixtures.PostgreSQL{},
    // add as many files you want
if err != nil {

Security check

In order to prevent you from accidentally wiping the wrong database, this package will refuse to load fixtures if the database name (or database filename for SQLite) doesn't contains "test". If you want to disable this check, use:



For PostgreSQL or Oracle, this package also resets all sequences to a high number to prevent duplicated primary keys while running the tests. The default is 10000, but you can change that with:


Compatible databases


This package has two approaches to disable foreign keys while importing fixtures in PostgreSQL databases:


This is the default approach. For that use:


With the above snippet this package will use DISABLE TRIGGER to temporarily disabling foreign key constraints while loading fixtures. This work with any version of PostgreSQL, but it is required to be connected in the database as a SUPERUSER. You can make a PostgreSQL user a SUPERUSER with:



This approach don't require to be connected as a SUPERUSER, but only work with PostgreSQL versions >= 9.4. Try this if you are getting foreign key violation errors with the previous approach. It is as simple as using:

&testfixtures.PostgreSQL{UseAlterConstraint: true}

Skipping reset of sequences

You can skip the reset of PostgreSQL sequences if you're debugging a problem with it, but most of the time you shouldn't do it:

&testfixtures.PostgreSQL{SkipResetSequences: true}

MySQL / MariaDB

Just make sure the connection string have the multistatement parameter set to true, and use:



SQLite is also supported. It is recommended to create foreign keys as DEFERRABLE (the default) to prevent problems. See more on the SQLite documentation. (Foreign key constraints are no-op by default on SQLite, but enabling it is recommended).


Microsoft SQL Server

SQL Server support requires SQL Server >= 2008. Inserting on IDENTITY columns are handled as well. Just make sure you are logged in with a user with ALTER TABLE permission.



Oracle is supported as well. Use:


Generating fixtures for a existing database (experimental)

The following code will generate a YAML file for each table of the database in the given folder. It may be useful to boostrap a test scenario from a sample database of your app.

err := testfixtures.GenerateFixtures(db, &testfixtures.PostgreSQL{}, "testdata/fixtures")
if err != nil {
    log.Fatalf("Error generating fixtures: %v", err)


err := testfixtures.GenerateFixturesForTables(
        &TableInfo{Name: "table_name", Where: "foo = 'bar'"},
        // ...
if err != nil {
    log.Fatalf("Error generating fixtures: %v", err)

This was thought to run in small sample databases. It will likely break if run in a production/big database.


Parallel testing

This library doesn't yet support running tests in parallel! Running tests in parallel can result in random data being present in the database, which will likely cause tests to randomly/intermittently fail.

This is specially tricky since it's not immediately clear that go test ./... run tests for each package in parallel. If more than one package use this library, you can face this issue. Please, use go test -p 1 ./... or run tests for each package in separated commands to fix this issue.

See #40 and golang/go#11521 for more information.

We're also planning to implement transactional tests to allow running tests in parallel (see #24). Running each test package in a separated database would also allow you to do that. Open issues for other ideas 🙂.


Tests were written to ensure everything work as expected. You can run the tests with:

# running tests for PostgreSQL
go test -tags postgresql

# running test for MySQL
go test -tags mysql

# running tests for SQLite
go test -tags sqlite

# running tests for SQL Server
go test -tags sqlserver

# running tests for Oracle
go test -tags oracle

# running test for multiple databases at once
go test -tags 'sqlite postgresql mysql'

# running tests + benchmark
go test -v -bench=. -tags postgresql

Travis runs tests for PostgreSQL, MySQL and SQLite. AppVeyor run for all these and also Microsoft SQL Server.

To set the connection string of tests for each database, copy the .sample.env file as .env and edit it according to your environment.


If you don't think using fixtures is a good idea, you can try one of these packages instead:

  • factory-go: Factory for Go. Inspired by Python's Factory Boy and Ruby's Factory Girl
  • go-txdb (Single transaction SQL driver for Go): Use a single database transaction for each functional test, so you can rollback to previous state between tests to have the same database state in all tests
  • go-sqlmock: A mock for the sql.DB interface. This allow you to unit test database code without having to connect to a real database
  • dbcleaner - Clean database for testing, inspired by database_cleaner for Ruby
You can’t perform that action at this time.