Introducing dbcleaner - database_cleaner gem like written in Go
https://gopkg.in/khaiql/dbcleaner.v2
UPDATES: I published v2 version of the library to fix some issues in previous version:
-
Allow truncate Mysql tables that have foreign key
-
Fix problem of race condition
-
Only truncate specified tables instead of all tables, this would avoid problem of making other tests failed because of accidentally truncate data.
If you have experience in Ruby/Rails development, you may know about database_cleaner, a 2k stars gem to clean database after each test case.
Switching to Go, you may miss the features that the gem provides during writing test. That said, having to write piece of code to truncate table after every single test case to keep the database clean is way to boilerplate. That’s why I decided to extract that piece of code into a small library that can do stuff automatically.
You can find source code and instructions on how to use in the library’s homepage. It’s a perfect combination with testify’s suite. All you need to do is to define a BaseSuite
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
```go
type BaseSuite struct {
suite.Suite
DBCleaner *dbcleaner.DBCleaner
}
// SetupSuite inits dbcleaner instance at the beginning of every suite
func (suite *BaseSuite) SetupSuite() {
cleaner, err := dbcleaner.New("postgres", "YOUR_DB_CONNECTION_STRING")
if err != nil {
panic(err)
}
suite.DBCleaner = cleaner
}
// TearDownSuite closes and releases connection at the end of suite
func (suite *BaseSuite) TearDownSuite() {
suite.DBCleaner.Close()
}
// Truncate tables after every test case. Note: sub-test using t.Run wouldn't be
// taken into account
func (suite *BaseSuite) TearDownTest() {
suite.DBCleaner.TruncateTablesExclude("migrations")
}
```
By this way, you can have great degree of isolation between different test suites but also take advantage of dbcleaner.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
```go
type ExampleSuite struct {
BaseSuite
}
func (suite *ExampleSuite) TestSomething() {
// Have some meaningful test
suite.Equal(true, true)
}
func TestRunSuite(t *testing.T) {
suite.Run(t, new(ExampleSuite))
}
```
For now, postgres and mysql are the support drivers. Implementing new driver is straightforward as it follows the same mechanism as sql
package.
Found some bugs? Feel free to submit a ticket.
Comments powered by Disqus.