group_test.go 1.13 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package common

import (
	"sync"
	"testing"
	"time"
)

func TestWaitingGroup(t *testing.T) {
	nb := 60
	w := NewWaitingGroupMap()

	waitGroup := &sync.WaitGroup{} // test only
	waitGroup.Add(nb)

	// Spawn nb emitters waiting for (nb-1) other emitters
	for i := 0; i < nb; i++ {
		go func(i int) {
			// Add some virtual latency
			time.Sleep(time.Duration(i) * time.Millisecond)
			// Join the waitingGroupMap
Loïck Bonniot's avatar
Loïck Bonniot committed
22
			myChan, nbs, _ := w.Join("A")
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
			w.Broadcast("A", i)
			// Wait for other msg
			for m := range myChan {
				nbs = append(nbs, m)
				if len(nbs) == nb {
					break
				}
			}
			// Free the waitingGroupMap
			w.Unjoin("A", myChan)
			waitGroup.Done()
		}(i)
	}
	waitGroup.Wait() // test only, wait for test to fully happen
}

func TestCloseWaitingGroup(t *testing.T) {
	w := NewWaitingGroupMap()

	waitGroup := &sync.WaitGroup{} // test only
	waitGroup.Add(1)

	go func() {
Loïck Bonniot's avatar
Loïck Bonniot committed
46
		myChan, _, _ := w.Join("A")
47
		for range myChan {
48
49
50
51
52
53
54
55
56
57
			t.Fatal("Should not be here")
		}
		// No need to call Unjoin here: if we do, we will try to unjoin a unknown room
		waitGroup.Done()
	}()

	time.Sleep(10 * time.Millisecond)
	w.CloseAll()
	waitGroup.Wait()
}