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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
package fslocker
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
type mockFn struct {
mock.Mock
}
func (l *mockFn) Run() {
l.Called()
}
func mockDefaultLocker(t *testing.T, expectedPath string) (*mockLocker, func()) {
fsLockerMock := new(mockLocker)
oldLocker := defaultLocker
cleanup := func() {
defaultLocker = oldLocker
fsLockerMock.AssertExpectations(t)
}
defaultLocker = func(path string) locker {
assert.Equal(t, expectedPath, path)
return fsLockerMock
}
return fsLockerMock, cleanup
}
func TestInLock(t *testing.T) {
filePath := "/some/path/to/config/file"
testError := errors.New("test-error")
tests := map[string]struct {
fileLocker locker
prepareMockAssertions func(locker *mockLocker, fn *mockFn)
expectedError error
}{
"error on file locking": {
prepareMockAssertions: func(locker *mockLocker, fn *mockFn) {
locker.On("TryLock").
Return(true, testError).
Once()
},
expectedError: errCantAcquireLock(testError, filePath),
},
"can't lock the file": {
prepareMockAssertions: func(locker *mockLocker, fn *mockFn) {
locker.On("TryLock").
Return(false, nil).
Once()
},
expectedError: errFileInUse(filePath),
},
"file locked properly, fails on unlock": {
prepareMockAssertions: func(locker *mockLocker, fn *mockFn) {
locker.On("TryLock").
Return(true, nil).
Once()
locker.On("Unlock").
Return(testError).
Once()
fn.On("Run").Once()
},
expectedError: errCantReleaseLock(testError, filePath),
},
"file locked and unlocked properly": {
prepareMockAssertions: func(locker *mockLocker, fn *mockFn) {
locker.On("TryLock").
Return(true, nil).
Once()
locker.On("Unlock").
Return(nil).
Once()
fn.On("Run").Once()
},
},
}
for testName, testCase := range tests {
t.Run(testName, func(t *testing.T) {
fnMock := new(mockFn)
defer fnMock.AssertExpectations(t)
fsLockerMock, cleanup := mockDefaultLocker(t, filePath)
defer cleanup()
testCase.prepareMockAssertions(fsLockerMock, fnMock)
err := InLock(filePath, fnMock.Run)
if testCase.expectedError == nil {
assert.NoError(t, err)
return
}
assert.EqualError(t, err, testCase.expectedError.Error())
})
}
}
|