-
Notifications
You must be signed in to change notification settings - Fork 15
/
dbcleaner_test.go
89 lines (71 loc) · 2.14 KB
/
dbcleaner_test.go
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package dbcleaner
import (
"errors"
"testing"
"time"
"github.com/khaiql/dbcleaner/engine"
"github.com/stretchr/testify/mock"
)
func setupMock() *engine.MockEngine {
mockEngine := &engine.MockEngine{}
mockEngine.On("Truncate", mock.AnythingOfType("string")).Return(nil)
mockEngine.On("Close").Return(nil)
return mockEngine
}
func TestClean(t *testing.T) {
cleaner := New(SetNumberOfRetry(2), SetLockTimeout(1*time.Second), SetRetryInterval(1*time.Second))
mockEngine := setupMock()
cleaner.SetEngine(mockEngine)
t.Run("TestNothingLock", func(t *testing.T) {
cleaner.Clean("table1", "table2")
mockEngine.AssertNumberOfCalls(t, "Truncate", 2)
mockEngine.AssertCalled(t, "Truncate", "table1")
mockEngine.AssertCalled(t, "Truncate", "table2")
})
t.Run("TestLockAndThenUnlock", func(t *testing.T) {
tbName := "lock_table"
cleaner.Acquire(tbName)
cleaner.Clean(tbName)
mockEngine.AssertCalled(t, "Truncate", tbName)
})
t.Run("TestClose", func(t *testing.T) {
cleaner.Close()
mockEngine.AssertCalled(t, "Close")
})
t.Run("TestTruncateError", func(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("The code did not panic")
}
}()
errorTruncateMock := &engine.MockEngine{}
errorTruncateMock.On("Truncate", mock.AnythingOfType("string")).Return(errors.New("Truncate error"))
cleaner.SetEngine(errorTruncateMock)
cleaner.Clean("error_table")
})
t.Run("TestCleanWithoutLock", func(t *testing.T) {
e := setupMock()
cleaner.SetEngine(e)
cleaner.Acquire("table_1")
cleaner.Acquire("table_1")
go func() {
cleaner.Clean("table_1")
e.AssertNumberOfCalls(t, "Truncate", 1)
}()
time.Sleep(2 * time.Second)
cleaner.Clean("table_1")
e.AssertNumberOfCalls(t, "Truncate", 2)
})
t.Run("TestAcquire", func(t *testing.T) {
t.Run("FailedToAcquireBecauseOfDeadLock", func(t *testing.T) {
cleaner.Acquire("table_1")
defer func() {
if r := recover(); r == nil {
t.Error("It should panic because of not able to acquire the lock")
}
}()
other := New(SetNumberOfRetry(2), SetLockTimeout(1*time.Second), SetRetryInterval(1*time.Second))
other.Acquire("table_1")
})
})
}