...
1 package conc
2
3 import (
4 "fmt"
5 "sync/atomic"
6 "testing"
7
8 "github.com/stretchr/testify/require"
9 )
10
11 func ExampleWaitGroup() {
12 var count atomic.Int64
13
14 var wg WaitGroup
15 for i := 0; i < 10; i++ {
16 wg.Go(func() {
17 count.Add(1)
18 })
19 }
20 wg.Wait()
21
22 fmt.Println(count.Load())
23
24
25 }
26
27 func ExampleWaitGroup_WaitAndRecover() {
28 var wg WaitGroup
29
30 wg.Go(func() {
31 panic("super bad thing")
32 })
33
34 recoveredPanic := wg.WaitAndRecover()
35 fmt.Println(recoveredPanic.Value)
36
37
38 }
39
40 func TestWaitGroup(t *testing.T) {
41 t.Parallel()
42
43 t.Run("ctor", func(t *testing.T) {
44 t.Parallel()
45 wg := NewWaitGroup()
46 require.IsType(t, &WaitGroup{}, wg)
47 })
48
49 t.Run("all spawned run", func(t *testing.T) {
50 t.Parallel()
51 var count atomic.Int64
52 var wg WaitGroup
53 for i := 0; i < 100; i++ {
54 wg.Go(func() {
55 count.Add(1)
56 })
57 }
58 wg.Wait()
59 require.Equal(t, count.Load(), int64(100))
60 })
61
62 t.Run("panic", func(t *testing.T) {
63 t.Parallel()
64
65 t.Run("is propagated", func(t *testing.T) {
66 t.Parallel()
67 var wg WaitGroup
68 wg.Go(func() {
69 panic("super bad thing")
70 })
71 require.Panics(t, wg.Wait)
72 })
73
74 t.Run("one is propagated", func(t *testing.T) {
75 t.Parallel()
76 var wg WaitGroup
77 wg.Go(func() {
78 panic("super bad thing")
79 })
80 wg.Go(func() {
81 panic("super badder thing")
82 })
83 require.Panics(t, wg.Wait)
84 })
85
86 t.Run("non-panics do not overwrite panic", func(t *testing.T) {
87 t.Parallel()
88 var wg WaitGroup
89 wg.Go(func() {
90 panic("super bad thing")
91 })
92 for i := 0; i < 10; i++ {
93 wg.Go(func() {})
94 }
95 require.Panics(t, wg.Wait)
96 })
97
98 t.Run("non-panics run successfully", func(t *testing.T) {
99 t.Parallel()
100 var wg WaitGroup
101 var i atomic.Int64
102 wg.Go(func() {
103 i.Add(1)
104 })
105 wg.Go(func() {
106 panic("super bad thing")
107 })
108 wg.Go(func() {
109 i.Add(1)
110 })
111 require.Panics(t, wg.Wait)
112 require.Equal(t, int64(2), i.Load())
113 })
114
115 t.Run("is caught by waitandrecover", func(t *testing.T) {
116 t.Parallel()
117 var wg WaitGroup
118 wg.Go(func() {
119 panic("super bad thing")
120 })
121 p := wg.WaitAndRecover()
122 require.Equal(t, p.Value, "super bad thing")
123 })
124
125 t.Run("one is caught by waitandrecover", func(t *testing.T) {
126 t.Parallel()
127 var wg WaitGroup
128 wg.Go(func() {
129 panic("super bad thing")
130 })
131 wg.Go(func() {
132 panic("super badder thing")
133 })
134 p := wg.WaitAndRecover()
135 require.NotNil(t, p)
136 })
137
138 t.Run("nonpanics run successfully with waitandrecover", func(t *testing.T) {
139 t.Parallel()
140 var wg WaitGroup
141 var i atomic.Int64
142 wg.Go(func() {
143 i.Add(1)
144 })
145 wg.Go(func() {
146 panic("super bad thing")
147 })
148 wg.Go(func() {
149 i.Add(1)
150 })
151 p := wg.WaitAndRecover()
152 require.Equal(t, p.Value, "super bad thing")
153 require.Equal(t, int64(2), i.Load())
154 })
155 })
156 }
157
View as plain text