2021-07-17 00:20:45 +00:00
|
|
|
package simple
|
|
|
|
|
|
|
|
import (
|
|
|
|
"runtime"
|
|
|
|
"testing"
|
2021-07-18 11:34:30 +00:00
|
|
|
"time"
|
2021-07-17 00:20:45 +00:00
|
|
|
|
|
|
|
"github.com/appleboy/gorush/gorush"
|
2021-07-18 11:34:30 +00:00
|
|
|
"github.com/appleboy/gorush/logx"
|
|
|
|
"github.com/appleboy/gorush/queue"
|
2021-07-17 12:14:19 +00:00
|
|
|
|
2021-07-17 00:20:45 +00:00
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
2021-07-18 11:34:30 +00:00
|
|
|
type mockMessage struct {
|
|
|
|
msg string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m mockMessage) Bytes() []byte {
|
|
|
|
return []byte(m.msg)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestMain(m *testing.M) {
|
|
|
|
m.Run()
|
|
|
|
}
|
|
|
|
|
2021-07-17 00:20:45 +00:00
|
|
|
func TestQueueUsage(t *testing.T) {
|
|
|
|
w := NewWorker()
|
|
|
|
assert.Equal(t, runtime.NumCPU()<<1, w.Capacity())
|
|
|
|
assert.Equal(t, 0, w.Usage())
|
|
|
|
|
2021-07-17 17:58:46 +00:00
|
|
|
w.Queue(&gorush.PushNotification{})
|
2021-07-17 00:20:45 +00:00
|
|
|
assert.Equal(t, 1, w.Usage())
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestMaxCapacity(t *testing.T) {
|
|
|
|
w := NewWorker(WithQueueNum(2))
|
|
|
|
assert.Equal(t, 2, w.Capacity())
|
|
|
|
assert.Equal(t, 0, w.Usage())
|
|
|
|
|
2021-07-17 17:58:46 +00:00
|
|
|
assert.NoError(t, w.Queue(&gorush.PushNotification{}))
|
2021-07-17 00:20:45 +00:00
|
|
|
assert.Equal(t, 1, w.Usage())
|
2021-07-17 17:58:46 +00:00
|
|
|
assert.NoError(t, w.Queue(&gorush.PushNotification{}))
|
2021-07-17 00:20:45 +00:00
|
|
|
assert.Equal(t, 2, w.Usage())
|
2021-07-17 17:58:46 +00:00
|
|
|
assert.Error(t, w.Queue(&gorush.PushNotification{}))
|
2021-07-17 00:20:45 +00:00
|
|
|
assert.Equal(t, 2, w.Usage())
|
|
|
|
|
2021-07-17 17:58:46 +00:00
|
|
|
err := w.Queue(&gorush.PushNotification{})
|
2021-07-17 00:20:45 +00:00
|
|
|
assert.Equal(t, errMaxCapacity, err)
|
|
|
|
}
|
2021-07-18 11:34:30 +00:00
|
|
|
|
|
|
|
func TestCustomFuncAndWait(t *testing.T) {
|
|
|
|
m := mockMessage{
|
|
|
|
msg: "foo",
|
|
|
|
}
|
|
|
|
w := NewWorker(
|
|
|
|
WithRunFunc(func(msg queue.QueuedMessage) error {
|
|
|
|
logx.LogAccess.Infof("get message: %s", msg.Bytes())
|
|
|
|
time.Sleep(500 * time.Millisecond)
|
|
|
|
return nil
|
|
|
|
}),
|
|
|
|
)
|
2021-07-23 17:29:47 +00:00
|
|
|
q, err := queue.NewQueue(
|
|
|
|
queue.WithWorker(w),
|
|
|
|
queue.WithWorkerCount(2),
|
|
|
|
)
|
|
|
|
assert.NoError(t, err)
|
2021-07-18 11:34:30 +00:00
|
|
|
q.Start()
|
|
|
|
time.Sleep(100 * time.Millisecond)
|
|
|
|
q.Queue(m)
|
|
|
|
q.Queue(m)
|
|
|
|
q.Queue(m)
|
|
|
|
q.Queue(m)
|
|
|
|
time.Sleep(600 * time.Millisecond)
|
|
|
|
q.Shutdown()
|
|
|
|
q.Wait()
|
|
|
|
// you will see the execute time > 1000ms
|
|
|
|
}
|