2021-02-12 16:33:16 +03:00
|
|
|
package broker
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"testing"
|
2021-07-23 12:03:18 +03:00
|
|
|
|
2025-01-30 23:26:45 +03:00
|
|
|
"go.uber.org/atomic"
|
2025-01-25 15:48:10 +03:00
|
|
|
"go.unistack.org/micro/v4/broker"
|
2025-01-30 23:26:45 +03:00
|
|
|
"go.unistack.org/micro/v4/codec"
|
2025-01-25 15:48:10 +03:00
|
|
|
"go.unistack.org/micro/v4/metadata"
|
2021-02-12 16:33:16 +03:00
|
|
|
)
|
|
|
|
|
2025-01-30 23:26:45 +03:00
|
|
|
type hldr struct {
|
|
|
|
c atomic.Int64
|
|
|
|
}
|
2021-07-22 22:53:44 +03:00
|
|
|
|
2025-01-30 23:26:45 +03:00
|
|
|
func (h *hldr) Handler(m broker.Message) error {
|
|
|
|
h.c.Add(1)
|
|
|
|
return nil
|
2021-07-22 22:53:44 +03:00
|
|
|
}
|
2021-09-28 23:43:43 +03:00
|
|
|
|
2021-02-12 16:33:16 +03:00
|
|
|
func TestMemoryBroker(t *testing.T) {
|
2025-01-30 23:26:45 +03:00
|
|
|
b := NewBroker(broker.Codec("application/octet-stream", codec.NewCodec()))
|
2021-02-12 16:33:16 +03:00
|
|
|
ctx := context.Background()
|
|
|
|
|
2024-04-22 08:47:50 +03:00
|
|
|
if err := b.Init(); err != nil {
|
|
|
|
t.Fatalf("Unexpected init error %v", err)
|
|
|
|
}
|
|
|
|
|
2021-02-12 16:33:16 +03:00
|
|
|
if err := b.Connect(ctx); err != nil {
|
|
|
|
t.Fatalf("Unexpected connect error %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
topic := "test"
|
2025-01-30 23:26:45 +03:00
|
|
|
count := int64(10)
|
2021-02-12 16:33:16 +03:00
|
|
|
|
2025-01-30 23:26:45 +03:00
|
|
|
h := &hldr{}
|
2021-02-12 16:33:16 +03:00
|
|
|
|
2025-01-30 23:26:45 +03:00
|
|
|
sub, err := b.Subscribe(ctx, topic, h.Handler)
|
2021-02-12 16:33:16 +03:00
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("Unexpected error subscribing %v", err)
|
|
|
|
}
|
|
|
|
|
2025-01-30 23:26:45 +03:00
|
|
|
for i := int64(0); i < count; i++ {
|
|
|
|
message, err := b.NewMessage(ctx,
|
|
|
|
metadata.Pairs(
|
|
|
|
"foo", "bar",
|
|
|
|
"id", fmt.Sprintf("%d", i),
|
|
|
|
),
|
|
|
|
[]byte(`"hello world"`),
|
|
|
|
broker.PublishContentType("application/octet-stream"),
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
2021-02-12 16:33:16 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := b.Publish(ctx, topic, message); err != nil {
|
2021-07-22 22:53:44 +03:00
|
|
|
t.Fatalf("Unexpected error publishing %d err: %v", i, err)
|
2021-02-12 16:33:16 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := sub.Unsubscribe(ctx); err != nil {
|
|
|
|
t.Fatalf("Unexpected error unsubscribing from %s: %v", topic, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := b.Disconnect(ctx); err != nil {
|
|
|
|
t.Fatalf("Unexpected connect error %v", err)
|
|
|
|
}
|
2025-01-30 23:26:45 +03:00
|
|
|
|
|
|
|
if h.c.Load() != count {
|
|
|
|
t.Fatal("invalid messages count received")
|
|
|
|
}
|
2021-02-12 16:33:16 +03:00
|
|
|
}
|