Files
gochat/backend/internal/pubsub/pubsub_test.go
T

108 lines
2.5 KiB
Go

package pubsub
import (
"context"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFormatTopic(t *testing.T) {
assert.Equal(t, "conversation.123", FormatTopic("conversation.%s", "123"))
assert.Equal(t, "account.5.message", FormatTopic("account.%s.message", "5"))
assert.Equal(t, "no_placeholder", FormatTopic("no_placeholder", "ignored"))
assert.Equal(t, "prefix.suffix", FormatTopic("prefix.%s", "suffix"))
assert.Equal(t, "", FormatTopic("", ""))
}
func TestInMemoryPubSub_Publish(t *testing.T) {
ps := NewInMemoryPubSub()
var received []Event
var mu sync.Mutex
err := ps.Subscribe(context.Background(), "test.topic", func(e Event) {
mu.Lock()
received = append(received, e)
mu.Unlock()
})
require.NoError(t, err)
err = ps.Publish(context.Background(), "test.topic", Event{
Type: "test",
AccountID: 1,
Payload: map[string]interface{}{"key": "value"},
})
require.NoError(t, err)
mu.Lock()
assert.Len(t, received, 1)
assert.Equal(t, "test", received[0].Type)
assert.Equal(t, uint(1), received[0].AccountID)
mu.Unlock()
}
func TestInMemoryPubSub_Publish_NoSubscribers(t *testing.T) {
ps := NewInMemoryPubSub()
err := ps.Publish(context.Background(), "no.subscribers", Event{Type: "test"})
require.NoError(t, err)
}
func TestInMemoryPubSub_MultipleSubscribers(t *testing.T) {
ps := NewInMemoryPubSub()
count := 0
var mu sync.Mutex
_ = ps.Subscribe(context.Background(), "topic", func(e Event) {
mu.Lock()
count++
mu.Unlock()
})
_ = ps.Subscribe(context.Background(), "topic", func(e Event) {
mu.Lock()
count++
mu.Unlock()
})
err := ps.Publish(context.Background(), "topic", Event{Type: "test"})
require.NoError(t, err)
mu.Lock()
assert.Equal(t, 2, count)
mu.Unlock()
}
func TestInMemoryPubSub_Unsubscribe(t *testing.T) {
ps := NewInMemoryPubSub()
count := 0
var mu sync.Mutex
_ = ps.Subscribe(context.Background(), "topic", func(e Event) {
mu.Lock()
count++
mu.Unlock()
})
err := ps.Unsubscribe(context.Background(), "topic")
require.NoError(t, err)
err = ps.Publish(context.Background(), "topic", Event{Type: "test"})
require.NoError(t, err)
mu.Lock()
assert.Equal(t, 0, count)
mu.Unlock()
}
func TestEvent_Struct(t *testing.T) {
e := Event{
Type: "message_created",
AccountID: 42,
Payload: map[string]interface{}{"message_id": float64(123)},
}
assert.Equal(t, "message_created", e.Type)
assert.Equal(t, uint(42), e.AccountID)
assert.Equal(t, float64(123), e.Payload["message_id"])
}