forked from p93542168/wheat-cache
100 lines
2.4 KiB
Go
100 lines
2.4 KiB
Go
package event
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"gitee.com/timedb/wheatCache/pkg/errorx"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
const testEvent = "1001"
|
|
const waitTestEvent = "1002"
|
|
|
|
// 简单 非等待响应模式, 使用 event driver
|
|
func TestEvent_DriverEventTest(t *testing.T) {
|
|
ctx := context.Background()
|
|
driver := NewDriver(500)
|
|
produce := NewProduce(driver)
|
|
consumer := NewConsumer(driver)
|
|
|
|
go produceEvent(t, ctx, produce)
|
|
consumerEvent(t, ctx, consumer)
|
|
}
|
|
|
|
func produceEvent(t *testing.T, ctx context.Context, v ProduceInterface) {
|
|
for i := 0; i < 100; i++ {
|
|
event := NewEvent(testEvent)
|
|
event.SetValue("test", i)
|
|
v.Call(ctx, event)
|
|
}
|
|
}
|
|
|
|
func consumerEvent(t *testing.T, ctx context.Context, v ConsumerInterface) {
|
|
for i := 0; i < 100; i++ {
|
|
event := v.Receive(ctx)
|
|
res, ok := event.GetValue("test")
|
|
require.True(t, ok)
|
|
fmt.Println(res)
|
|
require.Equal(t, res, i)
|
|
}
|
|
}
|
|
|
|
// 响应等待用法
|
|
func TestEvent_SpanWaitEvent(t *testing.T) {
|
|
ctx := context.Background()
|
|
driver := NewDriver(500)
|
|
produce := NewProduce(driver)
|
|
consumer := NewConsumer(driver)
|
|
|
|
go waitConsumer(t, ctx, consumer)
|
|
|
|
waitProduce(t, ctx, produce)
|
|
}
|
|
|
|
func waitProduce(t *testing.T, ctx context.Context, v ProduceInterface) {
|
|
for i := 0; i < 100; i++ {
|
|
event := NewEvent(waitTestEvent)
|
|
|
|
event.InitWaitEvent()
|
|
event.SetValue("test", i)
|
|
v.Call(ctx, event) // 推送给 consumer
|
|
res, err := event.StartWaitEvent(2 * time.Second) // 最多等待 consumer 回复 2s
|
|
require.NoError(t, err)
|
|
require.Equal(t, fmt.Sprintf("test:%v", i), res)
|
|
}
|
|
}
|
|
|
|
func waitConsumer(t *testing.T, ctx context.Context, v ConsumerInterface) {
|
|
for i := 0; i < 100; i++ {
|
|
event := v.Receive(ctx) // 接受 produce 的 event
|
|
res, ok := event.GetValue("test")
|
|
require.True(t, ok)
|
|
require.Equal(t, res, i)
|
|
|
|
// 发送返回值给 produce
|
|
event.ExecWorkAndSendResult(func() (interface{}, error) {
|
|
return fmt.Sprintf("test:%v", res), nil
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestEvent_SetResultErr(t *testing.T) {
|
|
ctx := context.Background()
|
|
event := NewEvent("dddd")
|
|
driver := NewDriver(100)
|
|
produce := NewProduce(driver)
|
|
consumer := NewConsumer(driver)
|
|
go func() {
|
|
event := consumer.Receive(ctx)
|
|
event.SetResultErr(errorx.New("err"))
|
|
}()
|
|
event.InitWaitEvent()
|
|
produce.Call(ctx, event)
|
|
_, err := event.StartWaitEvent(2 * time.Second)
|
|
fmt.Println(err)
|
|
require.Error(t, err)
|
|
}
|