Go: Run test from multiple package with DB initialization

3.1k views Asked by At

I have a GO project with this project structure (multiple couples of this kind of files in each package).

- api
    - userHandler.go
    - userHandler_test.go
- database
    - user.go
    - user_test.go

Inside user.go I have the User struct and the functions to Create/Get/Update a User (I'm using GORM but this is not the issue). In the user_test.go.

I'd like to have the DB cleaned (with all the data removed or in a certain state) for each different file, so I've tried to create 1 suite (using Testify) for each file, then use the SetupSuite function but the behaviour seems not deterministic, and probably I'm doing something wrong.

So my questions are:

  • Which is the best way to have a DB connection shared? Using a global variable is the best option?
  • Which is the best way to create the tables in the DB once and then init the DB with custom data before each file_test.go is run?

Right now I'm also having a strange bug: running

go test path/package1
go test path/package2

Everything works fine, but if I run (for testing all the packages)

cd path && go test ./...

I have errors that seems not to be deterministic, that's why I'm guessing that the DB connection is not handled properly

1

There are 1 answers

5
elithrar On BEST ANSWER

If your api package depends on your database package (which it appears to) then your api package should have a way to provide a database connection pool (e.g. a *sql.DB) to it.

In your tests for the api package, you should just pass in an initialised pool (perhaps with the test schema/fixtures pre-populated) that you can use. This can either be a global you initialise in init() for the api package or a setup() and defer teardown() pattern in each test function.

Here's the former (simplest) approach where you just create a shared database and schema for your tests to use.

package database

import testing

var testDB *sql.DB

// This gets run before your actual test functions do.
func init() {
    var err error
    db, err = sql.Open(...)
    if err != nil {
        log.Fatalf("test init failed: %s", err)
    }

    _, err := db.Exec(`CREATE TABLE ....`)
    if err != nil {
        log.Fatalf("test schema creation failed: %s", err)
    }
}

Some tips:

  • You can also call a setup() function can create a table with a random suffix and insert your test data so that your tests don't use the same test table (and therefore risk conflicting or relying on each other). Capture that table name and dump it in your defer teardown() function.
  • https://medium.com/@benbjohnson/structuring-applications-in-go-3b04be4ff091 is worth reading for some additional perspective.