File: pubsub_test.go

package info (click to toggle)
golang-github-anacrolix-missinggo 2.1.0-7
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 872 kB
  • sloc: makefile: 4
file content (74 lines) | stat: -rw-r--r-- 1,256 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package pubsub

import (
	"sync"
	"testing"

	"github.com/bradfitz/iter"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestDoubleClose(t *testing.T) {
	ps := NewPubSub()
	ps.Close()
	ps.Close()
}

func testBroadcast(t testing.TB, subs, vals int) {
	ps := NewPubSub()
	var wg sync.WaitGroup
	for range iter.N(subs) {
		wg.Add(1)
		s := ps.Subscribe()
		go func() {
			defer wg.Done()
			var e int
			for i := range s.Values {
				assert.Equal(t, e, i.(int))
				e++
			}
			assert.Equal(t, vals, e)
		}()
	}
	for i := range iter.N(vals) {
		ps.Publish(i)
	}
	ps.Close()
	wg.Wait()
}

func TestBroadcast(t *testing.T) {
	testBroadcast(t, 100, 10)
}

func BenchmarkBroadcast(b *testing.B) {
	for range iter.N(b.N) {
		testBroadcast(b, 10, 1000)
	}
}

func TestCloseSubscription(t *testing.T) {
	ps := NewPubSub()
	ps.Publish(1)
	s := ps.Subscribe()
	select {
	case <-s.Values:
		t.FailNow()
	default:
	}
	ps.Publish(2)
	s2 := ps.Subscribe()
	ps.Publish(3)
	require.Equal(t, 2, <-s.Values)
	require.EqualValues(t, 3, <-s.Values)
	s.Close()
	_, ok := <-s.Values
	require.False(t, ok)
	ps.Publish(4)
	ps.Close()
	require.Equal(t, 3, <-s2.Values)
	require.Equal(t, 4, <-s2.Values)
	require.Nil(t, <-s2.Values)
	s2.Close()
}