| 2 | 2 |
import (
|
| 3 | 3 |
"bytes"
|
| 4 | 4 |
"fmt"
|
|
5 |
"io/ioutil"
|
| 5 | 6 |
"math/rand"
|
| 6 | 7 |
"sync"
|
| 7 | 8 |
"testing"
|
|
| 66 | 67 |
func TestAddBar(t *testing.T) {
|
| 67 | 68 |
var wg sync.WaitGroup
|
| 68 | 69 |
var buf bytes.Buffer
|
| 69 | |
p := mpb.New(mpb.Output(&buf))
|
|
70 |
p := mpb.New(mpb.Output(&buf), mpb.WithWaitGroup(&wg))
|
| 70 | 71 |
|
| 71 | 72 |
count := p.BarCount()
|
| 72 | 73 |
if count != 0 {
|
|
| 78 | 79 |
|
| 79 | 80 |
for i := 0; i < numBars; i++ {
|
| 80 | 81 |
name := fmt.Sprintf("Bar#%d:", i)
|
| 81 | |
bar := p.AddBar(100, mpb.PrependDecorators(decor.Name(name, len(name), 0)))
|
|
82 |
bar := p.AddBar(100, mpb.PrependDecorators(decor.StaticName(name, len(name), 0)))
|
| 82 | 83 |
|
| 83 | 84 |
go func() {
|
| 84 | 85 |
defer wg.Done()
|
|
| 92 | 93 |
if count != numBars {
|
| 93 | 94 |
t.Errorf("BarCount want: %q, got: %q\n", numBars, count)
|
| 94 | 95 |
}
|
| 95 | |
wg.Wait()
|
| 96 | 96 |
p.Stop()
|
| 97 | 97 |
}
|
| 98 | 98 |
|
|
| 113 | 113 |
}
|
| 114 | 114 |
|
| 115 | 115 |
func TestWithCancel(t *testing.T) {
|
|
116 |
var wg sync.WaitGroup
|
| 116 | 117 |
cancel := make(chan struct{})
|
| 117 | 118 |
shutdown := make(chan struct{})
|
| 118 | |
p := mpb.New(mpb.WithCancel(cancel), mpb.WithShutdownNotifier(shutdown))
|
|
119 |
p := mpb.New(
|
|
120 |
mpb.Output(ioutil.Discard),
|
|
121 |
mpb.WithCancel(cancel),
|
|
122 |
mpb.WithShutdownNotifier(shutdown),
|
|
123 |
mpb.WithWaitGroup(&wg),
|
|
124 |
)
|
| 119 | 125 |
|
| 120 | |
var wg sync.WaitGroup
|
| 121 | 126 |
total := 100
|
| 122 | 127 |
numBars := 3
|
| 123 | 128 |
wg.Add(numBars)
|
|
| 125 | 130 |
for i := 0; i < numBars; i++ {
|
| 126 | 131 |
name := fmt.Sprintf("Bar#%d:", i)
|
| 127 | 132 |
bar := p.AddBar(int64(total), mpb.BarID(i),
|
| 128 | |
mpb.PrependDecorators(decor.Name(name, len(name), 0)))
|
|
133 |
mpb.PrependDecorators(decor.StaticName(name, len(name), 0)))
|
| 129 | 134 |
|
| 130 | 135 |
go func() {
|
| 131 | |
defer func() {
|
| 132 | |
// fmt.Printf("%s done\n", name)
|
| 133 | |
wg.Done()
|
| 134 | |
}()
|
|
136 |
defer wg.Done()
|
| 135 | 137 |
for i := 0; i < total; i++ {
|
| 136 | 138 |
select {
|
| 137 | 139 |
case <-cancel:
|
| 138 | 140 |
return
|
| 139 | 141 |
default:
|
| 140 | 142 |
}
|
| 141 | |
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
|
| 142 | |
bar.Incr(1)
|
|
143 |
time.Sleep(time.Duration(rand.Intn(10)+1) * time.Second / 100)
|
|
144 |
bar.Increment()
|
| 143 | 145 |
}
|
| 144 | 146 |
}()
|
| 145 | 147 |
}
|
|
| 148 | 150 |
close(cancel)
|
| 149 | 151 |
})
|
| 150 | 152 |
|
| 151 | |
wg.Wait()
|
| 152 | 153 |
p.Stop()
|
| 153 | 154 |
|
| 154 | 155 |
select {
|