edge/pkg/bus/testing/publish_subscribe.go

76 lines
1.3 KiB
Go
Raw Normal View History

2023-02-09 12:16:36 +01:00
package testing
import (
"context"
2023-11-28 16:35:49 +01:00
"fmt"
2023-02-09 12:16:36 +01:00
"sync"
"sync/atomic"
"testing"
"time"
"forge.cadoles.com/arcad/edge/pkg/bus"
"github.com/pkg/errors"
)
const (
2023-11-28 16:35:49 +01:00
testAddress bus.Address = "testAddress"
2023-02-09 12:16:36 +01:00
)
func TestPublishSubscribe(t *testing.T, b bus.Bus) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
t.Log("subscribe")
2023-11-28 16:35:49 +01:00
envelopes, err := b.Subscribe(ctx, testAddress)
2023-02-09 12:16:36 +01:00
if err != nil {
t.Fatal(errors.WithStack(err))
}
2023-11-28 16:35:49 +01:00
expectedTotal := 5
2023-02-09 12:16:36 +01:00
var wg sync.WaitGroup
2023-11-28 16:35:49 +01:00
wg.Add(expectedTotal)
2023-02-09 12:16:36 +01:00
go func() {
2023-11-28 16:35:49 +01:00
count := expectedTotal
2023-02-09 12:16:36 +01:00
2023-11-28 16:35:49 +01:00
for i := 0; i < count; i++ {
env := bus.NewEnvelope(testAddress, fmt.Sprintf("message %d", i))
2023-02-09 12:16:36 +01:00
2023-11-28 16:35:49 +01:00
if err := b.Publish(env); err != nil {
t.Error(errors.WithStack(err))
}
2023-02-09 12:16:36 +01:00
2023-11-28 16:35:49 +01:00
t.Logf("published %d", i)
2023-02-09 12:16:36 +01:00
}
}()
var count int32 = 0
go func() {
2023-11-28 16:35:49 +01:00
t.Log("range for received envelopes")
2023-02-09 12:16:36 +01:00
2023-11-28 16:35:49 +01:00
for env := range envelopes {
2023-02-09 12:16:36 +01:00
t.Logf("received msg %d", atomic.LoadInt32(&count))
atomic.AddInt32(&count, 1)
2023-11-28 16:35:49 +01:00
if e, g := testAddress, env.Address(); e != g {
t.Errorf("env.Address(): expected '%v', got '%v'", e, g)
2023-02-09 12:16:36 +01:00
}
wg.Done()
}
}()
wg.Wait()
2023-11-28 16:35:49 +01:00
b.Unsubscribe(testAddress, envelopes)
2023-02-09 12:16:36 +01:00
2023-11-28 16:35:49 +01:00
if e, g := int32(expectedTotal), count; e != g {
t.Errorf("envelopes received count: expected '%v', got '%v'", e, g)
2023-02-09 12:16:36 +01:00
}
}