I have the following testing code where I am testing some endpoints and database (mongoDB) features. I am using mgo package and I have some abstractions to get a new session copy each time I access the database.
package resolvers_test
import (
//various imports here
)
func setup() {
log.Println("ENTER SETUP
")
customerIndex := mgo.Index{
Key: []string{"email"},
Unique: true,
Background: true,
Sparse: true,
}
session := db.GetSession().Copy()
defer session.Close()
customerCollection := session.DB("testDB").C("customerCollection")
customerCollection.EnsureIndex(customerIndex)
log.Println("EXIT SETUP")
}
func shutdown() {
log.Println("ENTER SHUTDOWN
")
session := db.GetSession().Copy()
defer session.Close()
session.DB("testDB").DropDatabase()
log.Println("EXIT SHUTDOWN
")
}
func TestMain(m *testing.M) {
setup()
code := m.Run()
shutdown()
os.Exit(code)
}
In the shutdown()
function I have placed a piece of code that supposedly should delete the test database, however while setup()
function is called (I know that because it creates the Index) the shutdown()
function is never called. Any ideas?
EDIT: I added log statements when entering end exiting setup() and shutdown() and the console log. The functions are both reachable. The log is the following:
2018/02/10 09:09:54 ENTER SETUP
2018/02/10 09:09:55 EXIT SETUP
=== RUN TestCreateCustomer
--- PASS: TestCreateCustomer (0.14s)
a_customerProfile_test.go:108: Create Customer successful
=== RUN TestCustomerProfile
--- PASS: TestCustomerProfile (0.27s)
a_customerProfile_test.go:152: Customer Profile Test Successful
PASS
2018/02/10 09:09:55 ENTER SHUTDOWN
2018/02/10 09:09:55 EXIT SHUTDOWN
You are stating defer session.Close()
in setup()
Hence session := db.GetSession().Copy()
in shutdown()
will get a new session without any DB selected.
Make setup()
returns *mgo.Session
and state defer session.Close()
in TestMain()