Your Question
I'm trying to write a test suite with gin and gorm. The problem I am facing is that tests leave behind data that was created within the tests either by the API or test fixtures.
How can I get rid of that data?
Apparently, this used to work in the past. I guess this is broken now with the latest release.
func DeleteCreatedEntities(db *gorm.DB) func() {
type entity struct {
table string
keyname string
key interface{}
}
var entries []entity
hookName := "cleanupHook"
// Setup the onCreate Hook
db.Callback().Create().After("gorm:create").Register(hookName, func(scope *gorm.Scope) {
fmt.Printf("Inserted entities of %s with %s=%v\n", scope.TableName(), scope.PrimaryKey(), scope.PrimaryKeyValue())
entries = append(entries, entity{table: scope.TableName(), keyname: scope.PrimaryKey(), key: scope.PrimaryKeyValue()})
})
return func() {
// Remove the hook once we're done
defer db.Callback().Create().Remove(hookName)
// Find out if the current db object is already a transaction
_, inTransaction := db.CommonDB().(*sql.Tx)
tx := db
if !inTransaction {
tx = db.Begin()
}
// Loop from the end. It is important that we delete the entries in the
// reverse order of their insertion
for i := len(entries) - 1; i >= 0; i-- {
entry := entries[i]
fmt.Printf("Deleting entities from '%s' table with key %v\n", entry.table, entry.key)
tx.Table(entry.table).Where(entry.keyname+" = ?", entry.key).Delete("")
}
if !inTransaction {
tx.Commit()
}
}
}
Expected answer
Is there a way that I can make it work?
Comment From: hugowangler
Not sure how you have setup your tests, but if you have a test suite I found it easy to declare a TearDownTest() method which will run after each test in the test suite (See the docs). In this method I've placed all the cleanup code that simply deletes all the entries that was created.
Comment From: liamhendricks
Why not just drop the database and re-migrate? Or just truncate the tables.
Comment From: debugger22
I am doing the truncate table as of now but they only work when tests are run sequentially i.e. with arg go test -p 1. I'm guessing go tries to optimize the execution time by running tests concurrently.
This is when the issue comes when multiple handlers are being tested the data in tables create conflict.