boradcaster_test.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package broadcaster_test
  2. import (
  3. "context"
  4. "testing"
  5. "github.com/iwanhae/nodb/pkg/broadcaster"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestNewBroadcaster(t *testing.T) {
  9. b := broadcaster.New[int](50)
  10. if b == nil {
  11. t.Error("NewBroadcaster should not return nil")
  12. }
  13. chA := b.Subscribe()
  14. chB := b.Subscribe()
  15. ctx := context.Background()
  16. b.Publish(ctx, 1)
  17. b.Publish(ctx, 2)
  18. b.Publish(ctx, 3)
  19. idx := 1
  20. loopA:
  21. for {
  22. select {
  23. case val := <-chA:
  24. assert.Equal(t, idx, val)
  25. idx += 1
  26. default:
  27. break loopA
  28. }
  29. }
  30. idx = 1
  31. loopB:
  32. for {
  33. select {
  34. case val := <-chB:
  35. assert.Equal(t, idx, val)
  36. idx += 1
  37. default:
  38. break loopB
  39. }
  40. }
  41. }
  42. func TestNewBroadcaster_auto_close(t *testing.T) {
  43. b := broadcaster.New[int](50)
  44. if b == nil {
  45. t.Error("NewBroadcaster should not return nil")
  46. }
  47. ch := b.Subscribe()
  48. ctx := context.Background()
  49. for i := 0; i < 52; i++ {
  50. b.Publish(ctx, i)
  51. }
  52. for i := 0; i < 50; i++ {
  53. _, ok := <-ch
  54. assert.True(t, ok)
  55. }
  56. _, ok := <-ch
  57. assert.False(t, ok)
  58. }