github.com/nilium/gitlab-runner@v12.5.0+incompatible/helpers/fslocker/fslocker_test.go (about) 1 package fslocker 2 3 import ( 4 "errors" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 "github.com/stretchr/testify/mock" 9 ) 10 11 type mockFn struct { 12 mock.Mock 13 } 14 15 func (l *mockFn) Run() { 16 l.Called() 17 } 18 19 func mockDefaultLocker(t *testing.T, expectedPath string) (*mockLocker, func()) { 20 fsLockerMock := new(mockLocker) 21 22 oldLocker := defaultLocker 23 cleanup := func() { 24 defaultLocker = oldLocker 25 fsLockerMock.AssertExpectations(t) 26 } 27 28 defaultLocker = func(path string) locker { 29 assert.Equal(t, expectedPath, path) 30 31 return fsLockerMock 32 } 33 34 return fsLockerMock, cleanup 35 } 36 37 func TestInLock(t *testing.T) { 38 filePath := "/some/path/to/config/file" 39 testError := errors.New("test-error") 40 41 tests := map[string]struct { 42 fileLocker locker 43 prepareMockAssertions func(locker *mockLocker, fn *mockFn) 44 expectedError error 45 }{ 46 "error on file locking": { 47 prepareMockAssertions: func(locker *mockLocker, fn *mockFn) { 48 locker.On("TryLock"). 49 Return(true, testError). 50 Once() 51 }, 52 expectedError: errCantAcquireLock(testError, filePath), 53 }, 54 "can't lock the file": { 55 prepareMockAssertions: func(locker *mockLocker, fn *mockFn) { 56 locker.On("TryLock"). 57 Return(false, nil). 58 Once() 59 60 }, 61 expectedError: errFileInUse(filePath), 62 }, 63 "file locked properly, fails on unlock": { 64 prepareMockAssertions: func(locker *mockLocker, fn *mockFn) { 65 locker.On("TryLock"). 66 Return(true, nil). 67 Once() 68 locker.On("Unlock"). 69 Return(testError). 70 Once() 71 72 fn.On("Run").Once() 73 }, 74 expectedError: errCantReleaseLock(testError, filePath), 75 }, 76 "file locked and unlocked properly": { 77 prepareMockAssertions: func(locker *mockLocker, fn *mockFn) { 78 locker.On("TryLock"). 79 Return(true, nil). 80 Once() 81 locker.On("Unlock"). 82 Return(nil). 83 Once() 84 85 fn.On("Run").Once() 86 }, 87 }, 88 } 89 90 for testName, testCase := range tests { 91 t.Run(testName, func(t *testing.T) { 92 fnMock := new(mockFn) 93 defer fnMock.AssertExpectations(t) 94 95 fsLockerMock, cleanup := mockDefaultLocker(t, filePath) 96 defer cleanup() 97 98 testCase.prepareMockAssertions(fsLockerMock, fnMock) 99 100 err := InLock(filePath, fnMock.Run) 101 102 if testCase.expectedError == nil { 103 assert.NoError(t, err) 104 return 105 } 106 107 assert.EqualError(t, err, testCase.expectedError.Error()) 108 }) 109 } 110 }