File size: 1,437 Bytes
13555f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package utils

import (
	"context"
	"sync/atomic"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"

	"github.com/mattermost/mattermost/server/public/shared/mlog"
)

func Test_newChangeNotifier(t *testing.T) {
	logger := mlog.CreateConsoleTestLogger(t)

	t.Run("startup, shutdown", func(t *testing.T) {
		cn := NewCallbackQueue("test1", 100, 5, logger)

		var callbackCount int32
		callback := func() error {
			atomic.AddInt32(&callbackCount, 1)
			return nil
		}

		const loops = 500
		for i := 0; i < loops; i++ {
			cn.Enqueue(callback)
			// don't peg the cpu
			if i%20 == 0 {
				time.Sleep(time.Millisecond * 1)
			}
		}

		ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
		defer cancel()
		ok := cn.Shutdown(ctx)
		assert.True(t, ok, "shutdown should return true (no timeout)")

		assert.Equal(t, int32(loops), atomic.LoadInt32(&callbackCount))
	})

	t.Run("handle panic", func(t *testing.T) {
		cn := NewCallbackQueue("test2", 100, 5, logger)

		var callbackCount int32
		callback := func() error {
			atomic.AddInt32(&callbackCount, 1)
			panic("oh no!")
		}

		const loops = 5
		for i := 0; i < loops; i++ {
			cn.Enqueue(callback)
		}

		ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
		defer cancel()
		ok := cn.Shutdown(ctx)
		assert.True(t, ok, "shutdown should return true (no timeout)")

		assert.Equal(t, int32(loops), atomic.LoadInt32(&callbackCount))
	})
}