-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpool_test.go
334 lines (267 loc) · 8.08 KB
/
pool_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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Copyright (c) 2024 Bart Venter <bartventer@outlook.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pooler
import (
"context"
"errors"
"fmt"
"log"
"maps"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
// MockReusable is a mock implementation of the Reusable interface.
type MockReusable struct {
mock.Mock
}
func (m *MockReusable) Close() error {
args := m.Called()
return args.Error(0)
}
func (m *MockReusable) PingContext(ctx context.Context) error {
args := m.Called(ctx)
return args.Error(0)
}
// MockFactory is a mock implementation of the Factory function.
func MockFactory() (Reusable, error) {
return &MockReusable{}, nil
}
func TestNewPool_DefaultOptions(t *testing.T) {
ctx := context.Background()
pool := NewPool(ctx, MockFactory)
assert.Equal(t, defaultMaxOpenResources, pool.options.MaxOpenResources)
assert.Equal(t, defaultHealthCheckInterval, pool.options.HealthCheckInterval)
}
func TestNewPool_CustomOptions(t *testing.T) {
ctx := context.Background()
pool := NewPool(ctx, MockFactory, WithMaxOpenResources(5), WithHealthCheckInterval(2*time.Minute))
assert.Equal(t, 5, pool.options.MaxOpenResources)
assert.Equal(t, 2*time.Minute, pool.options.HealthCheckInterval)
}
func TestPool_Acquire(t *testing.T) {
ctx := context.Background()
pool := NewPool(ctx, MockFactory)
resource, err := pool.Acquire(ctx, "key1")
require.NoError(t, err)
assert.NotNil(t, resource)
assert.True(t, pool.Contains("key1"))
// Acquire the same resource again
resource2, err := pool.Acquire(ctx, "key1")
require.NoError(t, err)
assert.NotNil(t, resource2)
ctx2, cancel := context.WithCancel(ctx)
cancel()
_, err = pool.Acquire(ctx2, "key1")
assert.ErrorIs(t, err, context.Canceled)
}
func TestPool_Acquire_FactoryError(t *testing.T) {
ctx := context.Background()
pool := NewPool(ctx, func() (Reusable, error) {
return nil, errors.New("error")
})
resource, err := pool.Acquire(ctx, "key1")
require.ErrorIs(t, err, ErrFactoryError)
assert.Nil(t, resource)
}
func TestPool_Release(t *testing.T) {
mockResource := new(MockReusable)
mockResource.On("Close").Return(nil)
ctx := context.Background()
pool := NewPool(ctx, func() (Reusable, error) {
return mockResource, nil
})
resource, err := pool.Acquire(ctx, "key1")
require.NoError(t, err)
assert.NotNil(t, resource)
pool.Release("key1")
assert.False(t, pool.Contains("key1"))
mockResource.AssertCalled(t, "Close")
mockResource.AssertExpectations(t)
}
func TestPool_Contains(t *testing.T) {
ctx := context.Background()
pool := NewPool(ctx, MockFactory)
assert.False(t, pool.Contains("key1"))
_, err := pool.Acquire(ctx, "key1")
require.NoError(t, err)
assert.True(t, pool.Contains("key1"))
}
func TestPool_ReleaseAll(t *testing.T) {
mockResource := new(MockReusable)
mockResource.On("Close").Return(nil)
ctx := context.Background()
pool := NewPool(ctx, func() (Reusable, error) {
return mockResource, nil
})
for i := range 5 {
key := fmt.Sprintf("key%d", i)
_, err := pool.Acquire(ctx, key)
require.NoError(t, err)
assert.True(t, pool.Contains(key))
}
pool.ReleaseAll()
for i := range 5 {
key := fmt.Sprintf("key%d", i)
assert.False(t, pool.Contains(key))
}
}
func TestPool_Stats(t *testing.T) {
ctx := context.Background()
pool := NewPool(ctx, MockFactory, WithMaxOpenResources(2))
stats := pool.Stats()
assert.Equal(t, 2, stats.MaxOpenResources)
assert.Equal(t, 0, stats.OpenResources)
_, _ = pool.Acquire(ctx, "key1")
_, _ = pool.Acquire(ctx, "key2")
stats = pool.Stats()
assert.Equal(t, 2, stats.MaxOpenResources)
assert.Equal(t, 2, stats.OpenResources)
}
func TestPool_HealthCheck(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
mockResource := new(MockReusable)
mockResource.On("PingContext", ctx).Return(errors.New("error"))
mockResource.On("Close").Return(nil)
pool := NewPool(ctx, func() (Reusable, error) {
return mockResource, nil
}, WithHealthCheckInterval(100*time.Millisecond))
resource, err := pool.Acquire(ctx, "key1")
require.NoError(t, err)
assert.NotNil(t, resource)
assert.True(t, pool.Contains("key1"))
// Wait for the health check to run
time.Sleep(200 * time.Millisecond)
assert.False(t, pool.Contains("key1"))
mockResource.AssertExpectations(t)
}
func TestPool_Acquire_MaxResources(t *testing.T) {
ctx := context.Background()
mockResource := new(MockReusable)
mockResource.On("Close").Return(nil)
pool := NewPool(ctx, func() (Reusable, error) {
return mockResource, nil
}, WithMaxOpenResources(1))
resource1, err := pool.Acquire(ctx, "key1")
require.NoError(t, err)
assert.NotNil(t, resource1)
assert.True(t, pool.Contains("key1"))
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
_, _ = pool.Acquire(ctx, "key2")
}()
// Wait for the goroutine to block on Acquire
time.Sleep(100 * time.Millisecond)
// The waiting goroutine should be in the wait queue
stats := pool.Stats()
assert.False(t, pool.Contains("key2"))
assert.Equal(t, int64(1), stats.WaitCount)
// Release resource1 to unblock the waiting goroutine
pool.Release("key1")
wg.Wait()
assert.False(t, pool.Contains("key1"))
assert.True(t, pool.Contains("key2"))
stats = pool.Stats()
assert.Equal(t, int64(0), stats.WaitCount)
assert.GreaterOrEqual(t, stats.WaitDuration, int64(100*time.Millisecond))
}
func TestPool_ContextCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
pool := NewPool(ctx, MockFactory)
cancel()
_, err := pool.Acquire(ctx, "key1")
require.ErrorIs(t, err, context.Canceled)
}
func TestPool_ContextCancellation_Waiting(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
pool := NewPool(ctx, MockFactory, WithMaxOpenResources(1))
_, err := pool.Acquire(ctx, "key1")
require.NoError(t, err)
errCh := make(chan error, 1)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
_, ctxErr := pool.Acquire(ctx, "key2")
errCh <- ctxErr
}()
// Wait for the goroutine to block on Acquire
time.Sleep(100 * time.Millisecond)
cancel()
wg.Wait()
close(errCh)
err = <-errCh
require.ErrorIs(t, err, context.Canceled)
}
func TestPool_Parallel_Acquire_MaxResources(t *testing.T) {
t.Parallel()
ctx := context.Background()
mockResource := new(MockReusable)
mockResource.On("Close").Return(nil)
pool := NewPool(ctx, func() (Reusable, error) {
return mockResource, nil
}, WithMaxOpenResources(2))
for i := range 3 {
t.Run(fmt.Sprintf("goroutine-%d", i), func(t *testing.T) {
t.Parallel()
key := fmt.Sprintf("key%d", i)
_, err := pool.Acquire(ctx, key)
require.NoError(t, err)
assert.True(t, pool.Contains(key))
// Give some time for the goroutine to block on Acquire
time.Sleep(100 * time.Millisecond)
// Release the resource to make space for the next goroutine
pool.Release(key)
log.Printf("Released resource for key: %s", key)
assert.False(t, pool.Contains(key))
})
}
}
func TestPool_All(t *testing.T) {
ctx := context.Background()
pool := NewPool(ctx, MockFactory)
for i := range 3 {
key := fmt.Sprintf("key%d", i)
_, err := pool.Acquire(ctx, key)
require.NoError(t, err)
}
allResources := maps.Collect(pool.All())
assert.Len(t, allResources, 3)
}
func TestPool_Walk(t *testing.T) {
ctx := context.Background()
pool := NewPool(ctx, MockFactory)
for i := range 3 {
key := fmt.Sprintf("key%d", i)
_, err := pool.Acquire(ctx, key)
require.NoError(t, err)
}
var keys []string
next, stop := pool.Walk()
defer stop()
for {
key, _, ok := next()
if !ok {
break
}
keys = append(keys, key)
}
assert.Len(t, keys, 3)
}